Skip to main content
Docs

authenticateRequest()

Authenticates a token passed from the frontend. Networkless if the jwtKey is provided. Otherwise, performs a network call to retrieve the JWKS from the Backend API.

function authenticateRequest(
  request: Request,
  options: AuthenticateRequestOptions,
): Promise<RequestState>
  • Name
    request
    Type
    Request
    Description

    Request object

  • Name
    options?
    Type
    AuthenticateRequestOptions
    Description

    Optional options to configure the authentication.

AuthenticateRequestOptions

It is recommended to set these options as environment variables where possible, and then pass them to the function. For example, you can set the secretKey option using the CLERK_SECRET_KEY environment variable, and then pass it to the function like this: createClerkClient({ secretKey: process.env.CLERK_SECRET_KEY }).

Warning

You must provide either jwtKey or secretKey.

For better security, it's highly recommended to explicitly set the authorizedParties option when authorizing requests. The value should be a list of domains that are allowed to make requests to your application. Not setting this value can open your application to CSRF attacks.

  • Name
    acceptsToken?
    Type
    "api_key" | "session_token" | "machine_token" | "oauth_token" | ("api_key" | "session_token" | "machine_token" | "oauth_token")[] | "any"
    Description

    The type of token to accept. Defaults to 'session_token'.

  • Name
    afterSignInUrl?
    Type
    string
    Description

    Full URL or path to navigate to after successful sign in. Defaults to '/'.

  • Name
    afterSignUpUrl?
    Type
    string
    Description

    Full URL or path to navigate to after successful sign up. Defaults to '/'.

  • Name
    apiUrl?
    Type
    string
    Description

    The Clerk Backend API endpoint. Defaults to 'https://api.clerk.com'.

  • Name
    apiVersion?
    Type
    string
    Description

    The version passed to the Clerk API. Defaults to 'v1'.

  • Name
    audience?
    Type
    string | string[]
    Description

    A string or list of audiences. If passed, it is checked against the aud claim in the token.

  • Name
    authorizedParties?
    Type
    string[]
    Description

    An allowlist of origins to verify against, to protect your application from the subdomain cookie leaking attack. Example: ['http://localhost:3000', 'https://example.com'].

  • Name
    clockSkewInMs?
    Type
    number
    Description

    Specifies the allowed time difference (in milliseconds) between the Clerk server (which generates the token) and the clock of the user's application server when validating a token. Defaults to 5000.

  • Name
    domain?
    Type
    string
    Description

    The domain of a satellite application in a multi-domain setup.

  • Name
    isSatellite?
    Type
    boolean
    Description

    Whether the instance is a satellite domain in a multi-domain setup. Defaults to false.

  • Name
    jwksCacheTtlInMs?
    Type
    number
    Description

    Deprecated. This cache TTL will be removed in the next major version. Specifying a cache TTL is a no-op.

  • Name
    jwtKey?
    Type
    string
    Description

    Used to verify the session token in a networkless manner. Supply the PEM public key from the API keys page -> Show JWT public key -> PEM Public Key section in the Clerk Dashboard. It's recommended to use the environment variable instead. For more information, refer to Manual JWT verification.

  • Name
    organizationSyncOptions?
    Type
    { organizationPatterns?: string[]; personalAccountPatterns?: string[]; }
    Description

    Used to activate a specific organization or personal account based on URL path parameters. If there's a mismatch between the active organization in the session (e.g., as reported by auth()) and the organization indicated by the URL, an attempt to activate the organization specified in the URL will be made. If the activation can't be performed, either because an organization doesn't exist or the user lacks access, the active organization in the session won't be changed. Ultimately, it's the responsibility of the page to verify that the resources are appropriate to render given the URL and handle mismatches appropriately (e.g., by returning a 404).

  • Name
    organizationSyncOptions.organizationPatterns?
    Type
    string[]
    Description

    Specifies URL patterns that are organization-specific, containing an organization ID or slug as a path parameter. If a request matches this path, the organization identifier will be used to set that org as active. If the route also matches the personalAccountPatterns prop, this prop takes precedence. Patterns must have a path parameter named either :id (to match a Clerk organization ID) or :slug (to match a Clerk organization slug). If the organization can't be activated—either because it doesn't exist or the user lacks access—the previously active organization will remain unchanged. Components must detect this case and provide an appropriate error and/or resolution pathway, such as calling notFound() or displaying an <OrganizationSwitcher />. Examples: ["/orgs/:slug",, "/orgs/:slug/(.*)"], ["/orgs/:id",, "/orgs/:id/(.*)"], ["/app/:any/orgs/:slug",, "/app/:any/orgs/:slug/(.*)"].

  • Name
    organizationSyncOptions.personalAccountPatterns?
    Type
    string[]
    Description

    URL patterns for resources that exist within the context of a Clerk Personal Account (user-specific, outside any organization). If the route also matches the organizationPattern prop, the organizationPattern prop takes precedence. Examples: ["/user",, "/user/(.*)"], ["/user/:any",, "/user/:any/(.*)"].

  • Name
    proxyUrl?
    Type
    string
    Description

    The proxy URL from a multi-domain setup.

  • Name
    publishableKey?
    Type
    string
    Description

    The Clerk Publishable Key from the API keys page in the Clerk Dashboard.

  • Name
    secretKey?
    Type
    string
    Description

    The Clerk Secret Key from the API keys page in the Clerk Dashboard.

  • Name
    signInUrl?
    Type
    string
    Description

    The sign-in URL from a multi-domain setup.

  • Name
    signUpUrl?
    Type
    string
    Description

    The sign-up URL from a multi-domain setup.

  • Name
    skipJwksCache?
    Type
    boolean
    Description

    A flag to ignore the JWKS cache and always fetch JWKS before each JWT verification.

If you are using the JavaScript Backend SDK on its own, you need to provide the secretKey and publishableKey to createClerkClient() so that it is passed to authenticateRequest(). You can set these values as environment variables and then pass them to the function.

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, {
    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' })
}

authenticateRequest() requires publishableKey to be set. If you are importing clerkClient from a higher-level SDK, such as Next.js, then clerkClient infers the publishableKey from your environment variables. The following example uses Next.js, but the same logic applies for other frameworks.

import { clerkClient } from '@clerk/nextjs/server'

const client = await clerkClient()

export async function GET(req: Request) {
  const { isSignedIn } = await client.authenticateRequest(req, {
    authorizedParties: ['https://example.com'],
  })

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

  // Perform protected actions
  // Add logic to perform protected actions

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

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.

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