Next.jsMedium

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=lax cookie.
  • 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-only Data Access Layer with verifySession() wrapped in React.cache.
  • Every data read and every Server Function checks the session and permissions.
  • Return DTOs with only the fields the caller may see.
  • proxy.ts can 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

tsx
1// app/login/actions.ts
2"use server";
3
4import { 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 cookie
9
10const Login = z.object({ email: z.string().email(), password: z.string().min(8) });
11
12export 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" };
15
16 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 enumeration
19
20 await createSession(user.id);
21 redirect("/dashboard");
22}
23
24// 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.

Open in study app