18 tháng 1, 2026 · 12 phút đọc

Authentication với NextAuth.js v5: OAuth, credentials và session strategy

Cấu hình NextAuth v5 với multiple providers, custom callbacks, và JWT vs database sessions — tradeoffs thực tế.

Authentication với NextAuth.js v5: OAuth, credentials và session strategy

Authentication là một trong những feature phức tạp nhất khi xây dựng web app — không phải vì khó implement mà vì có nhiều edge cases và security implications. NextAuth.js v5 (Auth.js) là giải pháp comprehensive cho Next.js, giải quyết OAuth, credentials, sessions và security built-in.

NextAuth v5 vs v4: những thay đổi quan trọng

v5 được viết lại hoàn toàn để hỗ trợ App Router. auth() function thay thế getServerSession(). Middleware-based session verification với auth middleware. Edge runtime support. Configuration tập trung trong auth.ts thay vì [...nextauth] route.

Migration từ v4: update imports, replace useSession() với auth() ở server components, update callback signatures. Breaking changes documentation trên auth.js.dev đầy đủ.

Authentication flow diagram
OAuth flow với multiple providers qua NextAuth.js

OAuth Providers

NextAuth có built-in providers cho Google, GitHub, Discord, và nhiều nữa. Cần tạo OAuth app trên provider's developer console, lấy CLIENT_ID và CLIENT_SECRET. Callback URL format: {domain}/api/auth/callback/{provider}.

Custom providers dùng provider config object với authorization/token/userinfo endpoints. Hữu ích khi integrate với internal SSO hoặc enterprise IdPs.

Credentials Provider: cần cẩn thận

Credentials provider cho username/password authentication. Nhớ: hash passwords với bcrypt/argon2, không bao giờ store plaintext. Rate limit login attempts. Credentials provider không support JWT refresh tokens — cần implement thủ công nếu cần.

JWT vs Database Sessions

JWT sessions (stateless): không cần database, nhưng không thể revoke trước khi expire. Phù hợp khi không cần instant logout. Database sessions (stateful): có thể revoke bất kỳ lúc nào, nhưng cần database query mỗi request. Dùng Adapter (Prisma, Drizzle) cho database sessions.

Bảo vệ Routes

Middleware là nơi tốt nhất để protect routes — runs trên Edge trước khi request đến server. auth middleware của NextAuth v5 cho phép define authorized callback. Fallback: check session trong Server Components và redirect nếu unauthorized.