How do you implement authentication in Next.js?
Authentication in Next.js has three parts: sign-in (verify credentials or OAuth and create a session), session management (a secure cookie holding a signed token or a database session ID), and authorization checks in a Data Access Layer used by pages, Route Handlers and Server Functions. Use a library unless you have a strong reason not to.
1. Sign-in
- A form posts to a Server Function that validates input (Zod), checks the password hash (Argon2 or bcrypt) or completes an OAuth flow.
- On success, create a session and set an
httpOnly,secure,sameSite=laxcookie. - Return field errors with
useActionState; rate-limit attempts.
2. Sessions
- Stateless: a signed or encrypted JWT in the cookie (
jose). No database lookup, but hard to revoke instantly. - Database sessions: the cookie holds a random ID; the server looks it up. Easy to revoke, one query per check.
3. Authorization
- A
server-onlyData Access Layer withverifySession()wrapped inReact.cache. - Every data read and every Server Function checks the session and permissions.
- Return DTOs with only the fields the caller may see.
proxy.tscan redirect unauthenticated users optimistically, but it is not the security boundary.
Libraries
The Next.js docs list Auth0, Better Auth, Clerk, Descope, Kinde, Logto, Stytch, Supabase, WorkOS and others. Auth.js (NextAuth) is now maintained by the Better Auth team, which recommends Better Auth for new projects.
With Cache Components
Reading the session cookie is request-time work: put user-specific UI inside <Suspense>. Never put per-user data in a shared "use cache" entry; pass the user ID as an argument or use "use cache: private".
Code example
1// app/login/actions.ts2"use server";34import { z } from "zod";5import { redirect } from "next/navigation";6import { verify } from "@node-rs/argon2";7import { db } from "@/lib/db";8import { createSession } from "@/lib/session"; // sets an httpOnly signed cookie910const Login = z.object({ email: z.string().email(), password: z.string().min(8) });1112export async function login(_prev: { error?: string }, formData: FormData) {13 const parsed = Login.safeParse(Object.fromEntries(formData));14 if (!parsed.success) return { error: "Invalid email or password" };1516 const user = await db.user.findUnique({ where: { email: parsed.data.email } });17 const ok = user && (await verify(user.passwordHash, parsed.data.password));18 if (!ok) return { error: "Invalid email or password" }; // same message: no user enumeration1920 await createSession(user.id);21 redirect("/dashboard");22}2324// lib/dal.ts: export const verifySession = cache(async () => { ...read + verify cookie... });25// app/dashboard/page.tsx: const session = await verifySession(); if (!session) redirect("/login");
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the Next.js set.