Protect a route
An Express endpoint should allow only signed-in users.
Clerk · Function
getAuth() reads Clerk authentication state from an Express request and returns an Auth object. Use it in route handlers to protect endpoints and inspect authentication, authorization, and token information.
In an Express route, getAuth() reads the authentication state prepared on the request by Clerk middleware. It returns an Auth object that lets the handler inspect whether the request is authenticated, identify the user, and apply authorization or token-type rules before producing a response.
getAuth(req, options?)| Name | Type | Description |
|---|---|---|
req | Request | The Express request object whose Clerk authentication state is read. |
options | GetAuthOptions | Optional configuration controlling accepted authentication token types and related behavior. |
An Auth object containing the request's authentication state, including properties such as isAuthenticated, userId, session ID, and Organization ID.
import express from 'express'
import { clerkMiddleware, getAuth } from '@clerk/express'
const app = express()
app.use(clerkMiddleware())
app.get('/protected', (req, res) => {
const { isAuthenticated, userId } = getAuth(req)
if (!isAuthenticated) {
res.status(401).json({ error: 'Unauthorized' })
return
}
res.json({ userId })
})
app.listen(3000)Configure Clerk middleware first, then read authentication state in the route and reject unauthenticated requests.
An Express endpoint should allow only signed-in users.
A handler needs the current user's identifier to load user-specific data.
An endpoint must distinguish user sessions from machine or OAuth requests.
A route needs to return different responses for unauthenticated and unauthorized callers.
getAuth() reads authentication state from the request object and returns an Auth object. A route can inspect isAuthenticated and userId to decide whether to return a 401 response or continue processing.
Follow-up: How would you accept OAuth tokens? Pass acceptsToken: 'oauth_token', or provide an array containing the token types the route permits.
Use clerkMiddleware() before the route handlers, then call getAuth(req) inside the route. If isAuthenticated is false, return a 401 response; otherwise use the returned userId to load application data.
Follow-up: What happens when middleware is omitted? getAuth() cannot read the request authentication state, because the middleware is responsible for preparing it.
The acceptsToken option controls which authentication token types are accepted. It can be one token type or an array, and the default is session_token.
Follow-up: Which token types can be configured? The documented choices include session_token, oauth_token, m2m_token, and api_key; 'any' is also supported in the SDK references.
clerkMiddleware()AuthclerkClient.users.getUser()isAuthenticateduserIdacceptsToken