getToken()
Retrieves a token for a JWT Template that is defined in the Clerk Dashboard on the JWT Templates(opens in a new tab) page.
function getToken: (sessionId: string, template: string) => Promise<Token>;
Parameters
Name | Type | Description |
---|---|---|
sessionId | string | The ID of the session to retrieve a token for. |
template | string | The name of the JWT template from the Clerk Dashboard(opens in a new tab) to generate a new token from. For example: 'firebase', 'grafbase', or your custom template's name. |
Example
const sessionId = 'sess_123'; const template = 'test'; const response = await clerkClient.sessions.getToken(sessionId, template); console.log(response); /* _Token { jwt: 'eyJhbG...' } */
Examples with frameworks
app/api/get-token-example/route.tsimport { auth, clerkClient } from "@clerk/nextjs/server"; export async function GET() { const { sessionId } = auth(); if (!sessionId){ return Response.json({ message: "Unauthorized" }, { status: 401 }); } const template = 'test'; const token = await clerkClient.sessions.getToken(sessionId, template) return Response.json({ token }) }
pages/api/getToken.tsimport { 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 token = await clerkClient.sessions.getToken(sessionId, template); return res.json({ token }); }
getToken.tsimport { clerkClient } from '@clerk/clerk-sdk-node'; app.post('/api/get-token', // ClerkExpressRequireAuth returns an error for unauthorized requests ClerkExpressRequireAuth(), // Optionally ClerkExpressWithAuth returns an empty user with no error // ClerkExpressWithAuth(), async (req, res) => { const sessionId = req.auth.sessionId const template = 'test' const token = await clerkClient.sessions.getToken(sessionId, template) res.json({ token }) })
app/routes/get-token.tsimport { 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 }) }
Last updated on April 8, 2024