Skip to main content

Overview

The createExpressAuthMiddleware function creates an Express middleware that automatically verifies Logto authentication tokens and attaches authentication context to the request object.

Signature

Parameters

options
VerifyAuthOptions
required
Configuration options for token verification

Returns

middleware
ExpressMiddleware
Express middleware function that can be used with app.use() or route handlers

Request Enhancement

The middleware adds an auth property to the Express request object:

Examples

Basic Setup

Protected Routes Only

With Guest Support

With Required Scope

Error Handling

Behavior

Token Extraction

The middleware extracts tokens in this order:
  1. Cookie (using cookieName option, defaults to logto_authtoken)
  2. Authorization header (Bearer token)

Authentication Responses

When allowGuest: false (default):
  • No token found: Returns 401 with error message
  • Invalid token: Returns 401 with error details
  • Valid token: Attaches AuthContext to req.auth and calls next()
When allowGuest: true:
  • No token found: Attaches guest AuthContext to req.auth and calls next()
  • Invalid token: Attaches guest AuthContext to req.auth and calls next()
  • Valid token: Attaches authenticated AuthContext to req.auth and calls next()
The middleware automatically handles cookie parsing:
  • If cookies are not already parsed, it applies cookie-parser internally
  • No need to manually add cookie-parser middleware when using this middleware

TypeScript Support

Extend the Express request type to include the auth property:

See Also