Token Management
next-api-layer handles JWT token management automatically, including validation, refresh, and caching.
Overview#
The library manages three key token operations:
- Validation: Checking if a token is valid
- Refresh: Automatically refreshing expired tokens
- Caching: Reducing backend calls with smart caching
Token Validation#
Every request triggers token validation through your backend's validate endpoint:
Expected Response Format#
Your backend's /auth/me endpoint should return:
Custom Response Parsing#
If your backend uses a different format, use responseMappers:
Automatic Token Refresh#
When a token is invalid or expired, the library automatically attempts to refresh it:
Refresh Flow#
- Token validation fails (expired/invalid)
- Library calls
/auth/refreshwith current token - If successful, updates cookie with new token
- Sets
x-refreshed-tokenheader for the request - Continues with the original request
Expected Refresh Response#
Custom Refresh Parsing#
Token Caching#
To minimize backend calls, validated tokens are cached:
Cache Behavior#
- Valid tokens are cached for 2 seconds by default
- Cache is per-token (different users have separate entries)
- Cache automatically cleans up expired entries
- Pending validation requests are deduplicated
Deduplication#
If multiple simultaneous requests come in with the same token:
This prevents thundering herd problems during high traffic.
Token Types#
The library supports different token types:
Type Checking#
Guest vs User Tokens#
| Feature | Guest Token | User Token |
|---|---|---|
| Created automatically | Yes | No (login required) |
| Cookie name | guestToken | userToken |
| Typical TTL | 1 hour | 7 days |
| Can access protected routes | No | Yes |
Cookie Configuration#
Control how tokens are stored:
Security Best Practices#
- Always use
httpOnly: trueto prevent XSS token theft - Use
secure: truein production for HTTPS-only sameSite: 'lax'provides good CSRF protection while allowing normal navigation- Set appropriate
maxAgebased on your security requirements
Accessing Tokens#
In Route Handlers#
With API Client#
The API client handles token retrieval automatically:
Token Expiration Handling#
Proxy Level#
The proxy handles expiration automatically:
- Detects expired token from validation response
- Attempts refresh
- If refresh fails, clears cookies and redirects to login (for protected routes)
Client Level#
The AuthProvider keeps client state in sync:
Debugging#
Enable audit logging to track token operations:
This helps identify:
- Frequent refresh attempts (might indicate short token TTL)
- Failed validations (might indicate backend issues)
- Unauthorized access attempts