Overview
ThecreateExpressAuthMiddleware function creates an Express middleware that automatically verifies Logto authentication tokens and attaches authentication context to the request object.
Signature
Parameters
Configuration options for token verification
Returns
Express middleware function that can be used with
app.use() or route handlersRequest Enhancement
The middleware adds anauth property to the Express request object:
Examples
Basic Setup
Protected Routes Only
With Guest Support
With Required Scope
Custom Cookie Name
Error Handling
Behavior
Token Extraction
The middleware extracts tokens in this order:- Cookie (using
cookieNameoption, defaults tologto_authtoken) - Authorization header (Bearer token)
Authentication Responses
WhenallowGuest: false (default):
- No token found: Returns 401 with error message
- Invalid token: Returns 401 with error details
- Valid token: Attaches
AuthContexttoreq.authand callsnext()
allowGuest: true:
- No token found: Attaches guest
AuthContexttoreq.authand callsnext() - Invalid token: Attaches guest
AuthContexttoreq.authand callsnext() - Valid token: Attaches authenticated
AuthContexttoreq.authand callsnext()
Cookie Parsing
The middleware automatically handles cookie parsing:- If cookies are not already parsed, it applies
cookie-parserinternally - No need to manually add
cookie-parsermiddleware when using this middleware
TypeScript Support
Extend the Express request type to include theauth property:
See Also
- verifyAuth - Generic verification function
- verifyNextAuth - Next.js authentication helper
- useAuth - React hook for client-side authentication