How It Works
Understanding the architecture behind next-api-layer helps you make the most of its features and troubleshoot effectively.
Architecture Overview#
The library consists of two main components working together:
| Layer | Component | Responsibilities |
|---|---|---|
| Proxy | createAuthProxy | Token validation, auto refresh, guest tokens, CSRF, rate limiting |
| API Client | createApiClient | XSS sanitization, i18n injection, method spoofing, auth handling |
Request Flow:
Request Flow#
When a request comes into your Next.js application, here's what happens:
1. Proxy Intercepts#
The createAuthProxy proxy intercepts every request:
2. Token Validation#
The proxy checks for authentication tokens in cookies:
- User Token Check: First, it looks for the user token cookie
- Guest Token Fallback: If no user token, checks for guest token
- Validation: Validates the found token against your backend's
/auth/meendpoint - Caching: Valid tokens are cached to reduce backend calls
3. Auto Refresh#
If a token is expired but a refresh is possible:
- Calls your backend's
/auth/refreshendpoint - Updates the cookie with the new token
- Sets
x-refreshed-tokenheader for downstream use - Continues the request with the new token
4. Route Protection#
Based on your access configuration:
- Protected Routes: Require authentication, redirect to
/loginif not authenticated - Auth Routes: Login/register pages, redirect away if already authenticated
- Public Routes: Accessible by anyone
5. API Client Processing#
When your route handlers use the API client:
The client:
- Retrieves the token (from refreshed header or cookies)
- Sanitizes the outgoing request body on write methods (XSS protection)
- Makes the request to your backend
- Returns a Response object
Security Pipeline#
Every request passes through multiple security layers:
Rate Limiting#
Protects against DoS attacks by limiting requests per IP.
CSRF Protection#
Uses modern Fetch Metadata headers combined with HMAC-signed double-submit
cookies. Set a stable secret in production so tokens validate across instances
and restarts (otherwise a per-process ephemeral secret is used and a warning is
logged).
XSS Sanitization#
Outgoing request bodies are sanitized before they reach your backend, keeping stored data XSS-safe.
Audit Logging#
Track authentication events for security monitoring.
Token Cascade#
Tokens are retrieved in this priority order:
x-refreshed-tokenheader: If proxy refreshed the token- User token cookie: For authenticated users
- Guest token cookie: For anonymous sessions
Composability#
You can extend the proxy behavior with hooks:
Server Components Support#
For Server Components, use getServerUser:
This reads the x-auth-user header set by the proxy, avoiding extra backend calls.