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.
authenticateRequest() requires publishableKey to be set. You can set this value as an environment variable and then pass it to createClerkClient() so that it is passed to authenticateRequest().
authenticateRequest() requires publishableKey to be set. You should already have this set in your environment variables. clerkClient will infer the publishableKey from your environment variables.
function authenticateRequest(
request: Request,
options: AuthenticateRequestOptions,
): Promise<RequestState>- Name
request- Type
Request- Description
Requestobject
- 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 }).
- Name
-
apiUrl? - Type
string- Description
The Clerk Backend API endpoint. Defaults to
'https://api.clerk.com'.
- Name
-
audience? - Type
string | string[]- Description
A string or list of audiences. If passed, it is checked against the
audclaim in the token.
- Name
-
domain? - Type
string- Description
The domain of a satellite application in a multi-domain setup.
- Name
-
headerType? - Type
string | string[]- Description
A string or list of allowed header types. Defaults to
'JWT'.
- 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 Organization as active. If the route also matches the
personalAccountPatternsprop, 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 callingnotFound()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
organizationPatternprop, theorganizationPatternprop takes precedence. Examples:["/user",, "/user/(.*)"],["/user/:any",, "/user/:any/(.*)"].
- Name
-
publishableKey? - Type
string- Description
The Clerk Publishable Key from the API keys page in the Clerk Dashboard.
- Name
-
satelliteAutoSync? - Type
boolean- Description
Controls whether satellite apps automatically sync with the primary domain on initial page load. When
false(default), satellite apps will skip the automatic handshake if no session cookies exist, and only trigger the handshake after an explicit sign-in action. This provides the best performance by showing the satellite app immediately without attempting to sync state first. Whentrue, satellite apps will automatically trigger a handshake redirect to sync authentication state with the primary domain on first load, even if no session cookies exist. Use this if you want users who are already signed in on the primary domain to be automatically recognized on the satellite. Defaults tofalse.
- Name
-
secretKey? - Type
string- Description
The Clerk Secret Key from the API keys page in the Clerk Dashboard.
- Name
isAuthenticated- Type
boolean- Description
A boolean that indicates whether the incoming request is authenticated. Initially
false, becomestrueonce the request is authenticated.
- Name
isSignedIn(deprecated)- Type
boolean- Description
Deprecated. Use
isAuthenticatedinstead. Indicates whether the incoming request is authenticated.
- Name
status- Type
'signed-in' | 'signed-out' | 'handshake'- Description
The authentication state.
- Name
reason- Type
string | null- Description
The error code or reason for the current state. When there is a signed-in user, the value will be
null.
- Name
message- Type
string | null- Description
The full error message or additional context. When there is a signed-in user, the value will be
null.
- Name
tokenType- Type
'session_token' | 'oauth_token' | 'm2m_token' | 'api_key'- Description
The type of token.
- Name
token- Type
string- Description
The value of the token.
- Name
headers- Type
- Headers
- Description
A
Headersobject containing debug or status headers.
- Name
toAuth()- Type
function- Description
A function that returns the
Authobject. This JavaScript object contains important information like the current user's session ID, user ID, and Organization ID. Learn more about theAuthobject.
import { createClerkClient } from '@clerk/backend'
// Initialize clerkClient
const clerkClient = createClerkClient({
secretKey: process.env.CLERK_SECRET_KEY,
publishableKey: process.env.CLERK_PUBLISHABLE_KEY,
})
export async function GET(req: Request) {
// Use the `authenticateRequest()` method to verify the token
const { isAuthenticated } = await clerkClient.authenticateRequest(req, {
authorizedParties: ['https://example.com'],
})
// Protect the route from unauthenticated users
if (!isAuthenticated) {
return Response.json({ error: 'Unauthorized' }, { status: 401 })
}
// Add logic to perform protected actions
return Response.json({ message: 'This is a reply' })
}import { clerkClient } from '@clerk/nextjs/server'
export async function GET(req: Request) {
// Initialize clerkClient
const client = await clerkClient()
// Use the `authenticateRequest()` method to verify the token
const { isAuthenticated } = await client.authenticateRequest(req, {
authorizedParties: ['https://example.com'],
})
// Protect the route from unauthenticated users
if (!isAuthenticated) {
return Response.json({ error: 'Unauthorized' }, { status: 401 })
}
// Add logic to perform protected actions
return Response.json({ message: 'This is a reply' })
}import type { APIRoute } from 'astro'
import { clerkClient } from '@clerk/astro/server'
export const GET: APIRoute = async (context) => {
// Initialize clerkClient
// Use the `authenticateRequest()` method to verify the token
const { isAuthenticated } = await clerkClient(context).authenticateRequest(context.request, {
authorizedParties: ['https://example.com'],
})
// Protect the route from unauthenticated users
if (!isAuthenticated) {
return Response.json({ error: 'Unauthorized' }, { status: 401 })
}
// Add logic to perform protected actions
return Response.json({ message: 'This is a reply' })
}import { clerkClient } from '@clerk/express'
app.get('/example', async (req, res) => {
// Initialize clerkClient
// Use the `authenticateRequest()` method to verify the token
const { isAuthenticated } = await clerkClient.authenticateRequest(req, {
authorizedParties: ['https://example.com'],
})
// Protect the route from unauthenticated users
if (!isAuthenticated) {
return res.status(401).json({ error: 'User not authenticated' })
}
// Add logic to perform protected actions
return res.json({ message: 'This is a reply' })
})import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify'
import { clerkClient } from '@clerk/fastify'
export const exampleRoutes = (fastify: FastifyInstance) => {
fastify.get('/example', async (req: FastifyRequest, res: FastifyReply) => {
// Initialize clerkClient
// Use the `authenticateRequest()` method to verify the token
const { isAuthenticated } = await clerkClient.authenticateRequest(req, {
authorizedParties: ['https://example.com'],
})
// Protect the route from unauthenticated users
if (!isAuthenticated) {
return res.status(401).json({ error: 'User not authenticated' })
}
// Add logic to perform protected actions
return res.json({ message: 'This is a reply' })
})
}import { clerkClient } from '@clerk/nuxt/server'
export default defineEventHandler(async (event) => {
// Initialize clerkClient
// Use the `authenticateRequest()` method to verify the token
const { isAuthenticated } = await clerkClient(event).authenticateRequest(event.request, {
authorizedParties: ['https://example.com'],
})
// Protect the route from unauthenticated users
if (!isAuthenticated) {
throw createError({ statusCode: 401, statusMessage: 'User not authenticated' })
}
// Add logic to perform protected actions
return { message: 'This is a reply' }
})import { clerkClient } from '@clerk/react-router/server'
import type { Route } from './+types/example'
export async function loader(args: Route.LoaderArgs) {
// Initialize clerkClient
// Use the `authenticateRequest()` method to verify the token
const { isAuthenticated } = await clerkClient(args).authenticateRequest(args.request, {
authorizedParties: ['https://example.com'],
})
// Protect the route from unauthenticated users
if (!isAuthenticated) {
return redirect('/sign-in?redirect_url=' + args.request.url)
}
// Add logic to perform protected actions
return { message: 'This is a reply' }
}import { json } from '@tanstack/react-start'
import { createFileRoute } from '@tanstack/react-router'
import { clerkClient } from '@clerk/tanstack-react-start/server'
export const ServerRoute = createFileRoute('/api/example')({
server: {
handlers: {
GET: async ({ request }) => {
// Initialize clerkClient
// Use the `authenticateRequest()` method to verify the token
const { isAuthenticated } = await clerkClient().authenticateRequest(request, {
authorizedParties: ['https://example.com'],
})
// Protect the route from unauthenticated users
if (!isAuthenticated) {
return json({ error: 'Unauthorized' }, { status: 401 })
}
// Add logic to perform protected actions
return json({ message: 'This is a reply' })
},
},
},
})Machine authentication
By default, authenticateRequest() will authenticate a session request. To authenticate a machine request, you need to set the acceptsToken option to a machine token type, such as 'api_key', 'oauth_token' or 'm2m_token'.
import { createClerkClient } from '@clerk/backend'
// Initialize clerkClient
const clerkClient = createClerkClient({
secretKey: process.env.CLERK_SECRET_KEY,
publishableKey: process.env.CLERK_PUBLISHABLE_KEY,
})
export async function GET(request: Request) {
// Use the `authenticateRequest()` method to verify the token
const { isAuthenticated } = await clerkClient.authenticateRequest(request, {
acceptsToken: 'oauth_token',
})
// Protect the route from unauthenticated users
if (!isAuthenticated) {
return Response.json({ error: 'Unauthorized' }, { status: 401 })
}
// Add logic to perform protected actions
return Response.json({ message: 'This is a machine-to-machine reply' })
}import { clerkClient } from '@clerk/nextjs/server'
// Initialize clerkClient
const client = await clerkClient()
export async function GET(req: Request) {
// Use the `authenticateRequest()` method to verify the token
const { isAuthenticated } = await client.authenticateRequest(req, {
acceptsToken: 'oauth_token',
})
// Protect the route from unauthenticated users
if (!isAuthenticated) {
return Response.json({ error: 'Unauthorized' }, { status: 401 })
}
// Add logic to perform protected actions
return Response.json({ message: 'This is a machine-to-machine reply' })
}import type { APIRoute } from 'astro'
import { clerkClient } from '@clerk/astro/server'
export const GET: APIRoute = async (context) => {
// Initialize clerkClient
// Use the `authenticateRequest()` method to verify the token
const { isAuthenticated } = await clerkClient(context).authenticateRequest(context.request, {
authorizedParties: ['https://example.com'],
jwtKey: process.env.CLERK_JWT_KEY,
})
// Protect the route from unauthenticated users
if (!isAuthenticated) {
return Response.json({ error: 'Unauthorized' }, { status: 401 })
}
// Add logic to perform protected actions
return Response.json({ message: 'This is a machine-to-machine reply' })
}import { clerkClient } from '@clerk/express'
app.get('/example', async (req, res) => {
// Initialize clerkClient
// Use the `authenticateRequest()` method to verify the token
const { isAuthenticated } = await clerkClient.authenticateRequest(req, {
authorizedParties: ['https://example.com'],
jwtKey: process.env.CLERK_JWT_KEY,
})
// Protect the route from unauthenticated users
if (!isAuthenticated) {
return res.status(401).json({ error: 'User not authenticated' })
}
// Add logic to perform protected actions
return res.json({ message: 'This is a machine-to-machine reply' })
})import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify'
import { clerkClient } from '@clerk/fastify'
export const exampleRoutes = (fastify: FastifyInstance) => {
fastify.get('/example', async (req: FastifyRequest, res: FastifyReply) => {
// Initialize clerkClient
// Use the `authenticateRequest()` method to verify the token
const { isAuthenticated } = await clerkClient.authenticateRequest(req, {
authorizedParties: ['https://example.com'],
jwtKey: process.env.CLERK_JWT_KEY,
})
// Protect the route from unauthenticated users
if (!isAuthenticated) {
return res.status(401).json({ error: 'User not authenticated' })
}
// Add logic to perform protected actions
return res.json({ message: 'This is a machine-to-machine reply' })
})
}import { clerkClient } from '@clerk/nuxt/server'
export default defineEventHandler(async (event) => {
// Initialize clerkClient
// Use the `authenticateRequest()` method to verify the token
const { isAuthenticated } = await clerkClient(event).authenticateRequest(event.request, {
authorizedParties: ['https://example.com'],
jwtKey: process.env.CLERK_JWT_KEY,
})
// Protect the route from unauthenticated users
if (!isAuthenticated) {
throw createError({ statusCode: 401, statusMessage: 'User not authenticated' })
}
// Add logic to perform protected actions
return { message: 'This is a machine-to-machine reply' }
})import { clerkClient } from '@clerk/react-router/server'
import type { Route } from './+types/example'
import { redirect } from 'react-router'
export async function action(args: Route.ActionArgs) {
// Initialize clerkClient
// Use the `authenticateRequest()` method to verify the token
const { isAuthenticated } = await clerkClient(args).authenticateRequest(args.request, {
authorizedParties: ['https://example.com'],
jwtKey: process.env.CLERK_JWT_KEY,
})
// Protect the route by checking if the user is signed in
if (!isAuthenticated) {
return redirect('/sign-in?redirect_url=' + args.request.url)
}
// Add logic to perform protected actions
return Response.json({ message: 'This is a machine-to-machine reply' })
}import { json } from '@tanstack/react-start'
import { createFileRoute } from '@tanstack/react-router'
import { clerkClient } from '@clerk/tanstack-react-start/server'
export const ServerRoute = createFileRoute('/api/example')({
server: {
handlers: {
GET: async ({ request }) => {
// Initialize clerkClient
// Use the `authenticateRequest()` method to verify the token
const { isAuthenticated } = await clerkClient().authenticateRequest(request, {
authorizedParties: ['https://example.com'],
jwtKey: process.env.CLERK_JWT_KEY,
})
// Protect the route from unauthenticated users
if (!isAuthenticated) {
return json({ error: 'Unauthorized' }, { status: 401 })
}
// Add logic to perform protected actions
return json({ message: 'This is a machine-to-machine reply' })
},
},
},
})Networkless token verification
The following example uses the authenticateRequest() method with clerkClient 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'
// Initialize clerkClient
const clerkClient = createClerkClient({
secretKey: process.env.CLERK_SECRET_KEY,
publishableKey: process.env.CLERK_PUBLISHABLE_KEY,
})
export async function GET(req: Request) {
// Use the `authenticateRequest()` method to verify the token
const { isAuthenticated } = await clerkClient.authenticateRequest(req, {
authorizedParties: ['https://example.com'],
jwtKey: process.env.CLERK_JWT_KEY,
})
// Protect the route from unauthenticated users
if (!isAuthenticated) {
return Response.json({ error: 'Unauthorized' }, { status: 401 })
}
// Add logic to perform protected actions
return Response.json({ message: 'This is a reply' })
}import { clerkClient } from '@clerk/nextjs/server'
export async function GET(req: Request) {
// Initialize clerkClient
const client = await clerkClient()
// Use the `authenticateRequest()` method to verify the token
const { isAuthenticated } = await client.authenticateRequest(req, {
authorizedParties: ['https://example.com'],
jwtKey: process.env.CLERK_JWT_KEY,
})
// Protect the route from unauthenticated users
if (!isAuthenticated) {
return Response.json({ error: 'Unauthorized' }, { status: 401 })
}
// Add logic to perform protected actions
return Response.json({ message: 'This is a reply' })
}import { clerkClient } from '@clerk/astro/server'
import type { APIRoute } from 'astro'
export const GET: APIRoute = async (context) => {
// Initialize clerkClient
// Use the `authenticateRequest()` method to verify the token
const { isAuthenticated } = await clerkClient(context).authenticateRequest(context.request, {
authorizedParties: ['https://example.com'],
jwtKey: process.env.CLERK_JWT_KEY,
})
// Protect the route from unauthenticated users
if (!isAuthenticated) {
return Response.json({ error: 'Unauthorized' }, { status: 401 })
}
// Add logic to perform protected actions
return Response.json({ message: 'This is a reply' })
}import { clerkClient } from '@clerk/express'
import express from 'express'
const app = express()
app.get('/example', async (req, res) => {
// Initialize clerkClient
// Use the `authenticateRequest()` method to verify the token
const { isAuthenticated } = await clerkClient.authenticateRequest(req, {
authorizedParties: ['https://example.com'],
jwtKey: process.env.CLERK_JWT_KEY,
})
// Protect the route from unauthenticated users
if (!isAuthenticated) {
res.status(401).json({ error: 'User not authenticated' })
}
// Add logic to perform protected actions
return res.json({ message: 'This is a reply' })
})import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify'
import { clerkClient } from '@clerk/fastify'
export const exampleRoutes = (fastify: FastifyInstance) => {
fastify.get('/example', async (req: FastifyRequest, res: FastifyReply) => {
// Initialize clerkClient
// Use the `authenticateRequest()` method to verify the token
const { isAuthenticated } = await clerkClient.authenticateRequest(req, {
authorizedParties: ['https://example.com'],
jwtKey: process.env.CLERK_JWT_KEY,
})
// Protect the route from unauthenticated users
if (!isAuthenticated) {
return res.status(401).json({ error: 'User not authenticated' })
}
// Add logic to perform protected actions
return res.json({ message: 'This is a reply' })
})
}import { clerkClient } from '@clerk/nuxt/server'
export default defineEventHandler(async (event) => {
// Initialize clerkClient
// Use the `authenticateRequest()` method to verify the token
const { isAuthenticated } = await clerkClient(event).authenticateRequest(event.request, {
authorizedParties: ['https://example.com'],
jwtKey: process.env.CLERK_JWT_KEY,
})
// Protect the route from unauthenticated users
if (!isAuthenticated) {
return createError({ statusCode: 401, statusMessage: 'User not authenticated' })
}
// Add logic to perform protected actions
return { message: 'This is a reply' }
})import { redirect } from 'react-router'
import { clerkClient } from '@clerk/react-router/server'
import type { Route } from './+types/example'
export async function loader(args: Route.LoaderArgs) {
// Initialize clerkClient
// Use the `authenticateRequest()` method to verify the token
const { isAuthenticated } = await clerkClient(args).authenticateRequest(args.request, {
authorizedParties: ['https://example.com'],
jwtKey: process.env.CLERK_JWT_KEY,
})
// Protect the route from unauthenticated users
if (!isAuthenticated) {
return redirect('/sign-in?redirect_url=' + args.request.url)
}
// Add logic to perform protected actions
return { message: 'This is a reply' }
}import { createFileRoute } from '@tanstack/react-router'
import { clerkClient } from '@clerk/tanstack-react-start/server'
export const ServerRoute = createFileRoute('/api/example')({
server: {
handlers: {
GET: async ({ request }) => {
// Initialize clerkClient
// Use the `authenticateRequest()` method to verify the token
const { isAuthenticated } = await clerkClient().authenticateRequest(request, {
authorizedParties: ['https://example.com'],
jwtKey: process.env.CLERK_JWT_KEY,
})
// Protect the route from unauthenticated users
if (!isAuthenticated) {
return Response.json({ error: 'Unauthorized' }, { status: 401 })
}
// Add logic to perform protected actions
return Response.json({ message: 'This is a reply' })
},
},
},
})Feedback
Last updated on