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
import 'dotenv/config' // dotenv must be imported before @clerk/fastify
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' // dotenv must be imported before @clerk/fastify
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) => {
    // Use `getAuth()` to access `isAuthenticated` and the user's ID
    const { isAuthenticated, userId } = getAuth(req)
    // Protect the route from unauthenticated users
    if (!isAuthenticated) {
      return reply.code(403).send({ message: 'Access denied. Authentication required.' })
    }
    // Use `clerkClient` to access Clerk's JS Backend SDK methods
    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
- taskUrls?
- Type
- Record<SessionTask['key'], string>
- Description
- 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-organizationafter 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'
 
fastify.register(clerkPlugin, {
  hookName: 'preHandler',
})Feedback
Last updated on