getToken()
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.
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:
- Gets the current session ID using framework-specific auth helpers.
- Checks if there's an active session.
- Uses the
getToken()method to generate a token from a template. - Returns the token in the response.
The token resembles the following:
{
jwt: 'eyJhbG...'
}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 })
}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 })
}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 })
}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 })
}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 })
})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 })
})
}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
})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 })
}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
Last updated on