Authentication & Token Management
Priority: P0 (CRITICAL)
Use HttpOnly Cookies for token storage. Never use LocalStorage or sessionStorage.
Implementation Guidelines
- Token Storage: Strictly use
HttpOnly,Securecookies withSameSite: 'Lax'or'Strict'. Set reasonablemaxAge(e.g., 86400). Never store access tokens inlocalStorageorsessionStorage(XSS-vulnerable). LocalStorage causes hydration issues in Server Components. - Access Management: Read and verify tokens in Next.js Middleware (
middleware.ts) for edge-side redirection and route protection. - Next.js 15+ Async:
cookies()is a Promise fromnext/headersand must be awaited. - Library Selection: Prefer
next-auth(Auth.js) orClerkfor social logins and session management. - Data Access: Always use a DAL (Data Access Layer) to validate credentials and verify cookie presence before rendering.
- CSRF Protection: Guard all Server Actions and Route Handlers by verifying the Origin/Referer headers.
- User Verification: Use
await auth()(Auth.js) or a customgetSession()helper in Server Components.
Example: Auth Middleware
Example: HttpOnly Cookie Setup
Anti-Patterns
- No localStorage for tokens: XSS-vulnerable and causes hydration issues.
- No raw tokens in Client Components: Pass session state, not tokens.
- No unprotected Server Actions: Always verify Origin/Referer headers.