The Clerk Fastify SDK provides a powerful set of tools and utilities to seamlessly integrate authentication, user management, and organization management into your Fastify application. Refer to the quickstart guide to get started.
The clerkPlugin() function is a Fastify plugin that integrates Clerk's authentication into your application. The function checks request cookies and headers for a session JWT. If valid, it attaches the Auth object to the request object under the auth key.
The URL paths users are redirected to after sign-up or sign-in when specific session tasks need to be completed. For example, { 'choose-organization': '/onboarding/choose-organization' } redirects users to /onboarding/choose-organization after sign-up if they need to choose an organization.
Name
hookName
Type
'onRequest' | 'preHandler'
Description
Determines which of Fastify's Request/Reply hooks Clerk should run. Default: 'preHandler'
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 get the user's IDconst { userId } =getAuth(request)// If user isn't authenticated, return a 401 errorif (!userId) {returnreply.code(401).send({ error:'User not authenticated' }) }// Use `clerkClient` to access Clerk's Backend SDK methods// and get the user's User objectconstuser= userId ?awaitclerkClient.users.getUser(userId) :nullreturnreply.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()
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) => {constauthObject=getAuth(req, { acceptsToken:'any' })if (authObject.tokenType ==='session_token') {console.log('this is session token from a user') } else {console.log('this is some other type of machine token')console.log('more specifically, a '+authObject.tokenType) }})