Next.js Security, Auth, and Sessions
Implement authentication and session handling with explicit security controls.
When to Use
- •Protecting routes and APIs
- •Managing sessions server-side
- •Enforcing CSP and CSRF protections
- •Building multi-tenant safe routing
Inputs
- •Auth provider integration
- •Session storage approach (cookies vs token store)
- •CSP policy requirements
- •CSRF protection strategy
- •Tenant identifiers and isolation rules
Instructions
- •Keep auth logic server-only with Route Handlers or Server Actions.
- •Use Middleware for gatekeeping, redirects, and tenant resolution.
- •Validate session tokens on every protected request.
- •Set secure cookies (
httpOnly,secure,sameSite). - •Add CSP headers via
next.config.tsor Middleware. - •Enforce CSRF protection on state-changing requests.
- •Ensure tenant isolation in queries and caching boundaries.
- •Never expose secrets in Client Components.
Output
- •Auth/session flow aligned with Next.js server-first patterns.
- •CSP and CSRF requirements documented.
- •Multi-tenant guardrails applied to routing and data access.