JWT Authentication Middleware
Protect AxilJS routes with JWT authentication middleware, extract bearer tokens from headers, cookies, or query parameters, and support optional authentication.
On this page12
AxilJS provides the authenticate middleware for extracting and verifying JWT tokens from incoming HTTP requests.
The middleware uses an AxilJS JWT instance to validate authentication tokens and makes the authenticated user information available through req.locals.user.
It can read tokens from request headers, cookies, query parameters, or multiple sources.
Protect a Route
Pass your JWT instance to authenticate() to protect an HTTP route.
1import { authenticate } from '@axiljs/auth'
2
3app.get(
4 '/profile',
5 authenticate(jwt),
6 (req, res) => {
7 res.json(req.locals.user)
8 }
9)For an authenticated request, the verified JWT payload is available through:
req.locals.userThis allows route handlers to access the authenticated user's claims after successful token verification.
Token Sources
AxilJS supports multiple JWT token sources.
Authorization Header
Use the header source to extract a bearer token from the Authorization header.
authenticate(jwt, {
source: 'header'
})The expected request format is:
Authorization: Bearer <token>This is the conventional approach for APIs where clients send JWTs using HTTP authorization headers.
Cookie
Use the cookie source to read the token from a cookie named token (change it with cookieName).
authenticate(jwt, {
source: 'cookie'
})The middleware expects the JWT to be provided through the token cookie.
Query Parameter
Use the query source to extract the JWT from the token query parameter (change it with queryParam).
authenticate(jwt, {
source: 'query'
})The corresponding request format is:
?token=<token>Query-string authentication should generally be used only when the application's transport or integration requirements make it necessary, because URLs can be recorded by infrastructure such as logs and proxies.
Multiple Token Sources
You can configure more than one token source by providing an array.
authenticate(jwt, {
source: ['header', 'cookie']
})This allows the middleware to support authentication tokens from both the Authorization header and the token cookie.
Options
| Option | Default | Description |
|---|---|---|
required | true | When false, requests without a token continue with no user |
source | 'header' | 'header', 'cookie', 'query', or an array tried in order |
cookieName | 'token' | Cookie read by the cookie source |
queryParam | 'token' | Query parameter read by the query source |
audience | none | Expected audience, passed to jwt.verify() |
issuer | none | Expected issuer, passed to jwt.verify() |
1authenticate(jwt, {
2 source: ['header', 'cookie'],
3 cookieName: 'session',
4 audience: 'api',
5 issuer: 'auth.example.com'
6})Optional Authentication
By default, authentication is required for a protected route.
You can make authentication optional with required: false.
authenticate(jwt, {
required: false
})With optional authentication, unauthenticated requests are allowed to continue and:
req.locals.useris undefined when no authenticated user is available.
This is useful for endpoints that provide different behavior for authenticated and unauthenticated users.
Authentication Flow
The middleware can be understood as the following request flow:
When multiple sources are configured, they are tried in the order given and the first token found is verified. A missing token (when required) or an invalid token is passed to next() as an UnauthorizedError, which the error handler turns into a 401.
On success, req.locals.user is the JWT payload plus id (copied from sub).
Marker for tools
Since 0.4.0 the middleware returned by authenticate(), requireRole(), requirePermission() and requireOwnership() is marked with Symbol.for('axiljs.auth'), exported as AUTH_MIDDLEWARE. The marker is a non-enumerable property whose value names the factory ('authenticate', 'requireRole', …), so tools can recognise protected routes without depending on @axiljs/auth. generateOpenAPI() uses it to add the bearer security requirement and the 401 and 403 responses to those routes.
1import { AUTH_MIDDLEWARE, authenticate, markAuth } from '@axiljs/auth'
2
3const mw = authenticate(jwt)
4(mw as any)[AUTH_MIDDLEWARE] // 'authenticate'
5
6// Mark your own auth middleware the same way
7const requireApiKey = markAuth((req, res, next) => { /* ... */ }, 'apiKey')The marker does not change how the middleware behaves. An optional authenticate(jwt, { required: false }) carries it too.
Reading the User
1import { getUser } from '@axiljs/auth'
2
3app.get('/me', authenticate(jwt), (req, res) => {
4 const user = getUser(req) // throws UnauthorizedError when not authenticated
5 res.success(user)
6})Common Authentication Patterns
A required bearer-token route:
1app.get(
2 '/profile',
3 authenticate(jwt, {
4 source: 'header'
5 }),
6 profileHandler
7)A route supporting both headers and cookies:
1app.get(
2 '/profile',
3 authenticate(jwt, {
4 source: ['header', 'cookie']
5 }),
6 profileHandler
7)An endpoint with optional authentication:
1app.get(
2 '/content',
3 authenticate(jwt, {
4 required: false
5 }),
6 contentHandler
7)The same middleware can therefore support required authentication, optional authentication, and multiple token transport mechanisms.
Was this page helpful?