Initialize request authentication context
An Express application needs Clerk authentication state available to route handlers.
Clerk · Function
Clerk's Express clerkMiddleware() reads request cookies and headers for a session JWT and, when present, attaches an Auth object to req.auth. Register it before other middleware, then use getAuth() in routes to apply access decisions.
In Express, clerkMiddleware() examines request cookies and headers for a session JWT. When one is present, it adds Clerk's Auth object to req.auth; routes can then use getAuth() to make authentication or authorization decisions. Register it before other middleware so downstream handlers can access the authentication state.
clerkMiddleware(options?)| Name | Type | Description |
|---|---|---|
options | ClerkMiddlewareOptions | Optional configuration object controlling clerkMiddleware() behavior, including documented middleware options. |
Express middleware that processes Clerk authentication state for incoming requests.
import { clerkMiddleware, getAuth } from '@clerk/express'
import express from 'express'
const app = express()
app.use(clerkMiddleware())
app.get('/protected', (req, res) => {
const { isAuthenticated } = getAuth(req)
if (!isAuthenticated) return res.status(401).send('Unauthorized')
res.send('Protected response')
})
app.listen(3000)Install and configure the Clerk Express SDK, then start the server and request /protected while signed in or out to observe the authentication check.
An Express application needs Clerk authentication state available to route handlers.
A route should return its own response for signed-out requests.
Downstream handlers need access to the current Clerk Auth object.
clerkMiddleware() checks request cookies and headers for a session JWT. If it finds one, it attaches the Auth object to req.auth.
Follow-up: How would you enforce access to a route? Use getAuth(req) in the route and return an unauthenticated response when the authentication state does not satisfy the route's requirement.
Call app.use(clerkMiddleware()) before registering other middleware or routes. This ordering ensures downstream request handlers can use the authentication information.
Follow-up: What is the consequence of registering it later? Earlier middleware cannot rely on Clerk's request authentication state because Clerk has not yet processed the request.
The middleware supplies authentication state but leaves routes public by default. Use getAuth() with route-specific logic to decide whether a request is allowed.
Follow-up: Why use getAuth() alongside the middleware? It lets each route keep control over the response for unauthenticated or unauthorized requests.
getAuthAuth@clerk/express