Skip to main content
Docs

Retrieves a session token or generate a JWT using a specified template that is defined on the JWT templates page in the Clerk Dashboard.

function getToken(sessionId: string, template: string): Promise<Token>
  • Name
    sessionId
    Type
    string
    Description

    The ID of the session to retrieve a token for.

  • Name
    expiresInSeconds?
    Type
    number
    Description

    The expiration time for the token in seconds. If not provided, uses the default expiration time for the JWT template.

  • Name
    template?
    Type
    string
    Description

    The name of the JWT template from the Clerk Dashboard to generate a new token from. For example: 'firebase', 'grafbase', or your custom template's name.

Note

Using clerkClient varies based on the SDK you're using. Refer to the overview for usage details, including guidance on how to access the userId and other properties.

const sessionId = 'sess_123'

const template = 'test'

const response = await clerkClient.sessions.getToken(sessionId, template)

Examples with frameworks

The following examples demonstrate how to use getToken() with different frameworks. Each example performs the following steps:

  1. Gets the current session ID using framework-specific auth helpers.
  2. Checks if there's an active session.
  3. Uses the getToken() method to generate a token from a template.
  4. Returns the token in the response.

The token resembles the following:

{
  jwt: 'eyJhbG...'
}

Note

For these examples to work, you must have a JWT template named "test" in the Clerk Dashboard before running the code.

import { createClerkClient } from '@clerk/backend'

// Initialize clerkClient
const clerkClient = createClerkClient({
  secretKey: process.env.CLERK_SECRET_KEY,
})

export async function GET(req: Request) {
  const { sessionId } = req.auth

  // Protect the route from unauthenticated users
  if (!sessionId) {
    return Response.json({ error: 'Unauthorized' }, { status: 401 })
  }

  // Set the template name (optional)
  const template = 'test'

  // Use the `getToken()` method to generate a token from a template
  const token = await clerkClient.sessions.getToken(sessionId, template)

  return Response.json({ token })
}
app/api/get-token-example/route.ts
import { auth, clerkClient } from '@clerk/nextjs/server'

export async function GET() {
  const { sessionId } = await auth()

  // Protect the route from unauthenticated users
  if (!sessionId) {
    return Response.json({ message: 'Unauthorized' }, { status: 401 })
  }

  // Set the template name (optional)
  const template = 'test'

  // Initialize clerkClient
  const client = await clerkClient()

  // Use the `getToken()` method to generate a token from a template
  const token = await client.sessions.getToken(sessionId, template)

  return Response.json({ token })
}
pages/api/getToken.ts
import { clerkClient, getAuth } from '@clerk/nextjs/server'
import type { NextApiRequest, NextApiResponse } from 'next'

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
  const { sessionId } = getAuth(req)

  // Protect the route from unauthenticated users
  if (!sessionId) {
    return res.status(401).json({ error: 'Unauthorized' })
  }

  // Set the template name (optional)
  const template = 'test'

  // Initialize clerkClient
  const client = await clerkClient()

  // Use the `getToken()` method to generate a token from a template
  const token = await client.sessions.getToken(sessionId, template)

  return res.json({ token })
}
src/api/example.ts
import { clerkClient } from '@clerk/astro/server'
import type { APIRoute } from 'astro'

export const GET: APIRoute = async (context) => {
  const { sessionId } = context.locals.auth()

  // Protect the route from unauthenticated users
  if (!sessionId) {
    return Response.json({ error: 'Unauthorized' }, { status: 401 })
  }

  // Set the template name (optional)
  const template = 'test'

  // Initialize clerkClient
  // Use the `getToken()` method to generate a token from a template
  const token = await clerkClient(context).sessions.getToken(sessionId, template)

  return Response.json({ token })
}
getToken.ts
import { clerkClient } from '@clerk/express'

app.get('/api/get-token', async (req, res) => {
  const sessionId = req.auth.sessionId

  // Protect the route from unauthenticated users
  if (!sessionId) {
    res.status(401).json({ error: 'Unauthorized' })
    return
  }

  // Set the template name (optional)
  const template = 'test'

  // Initialize clerkClient
  // Use the `getToken()` method to generate a token from a template
  const token = await clerkClient.sessions.getToken(sessionId, template)

  res.json({ token })
})
src/routes/example.ts
import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify'
import { clerkClient } from '@clerk/fastify'

export const exampleRoutes = (fastify: FastifyInstance) => {
  fastify.get('/get-token', async (req: FastifyRequest, res: FastifyReply) => {
    const { sessionId } = req.auth

    // Protect the route from unauthenticated users
    if (!sessionId) {
      res.status(401).json({ error: 'User not authenticated' })
    }

    // Set the template name (optional)
    const template = 'test'

    // Initialize clerkClient
    // Use the `getToken()` method to generate a token from a template
    const token = await clerkClient.sessions.getToken(sessionId, template)

    res.json({ token })
  })
}
server/api/example.ts
import { clerkClient } from '@clerk/nuxt/server'

export default defineEventHandler(async (event) => {
  const sessionId = event.context.auth().sessionId

  // Protect the route from unauthenticated users
  if (!sessionId) {
    throw createError({ statusCode: 401, statusMessage: 'User not authenticated' })
  }

  // Set the template name (optional)
  const template = 'test'

  // Initialize clerkClient
  // Use the `getToken()` method to generate a token from a template
  const token = await clerkClient(event).sessions.getToken(sessionId, template)

  return token
})
app/routes/example.tsx
import { clerkClient, getAuth } from '@clerk/react-router/server'
import type { Route } from './+types/example'

export async function loader(args: Route.LoaderArgs) {
  const { sessionId } = await getAuth(args)

  // Protect the route from unauthenticated users
  if (!sessionId) {
    return new Response('User not authenticated', {
      status: 401,
    })
  }

  // Set the template name (optional)
  const template = 'test'

  // Initialize clerkClient
  // Use the `getToken()` method to generate a token from a template
  const token = await clerkClient(args).sessions.getToken(sessionId, template)

  return Response.json({ token })
}
app/routes/api/example.tsx
import { json } from '@tanstack/react-start'
import { createFileRoute } from '@tanstack/react-router'
import { auth, clerkClient } from '@clerk/tanstack-react-start/server'

export const ServerRoute = createFileRoute('/api/example')({
  server: {
    handlers: {
      GET: async () => {
        const { sessionId } = await auth()

        // Protect the route from unauthenticated users
        if (!sessionId) {
          return new Response('User not authenticated', {
            status: 401,
          })
        }

        // Set the template name (optional)
        const template = 'test'

        // Use the `getToken()` method to generate a token from a template
        const token = await clerkClient().sessions.getToken(sessionId, template)

        return json({ token })
      },
    },
  },
})

Backend API (BAPI) endpoint

This method in the SDK is a wrapper around the BAPI endpoint POST/sessions/{session_id}/tokens/{template_name}. See the BAPI reference for more information.

Feedback

What did you think of this content?

Last updated on