getToken()
Retrieves a token for a JWT 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
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 Backend SDK's
getToken()
method to generate a token from a template. - Returns the token in the response.
The token resembles the following:
{
jwt: 'eyJhbG...'
}
import { auth, clerkClient } from '@clerk/nextjs/server'
export async function GET() {
const { sessionId } = await auth()
if (!sessionId) {
return Response.json({ message: 'Unauthorized' }, { status: 401 })
}
const template = 'test'
const client = await clerkClient()
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)
if (!sessionId) {
return res.status(401).json({ error: 'Unauthorized' })
}
const template = 'test'
const client = await clerkClient()
const token = await client.sessions.getToken(sessionId, template)
return res.json({ token })
}
import { clerkClient } from '@clerk/express'
app.get('/api/get-token', async (req, res) => {
const sessionId = req.auth.sessionId
if (!sessionId) {
res.status(401).json({ error: 'Unauthorized' })
return
}
const template = 'test'
const token = await clerkClient.sessions.getToken(sessionId, template)
res.json({ token })
})
import { createClerkClient } from '@clerk/remix/api.server'
import { getAuth } from '@clerk/remix/ssr.server'
import { ActionFunction, json } from '@remix-run/node'
export const action: ActionFunction = async (req) => {
const { sessionId } = await getAuth(req)
const template = 'test'
const token = await createClerkClient({
secretKey: process.env.CLERK_SECRET_KEY,
}).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