Clerk Fastify SDK
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.
clerkPlugin()
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.
You can register the plugin for all routes or limit it to specific ones.
Example: Register clerkPlugin() for all routes
// dotenv must be imported before @clerk/fastify
import 'dotenv/config'
import Fastify from 'fastify'
import { clerkPlugin } from '@clerk/fastify'
const fastify = Fastify({ logger: true })
fastify.register(clerkPlugin)
const start = async () => {
  try {
    await fastify.listen({ port: 8080 })
  } catch (error) {
    fastify.log.error(error)
    process.exit(1)
  }
}
start()Example: Register clerkPlugin() for specific routes
To apply Clerk authentication only to specific routes, register the plugin in the scope of those routes.
In the following example, the application is split into protected and public routes:
import 'dotenv/config'
import Fastify, { FastifyPluginCallback } from 'fastify'
import { clerkClient, clerkPlugin, getAuth } from '@clerk/fastify'
const fastify = Fastify({ logger: true })
const protectedRoutes: FastifyPluginCallback = (instance, options, done) => {
  instance.register(clerkPlugin)
  instance.get('/protected', async (req, reply) => {
    const { userId } = getAuth(req)
    // Protect the route from unauthenticated users
    if (!userId) {
      return reply.code(403).send({ message: 'Access denied. Authentication required.' })
    }
    const user = await clerkClient.users.getUser(userId)
    // Only authenticated users will see the following message
    reply.send({ message: 'This is a protected route.', user })
  })
  done()
}
const publicRoutes: FastifyPluginCallback = (instance, options, done) => {
  instance.get('/', async (req, reply) => {
    reply.send({ message: 'This is a public route.' })
  })
  done()
}
fastify.register(protectedRoutes)
fastify.register(publicRoutes)
const start = async () => {
  try {
    await fastify.listen({ port: 8080 })
  } catch (error) {
    fastify.log.error(error)
    process.exit(1)
  }
}
start()clerkPlugin() options
The clerkPlugin() function accepts the following options:
- Name
 secretKey(required)- Type
 string- Description
 The Clerk Secret Key from the API keys page in the Clerk Dashboard.
- Name
 jwtKey?- Type
 string- Description
 The JWKS Public Key from the API keys in the Clerk Dashboard. For more information, refer to Manual JWT verification.
- Name
 publishableKey?- Type
 string- Description
 The Clerk Publishable Key from the API keys page in the Clerk Dashboard.
- Name
 domain?- Type
 string- Description
 The domain of a satellite application in a multi-domain setup.
- Name
 isSatellite?- Type
 boolean- Description
 Whether the instance is a satellite domain in a multi-domain setup. Defaults to
false.
- Name
 proxyUrl?- Type
 string- Description
 The proxy URL from a multi-domain setup.
- Name
 sdkMetadata?- Type
 { name: string, version: string }- Description
 Metadata about the SDK.
- Name
 telemetry?- Type
 { disabled: boolean, debug: boolean }- Description
 Telemetry configuration.
- Name
 userAgent?- Type
 string- Description
 The User-Agent request header passed to the Clerk API.
- Name
 apiUrl?- Type
 string- Description
 The Clerk Backend API endpoint. Defaults to
'https://api.clerk.com'.
- Name
 apiVersion?- Type
 string- Description
 The version passed to the Clerk API. Defaults to
'v1'.
- Name
 audience?- Type
 string | string[]- Description
 A string or list of audiences.
- Name
 hookName- Type
 'onRequest' | 'preHandler'- Description
 Determines which of Fastify's Request/Reply hooks Clerk should run. Default:
'preHandler'
fastify.register(clerkPlugin, {
  hookName: 'preHandler',
})getAuth()
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.
getAuth() options
- Name
 acceptsToken?- Type
 TokenType- Description
 The type of authentication token(s) to accept. Valid values are:
'session_token'- authenticates a user session.'oauth_token'- authenticates a machine request using OAuth.'machine_token'- authenticates a machine request.'api_key'- authenticates a machine request using API keys.
Can be set to:
- A single token type.
 - An array of token types.
 'any'to accept all available token types.
Defaults to
'session_token'.
Example: Use getAuth() to retrieve the userId
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() to get the current user's User object. If not authenticated, the request is rejected with a 401 status code.
// dotenv must be imported before @clerk/fastify
import 'dotenv/config'
import Fastify from 'fastify'
import { clerkClient, clerkPlugin, getAuth } from '@clerk/fastify'
const fastify = Fastify({ logger: true })
fastify.register(clerkPlugin)
// Use `getAuth()` to protect this route
fastify.get('/protected', async (request, reply) => {
  try {
    // Use `getAuth()` to get the user's ID
    const { userId } = getAuth(request)
    // If user isn't authenticated, return a 401 error
    if (!userId) {
      return reply.code(401).send({ error: 'User not authenticated' })
    }
    // Use `clerkClient` to access Clerk's Backend SDK methods
    // and get the user's User object
    const user = userId ? await clerkClient.users.getUser(userId) : null
    return reply.send({
      message: 'User retrieved successfully',
      user,
    })
  } catch (error) {
    fastify.log.error(error)
    return reply.code(500).send({ error: 'Failed to retrieve user' })
  }
})
const start = async () => {
  try {
    await fastify.listen({ port: 8080 })
  } catch (error) {
    fastify.log.error(error)
    process.exit(1)
  }
}
start()Example: Protecting a route by accepting and verifying multiple token types using getAuth()
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'
const fastify = Fastify()
fastify.get('/path', (request, reply) => {
  const authObject = 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)
  }
})Feedback
Last updated on