The getAuth() helper retrieves the current user's authentication state from the request object. It returns the Auth object. See the Next.js reference documentation for more examples on how to use the returned Auth object.
The following example uses getAuth() to protect a route and load the user's data. If the user is authenticated, their userId is passed to clerkClient.users.getUser()Clerk Icon to get the current user's UserJavaScript Icon object. If not authenticated, the request is rejected with a 401 status code.
// dotenv must be imported before @clerk/fastifyimport'dotenv/config'import Fastify from'fastify'import { clerkClient, clerkPlugin, getAuth } from'@clerk/fastify'constfastify=Fastify({ logger:true })fastify.register(clerkPlugin)// Use `getAuth()` to protect this routefastify.get('/protected',async (request, reply) => {try {// Use `getAuth()` to access `isAuthenticated` and the user's IDconst { isAuthenticated,userId } =getAuth(request)// If user isn't authenticated, return a 401 errorif (!isAuthenticated) {returnreply.code(401).send({ error:'User not authenticated' }) }// Use `clerkClient` to access Clerk's JS Backend SDK methods// and get the user's User objectconstuser=awaitclerkClient.users.getUser(userId)returnreply.send({ message:'User retrieved successfully', user, }) } catch (error) {fastify.log.error(error)returnreply.code(500).send({ error:'Failed to retrieve user' }) }})conststart=async () => {try {awaitfastify.listen({ port:8080 }) } catch (error) {fastify.log.error(error)process.exit(1) }}start()
For examples on how to use getAuth() to perform authorization checks, see the dedicated guide.
The following example uses getAuth() to protect the route based on token type:
It accepts any token type (acceptsToken: 'any') from the request.
If the token is a session_token, it logs that the request is from a user session.
Otherwise, it logs that the request uses a machine token and specifies its type.
import Fastify from'fastify'import { getAuth } from'@clerk/fastify'constfastify=Fastify()fastify.get('/path', (request, reply) => {// Use `getAuth()` to protect a route based on token typeconstauthObject=getAuth(req, { acceptsToken:'any' })if (authObject.tokenType ==='session_token') {console.log('This is a session token from a user') } else {console.log(`This is a ${authObject.tokenType} token`) }})