Next.js + Supabase Auth
Best practices for secure authentication in the App Router.
Core Principles
- •Middleware First: Check session and refresh tokens in
middleware.ts. - •Server Verification: Use
auth.getUser()in Server Components for security (don't trustgetSessionalone on the server). - •Cookie Safety: Ensure
httpOnly,secure, andsameSite: laxfor session cookies.
Patterns
- •Protected Routes: Redirect unauthenticated users in middleware or at the page level.
- •Auth Callback: Handle PKCE flow in
app/auth/callback/route.ts. - •Client Sync: Use
onAuthStateChangeto keep client state in sync with server.
Related
- •Implementation in this project:
src/lib/auth.ts,app/api/auth/