Authentication in Next.js
Hiding a link does not protect a page: anyone can type the URL. Authentication in Next.js means a session in an HttpOnly cookie, one central server-only helper that verifies it, and checks in every page, Server Action and Route Handler, plus authorization in every query.
68.1 Problem: anyone can open it
- The orders page loads all orders; the navbar shows the link only to logged-in users, so it feels safe.
- A logged-out user types /orders directly and the page shows everyone's orders.
React (TSX)
// app/orders/page.tsximport { db } from "@/lib/db"; export default async function OrdersPage() { const orders = await db.order.findMany(); return orders.map((o) => ( <p key={o.id}> {o.item}: ₹{o.total} </p> ));}Output
(logged out user types /orders)Running Shoes: ₹999Cotton Kurta: ₹1299Wireless Mouse: ₹64968.2 How does the server remember you?
- HTTP is stateless: the server treats every request as brand new and does not remember your login.
- At login the server creates a session, stores it in the database and sends the browser an HttpOnly cookie.
- The cookie goes with every request automatically and the server uses it to identify the user: authentication.
- Step 1
1.Login: email + password
- Step 2
2.Server creates a session and stores it in the database
- Step 3
3.Browser saves an HttpOnly cookie
- Step 4
4.Every request carries the cookie automatically
- Step 5
5.Server looks up the session to know who the user is
68.3 Setup: Better Auth
- Writing auth yourself is risky (passwords, sessions, many security details), so use a library.
- Options: Auth.js, Better Auth, hosted services like Clerk. The video uses Better Auth (the same team now maintains Auth.js).
- Give it a database, enable email and password login; the nextCookies plugin lets Server Actions set cookies.
TypeScript
// lib/auth.tsimport { betterAuth } from "better-auth";import { nextCookies } from "better-auth/next-js";import { DatabaseSync } from "node:sqlite"; export const auth = betterAuth({ database: new DatabaseSync("app.db"), emailAndPassword: { enabled: true }, plugins: [nextCookies()],});68.4 The auth route
- A catch-all route under app/api/auth receives every sign up, login and logout request.
- toNextJsHandler(auth) gives both GET and POST handlers.
- The demo uses Node's built-in SQLite; in a real app pass the Prisma or Drizzle adapter.
TypeScript
// app/api/auth/[...all]/route.tsimport { auth } from "@/lib/auth";import { toNextJsHandler } from "better-auth/next-js"; export const { GET, POST } = toNextJsHandler(auth);68.5 One central helper: requireUser
- import "server-only" keeps this code out of the browser bundle.
- Pass the request headers to getSession, because they carry the cookie.
- No session -> redirect("/login"); otherwise return the user.
TypeScript
// lib/session.tsimport "server-only";import { headers } from "next/headers";import { redirect } from "next/navigation";import { auth } from "@/lib/auth"; export async function requireUser() { const session = await auth.api.getSession({ headers: await headers(), }); if (!session) redirect("/login"); return session.user;}68.6 Fix: check in the page
- requireUser() sends a logged-out user straight to login.
- The query now filters by userId, so only this user's orders come back.
- Logged-out request: the server returns 307 with location /login.
React (TSX)
import { db } from "@/lib/db";import { requireUser } from "@/lib/session"; export default async function OrdersPage() { const user = await requireUser(); const orders = await db.order.findMany({ where: { userId: user.id }, }); return orders.map((o) => ( <p key={o.id}> {o.item}: ₹{o.total} </p> ));}Output
$ curl -I localhost:3000/ordersHTTP/1.1 307 Temporary Redirectlocation: /login68.7 Where does the check go?
- Step 1
1.proxy.ts: cookie present? fast redirect (optimistic only)
- Step 2
2.Page: requireUser()
- Step 3
3.Server Action: requireUser() again, fresh check
- Step 4
4.Route Handler: no session -> 401 JSON, not a redirect
The real check sits next to the data
| Layer | What it checks | On failure |
|---|---|---|
| proxy.ts | Only whether a cookie exists | Fast redirect to /login |
| Page | Verified session via requireUser | redirect("/login") |
| Server Action | Verified session again + ownership | redirect or throw |
| Route Handler | Verified session | 401 response (APIs need a clear error) |
68.8 Checkpoint: is this action safe?
- The page has its check and the cancel button shows only to logged-in users.
- Answer: no. Every Server Action is a public POST endpoint; anyone can call it from a script, so it needs its own check.
TypeScript
"use server";import { db } from "@/lib/db"; export async function cancelOrder(id: string) { await db.order.delete({ where: { id } });}68.9 Common mistakes
- Checking only login: deleting by id alone lets logged-in Priya send the id of Rahul's order and cancel it.
- Fix: match userId along with id in the query.
- Checking login is authentication (who you are); checking whose data it is, is authorization (what you can access).
- Myth: one proxy check secures the app. The proxy only sees a cookie, and in 2025 a middleware bug let attackers skip it with a special header.
TypeScript
// Wrong: any logged-in user can cancel anyone's order"use server";import { db } from "@/lib/db";import { requireUser } from "@/lib/session"; export async function cancelOrder(id: string) { await requireUser(); await db.order.delete({ where: { id } });}TypeScript
// Right: only your own order"use server";import { db } from "@/lib/db";import { requireUser } from "@/lib/session"; export async function cancelOrder(id: string) { const user = await requireUser(); await db.order.delete({ where: { id, userId: user.id }, });}| Term | Question it answers | Example in code |
|---|---|---|
| Authentication (AuthN) | Who is the user? | requireUser() returns the session user |
| Authorization (AuthZ) | What can this user access? | where: { id, userId: user.id } or a role check |
68.10 Auth best practices
- Keep the session in an HttpOnly cookie; never put a token in localStorage, any script on the page can read it.
- Build one central requireUser helper and call it in every page, action and route handler.
- Check userId or role in every query.
- Never handle passwords or secrets yourself: use the library and environment variables.
68.11 Interview tips
- Use a library like Better Auth or Auth.js that keeps the session in an HttpOnly cookie after login.
- Write a server-only helper that verifies the session and call it in every page, Server Action and Route Handler.
- Do not depend on the proxy; it is only an optimistic, cookie-exists check.
- Enforce authorization with userId / role conditions in queries.
- Route Handlers return 401; pages redirect to login.