Authentication Patterns for Next.js
⚠️ Always verify Auth.js docs first
Auth.js evolves rapidly. Check current documentation before implementing.
Documentation lookup
- •Auth.js docs: try
https://authjs.dev/llms-full.txtvia WebFetch - •Context7 fallback: resolve-library-id("next-auth") → get-library-docs
Auth.js v5 (NextAuth.js) overview
Auth.js v5 is the recommended auth solution for Next.js App Router.
Key concepts
- •Providers: OAuth (Google, GitHub, etc.), Credentials, Email
- •Session strategies: JWT (default, stateless) vs Database (server-side sessions)
- •Callbacks: jwt, session, signIn, redirect — customize token/session data
- •Middleware: Protect routes at the edge before they render
- •Adapters: Prisma, Drizzle, etc. for database sessions
Core files
code
auth.ts # Auth configuration app/api/auth/[...nextauth]/route.ts # Auth route handler middleware.ts # Route protection
Session access
- •Server Components:
const session = await auth() - •Client Components:
const { data: session } = useSession()(needs SessionProvider) - •Route Handlers:
const session = await auth() - •Server Actions:
const session = await auth() - •Middleware:
const { auth } = NextAuth(config); export default auth
When to use what
| Need | Pattern |
|---|---|
| Simple login/logout | Auth.js with OAuth provider |
| Custom login form | Auth.js Credentials provider |
| Protect all routes | Middleware matcher |
| Protect specific pages | Server-side check in layout/page |
| Role-based access | Session callback + middleware |
| API protection | auth() in route handlers |
Security considerations
- •Always validate on the server (never trust client-only checks)
- •Use CSRF protection (Auth.js handles this)
- •Rotate AUTH_SECRET regularly
- •Use httpOnly cookies for sessions
- •Validate redirect URLs
References
- •Setup guide:
references/auth-setup.md - •Protected routes:
references/protected-routes.md