Session Management (Next.js)
This page covers cookie-based session management for Next.js frontend applications. The Next.js app acts as a Backend-for-Frontend (BFF), storing tokens in HTTP-only cookies rather than localStorage for better XSS protection.
How it works
The diagram below shows the session flow (production deployments include load balancers, WAF, CDN, etc.):
Login flow:
Subsequent API requests:
The Next.js frontend stores tokens in HTTP-only cookies and forwards them to the API on each request.
Token cookie utilities
tsdevstack includes utility functions for cookie management:
Login API route
Frontend login function
Logout
Cookie configuration
The setHttpOnlyCookie utility applies secure defaults:
Security considerations
The auth service template's session management follows the OWASP Session Management Cheat Sheet:
- HTTP-only cookies - Cannot be accessed by JavaScript (XSS protection)
- Secure flag - Only sent over HTTPS in production
- SameSite=lax - Protects against CSRF attacks
- Short access token lifetime - Limits exposure if compromised (15 min default)
- BFF pattern - Tokens never exposed to browser JavaScript
- Refresh token rotation - Each refresh invalidates the previous token, limiting replay windows
- Hashed token storage - Refresh tokens are SHA-256 hashed before database storage, per OWASP Cryptographic Storage