Authentication

JWT Authentication Middleware

Protect AxilJS routes with JWT authentication middleware, extract bearer tokens from headers, cookies, or query parameters, and support optional authentication.

4 min readUpdated DocumentationEdit this page
On this page11

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.

TypeScript
TS
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:

TypeScript
TS
req.locals.user

This 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.

TypeScript
TS
authenticate(jwt, {
  source: 'header'
})

The expected request format is:

Output
TXT
Authorization: Bearer <token>

This is the conventional approach for APIs where clients send JWTs using HTTP authorization headers.

Use the cookie source to read the token from a cookie named token (change it with cookieName).

TypeScript
TS
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).

TypeScript
TS
authenticate(jwt, {
  source: 'query'
})

The corresponding request format is:

Output
TXT
?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.

TypeScript
TS
authenticate(jwt, {
  source: ['header', 'cookie']
})

This allows the middleware to support authentication tokens from both the Authorization header and the token cookie.

Options

OptionDefaultDescription
requiredtrueWhen 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
audiencenoneExpected audience, passed to jwt.verify()
issuernoneExpected issuer, passed to jwt.verify()
TypeScript
TS
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.

TypeScript
TS
authenticate(jwt, {
  required: false
})

With optional authentication, unauthenticated requests are allowed to continue and:

TypeScript
TS
req.locals.user

is 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:

HTTP Request
authenticate(jwt)
Extract JWT (header / cookie / query)
JWT Verification
Valid
req.locals.user
Route Handler
Invalid
Authentication Failure

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).

Reading the User

TypeScript
TS
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:

TypeScript
TS
1app.get(
2  '/profile',
3  authenticate(jwt, {
4    source: 'header'
5  }),
6  profileHandler
7)

A route supporting both headers and cookies:

TypeScript
TS
1app.get(
2  '/profile',
3  authenticate(jwt, {
4    source: ['header', 'cookie']
5  }),
6  profileHandler
7)

An endpoint with optional authentication:

TypeScript
TS
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?

Help improve the documentation

AxilJS is open source and documentation improvements are welcome.

AxilJS DocumentationMIT License · Built by SyntaxilitY