AgentSkillsCN

auth-patterns

为Next.js应用提供身份验证与授权模式指南。涵盖Auth.js(NextAuth.js v5)的搭建、基于中间件的身份验证、会话管理(JWT与数据库)、受保护路由、基于角色的访问控制,以及OAuth提供商的集成。在实施前,请务必参照最新的Auth.js官方文档进行验证。

SKILL.md
--- frontmatter
name: auth-patterns
description: "Authentication and authorization patterns for Next.js. Covers Auth.js (NextAuth.js v5) setup, middleware-based auth, session handling (JWT vs database), protected routes, role-based access control, and OAuth providers. Always verify against current Auth.js docs before implementing."
license: MIT
metadata:
  author: Balazs Barta
  version: "0.1.0"

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.txt via 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

NeedPattern
Simple login/logoutAuth.js with OAuth provider
Custom login formAuth.js Credentials provider
Protect all routesMiddleware matcher
Protect specific pagesServer-side check in layout/page
Role-based accessSession callback + middleware
API protectionauth() 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