# Next.js Authentication

> Secure token storage (HttpOnly Cookies) and Middleware patterns.

- Skill: `ngxtm-devkit/next-js-authentication` (Agent Skill, multi-file: 2 files)
- Install (CLI): `npx skillmds@latest add ngxtm-devkit/next-js-authentication`
- Raw SKILL.md: https://api.skillmd.com/api/skills/ngxtm-devkit/next-js-authentication/raw
- Safety review: pending
- Works with: Claude Code, Claude.ai, OpenAI Codex
- Category: Web & Frontend
- Author: ngxtm (https://skillmd.com/u/ngxtm-devkit)
- Updated: 2026-09-17
- Page: https://skillmd.com/skills/ngxtm-devkit/next-js-authentication

---


# 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_: [Auth Implementation](references/auth-implementation.md) (See "Setting Tokens").
2. **Access**: Read tokens in Server Components via `cookies().get()`.
   - _Reference_: [Auth Implementation](references/auth-implementation.md) (See "Reading Tokens").
3. **Protection**: Guard routes in `middleware.ts` before rendering.
   - _Reference_: [Auth Implementation](references/auth-implementation.md) (See "Middleware Protection").

## Anti-Pattern: LocalStorage

- **Security Risk**: Vulnerable to XSS.
- **Performance Hit**: Incompatible with Server Components (RSC). Forces client hydration and causes layout shift.

