Quick Start
ThecreateExpressAuthMiddleware function creates an Express middleware that automatically verifies Logto tokens and attaches user information to the request object.
Configuration
The middleware accepts aVerifyAuthOptions object:
Your Logto server URL
The API resource identifier you registered in Logto
Custom cookie name if you changed it in the frontend
Require a specific scope to be present in the token
Allow unauthenticated users with guest context
Request Object
The middleware adds anauth property to the Express request:
Usage Examples
Basic Protected Route
Route with Required Scope
Multiple Middleware
Use different authentication requirements for different routes:Guest Mode
Allow both authenticated and guest users:TypeScript Usage
Error Responses
The middleware returns401 Unauthorized for authentication failures:
Missing Token
Invalid Token
Missing Scope
When
allowGuest: true, the middleware never returns 401 errors. Instead, it sets req.auth with guest context.How It Works
The middleware performs these steps on each request:1
Parse Cookies
Automatically parses cookies using
cookie-parser if not already available2
Extract Token
Checks for token in cookies (
logto_authtoken) then Authorization header3
Verify Token
- Fetches JWKS from Logto server (cached for 5 minutes)
- Verifies JWT signature using the appropriate public key
- Validates issuer, audience, expiration, and scopes
4
Set Auth Context
Attaches
AuthContext to req.auth and calls next()5
Handle Errors
Returns 401 JSON response or guest context (if
allowGuest enabled)Best Practices
Environment Variables
Environment Variables
Store configuration in environment variables:
Check Authentication Status
Check Authentication Status
Always check
isAuthenticated when using allowGuest:Access JWT Payload
Access JWT Payload
The full JWT payload is available in
req.auth.payload:Cookie Parsing
The middleware automatically handles cookie parsing:- If
req.cookiesexists (already parsed), uses it directly - If not, applies
cookie-parsermiddleware internally - No need to add
cookie-parserto your app separately
Related
Next.js Integration
Server-side auth for Next.js
Generic Usage
Use in any Node.js environment