Skip to main content
Docs

Clerk Fastify SDK

The Clerk Fastify SDK is the recommended method for integrating Clerk 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:

index.ts
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 (request, reply) => {
    const { userId } = getAuth(request)

    // 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 (request, 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 PEM public key from the API keys page -> Show JWT public key -> PEM Public Key section 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.

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()

Feedback

What did you think of this content?

Last updated on