Docs

You are viewing an archived version of the docs.Go to latest version

getToken()

Retrieves a token for a JWT Template that is defined in the Clerk Dashboard on the JWT Templates page.

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

console.log(response);
/*
_Token {
  jwt: 'eyJhbG...'
}
*/
app/api/get-token-example/route.ts
import { 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.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);

  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.ts
import { 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.ts
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 })
}

Feedback

What did you think of this content?

Last updated on