Docs

Manual JWT verification

Your Clerk-generated session tokens are essentially JWTs which are signed using your instance's private key and can be verified using your instance's public key. Depending on your architecture, these tokens will be in your backend requests either via a cookie named __session or via the Authorization header.

For every request, you must validate its token to make sure it hasn't expired and it is authentic (i.e. no malicious user tried to tamper with it). If these validations pass, then it means that the user is authenticated to your application and you should consider them signed in.

The authenticateRequest() method from the JavaScript Backend SDK does all of this for you. It accepts the request object and authenticates the session token in it. See the reference page for more information.

Networkless token verification

The following example uses the authenticateRequest() method with the JavaScript Backend SDK to verify the token passed by the frontend, and performs a networkless authentication by passing jwtKey. This will verify if the user is signed into the application or not. For more information, like using the method with higher-level SDK's, see the authenticateRequest() reference.

import { createClerkClient } from '@clerk/backend'

export async function GET(req: Request) {
  const clerkClient = createClerkClient({
    secretKey: process.env.CLERK_SECRET_KEY,
    publishableKey: process.env.CLERK_PUBLISHABLE_KEY,
  })

  const { isSignedIn } = await clerkClient.authenticateRequest(req, {
    jwtKey: process.env.CLERK_JWT_KEY,
    authorizedParties: ['https://example.com'],
  })

  if (!isSignedIn) {
    return Response.json({ status: 401 })
  }

  // Add logic to perform protected actions

  return Response.json({ message: 'This is a reply' })
}

Feedback

What did you think of this content?

Last updated on