Skip to main content

Quick Start

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

Configuration

The middleware accepts a VerifyAuthOptions object:
string
required
Your Logto server URL
string
required
The API resource identifier you registered in Logto
Custom cookie name if you changed it in the frontend
string
Require a specific scope to be present in the token
boolean
default:"false"
Allow unauthenticated users with guest context

Request Object

The middleware adds an auth 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 returns 401 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 available
2

Extract Token

Checks for token in cookies (logto_authtoken) then Authorization header
3

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

Store configuration in environment variables:
Use different middleware instances for different authorization levels:
Always check isAuthenticated when using allowGuest:
The full JWT payload is available in req.auth.payload:
The middleware automatically handles cookie parsing:
  • If req.cookies exists (already parsed), uses it directly
  • If not, applies cookie-parser middleware internally
  • No need to add cookie-parser to your app separately
While the middleware handles cookie parsing internally, you can still use cookie-parser globally if needed for other routes.

Next.js Integration

Server-side auth for Next.js

Generic Usage

Use in any Node.js environment