Authentication

AxilJS Auth Middleware for JWT Token Verification

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

3 min readDocumentationEdit this page

JWT Authentication Middleware

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
import { authenticate } from '@axiljs/auth'
 
app.get(
  '/profile',
  authenticate(jwt),
  (req, res) => {
    res.json(req.locals.user)
  }
)

For an authenticated request, the verified JWT payload is available through:

typescript
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
authenticate(jwt, {
  source: 'header'
})

The expected request format is:

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

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

typescript
authenticate(jwt, {
  source: 'query'
})

The corresponding request format is:

text
?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
authenticate(jwt, {
  source: ['header', 'cookie']
})

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

Optional Authentication

By default, authentication is required for a protected route.

You can make authentication optional with required: false.

typescript
authenticate(jwt, {
  required: false
})

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

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

text
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, the middleware can use the configured authentication sources to locate the token before verification.

Common Authentication Patterns

A required bearer-token route:

typescript
app.get(
  '/profile',
  authenticate(jwt, {
    source: 'header'
  }),
  profileHandler
)

A route supporting both headers and cookies:

typescript
app.get(
  '/profile',
  authenticate(jwt, {
    source: ['header', 'cookie']
  }),
  profileHandler
)

An endpoint with optional authentication:

typescript
app.get(
  '/content',
  authenticate(jwt, {
    required: false
  }),
  contentHandler
)

The same middleware can therefore support required authentication, optional authentication, and multiple token transport mechanisms.

Help improve the documentation

AxilJS is open source and documentation improvements are welcome.

AxilJS DocumentationMIT License · Built by SyntaxilitY