Skip to main content
Docs

verifyToken()

Warning

This is a lower-level method intended for more advanced use-cases. It's recommended to use authenticateRequest(), which fully authenticates a token passed from the request object.

function verifyToken(
  token: string,
  options: VerifyTokenOptions,
): Promise<JwtReturnType<JwtPayload, TokenVerificationError>>;

Verifies a Clerk-generated token signature. Networkless if the jwtKey is provided. Otherwise, performs a network call to retrieve the JWKS from the Backend API.

Parameters

  • Name
    token
    Type
    string
    Description

    The token to verify.

  • Name
    options
    Type
    VerifyTokenOptions
    Description

    Options for verifying the token.

Example

The following example demonstrates how to use the JavaScript Backend SDK to verify the token signature.

In the following example:

  1. The JWKS Public Key from the Clerk Dashboard is set in the environment variable CLERK_JWT_KEY.
  2. The session token is retrieved from the __session cookie or the Authorization header.
  3. The token is verified in a networkless manner by passing the jwtKey prop.
  4. The authorizedParties prop is passed to verify that the session token is generated from the expected frontend application.
  5. If the token is valid, the response contains the verified token.
import { verifyToken } from "@clerk/backend";
import { cookies } from "next/headers";

export async function GET(request: Request) {
  const cookieStore = cookies();
  const sessToken = cookieStore.get("__session")?.value;
  const bearerToken = request.headers
    .get("Authorization")
    ?.replace("Bearer ", "");
  const token = sessToken || bearerToken;

  if (!token) {
    return Response.json(
      { error: "Token not found. User must sign in." },
      { status: 401 },
    );
  }

  try {
    const verifiedToken = await verifyToken(token, {
      jwtKey: process.env.CLERK_JWT_KEY,
      authorizedParties: ["http://localhost:3001", "api.example.com"], // Replace with your authorized parties
    });

    return Response.json({ verifiedToken });
  } catch (error) {
    return Response.json({ error: "Token not verified." }, { status: 401 });
  }
}

If the token is valid, the response will contain a JSON object that looks something like this:

{
  "verifiedToken": {
    "azp": "http://localhost:3000",
    "exp": 1687906422,
    "iat": 1687906362,
    "iss": "https://magical-marmoset-51.clerk.accounts.dev",
    "nbf": 1687906352,
    "sid": "sess_2Ro7e2IxrffdqBboq8KfB6eGbIy",
    "sub": "user_2RfWKJREkjKbHZy0Wqa5qrHeAnb"
  }
}

Feedback

What did you think of this content?

Last updated on