home / skills / hoangnguyen0403 / agent-skills-standard / authentication
This skill helps implement secure Next.js authentication using HttpOnly cookies, server components access, and middleware protection to strengthen token
npx playbooks add skill hoangnguyen0403/agent-skills-standard --skill authenticationReview the files below or copy the command above to add this skill to your agents.
---
name: Next.js Authentication
description: Secure token storage (HttpOnly Cookies) and Middleware patterns.
metadata:
labels: [nextjs, auth, security, cookies]
triggers:
files: ['middleware.ts', '**/auth.ts', '**/login/page.tsx']
keywords: [cookie, jwt, session, localstorage, auth]
---
# Authentication & Token Management
## **Priority: P0 (CRITICAL)**
Use **HttpOnly Cookies** for token storage. **Never** use LocalStorage.
## Key Rules
1. **Storage**: Use `cookies().set()` with `httpOnly: true`, `secure: true`, `sameSite: 'lax'`. (Reference: [Setting Tokens](references/auth-implementation.md))
2. **Access**: Read tokens in Server Components via `cookies().get()`. (Reference: [Reading Tokens](references/auth-implementation.md))
3. **Protection**: Guard routes in `middleware.ts` before rendering. (Reference: [Middleware Protection](references/auth-implementation.md))
## Anti-Pattern: LocalStorage
- **Security Risk**: Vulnerable to XSS.
- **Performance Hit**: Incompatible with Server Components (RSC). Forces client hydration and causes layout shift.
## Related Topics
common/security-standards | server-components | app-router
This skill documents secure authentication patterns for Next.js using HttpOnly cookies and middleware route protection. It emphasizes server-first token handling to avoid client-side storage risks and to stay compatible with Server Components. The guidance focuses on concrete configuration and common anti-patterns to prevent XSS and layout-hydration issues.
Tokens are issued and stored with cookies().set() configured as httpOnly, secure, and sameSite: 'lax' so they are inaccessible to JavaScript and sent automatically with requests. Server Components and API routes read tokens via cookies().get(), keeping authentication logic on the server. A middleware.ts file inspects requests and redirects or blocks access to protected pages before rendering.
Why not use LocalStorage for tokens?
LocalStorage is accessible to JavaScript, making tokens vulnerable to XSS. It also forces client-side hydration and breaks Server Components compatibility, causing layout shifts.
How should I configure cookie options?
Set cookies with httpOnly: true, secure: true (in production), and sameSite: 'lax' to limit cross-site request exposure while allowing normal navigation.