Next.js
createNextAuthHelpers, server-side auth, and App Router SSR.
Next.js gets first-class support: read auth from cookies in Server Components, render an authenticated page on the first byte, and protect API routes with one wrapper.
Setup
Create a lib/auth.ts that you import from both client and server code:
Server-side auth in a layout
getServerAuth reads the auth cookies, calls /auth/verify-session on the backend, and returns an InitialAuthState ready to feed <NextAuthProvider>. The first render is fully authenticated — no client-side useEffect round-trip.
Reading the user from a Server Component
Protecting an API route
withAuth is a higher-order function. You give it your handler; it wraps it with a check that verifies the cookies and short-circuits to 401 if the session is bad.
Middleware redirects
For coarse-grained gating across whole route trees, use a Next.js middleware.ts:
Middleware runs on every request — keep it cheap. It can't reach the database; for fine-grained role checks, use withAuth in the API/route handler instead.
Hydration & double fetches
When initialState is supplied, <NextAuthProvider> skips the client-side fetch. If you don't supply it, the provider falls back to its normal client-side bootstrap — works, but slower.
The getServerAuth call is cached per request by Next.js, so calling it from both layout.tsx and a page is fine.
Related
- Provider —
<NextAuthProvider>props. - Cross-tab sync.
- Next.js protected dashboard recipe.