Explain it simply
Authentication and authorization in plain language
Think of an airport. Checking your passport at the entrance is authentication: 'who are you?'. Checking your boarding pass at the gate is authorization: 'may you board this plane?'. Being inside the terminal does not let you board every flight.
A web app works the same way. Being signed in only proves authentication happened; whether you may delete a particular note is a separate question. Hiding the Delete button is like removing the sign from a door, not locking it.
Problem → Why → Solution
The problem: a hidden button is the only guard
The note page shows the Delete button only to the owner, and the layout redirects signed-out visitors to /login. The team considers it secure. But the deleteNote action itself accepts any id. A signed-in member replays the request in devtools with someone else's note id, and that note is gone. The layout does not re-render on every navigation either, so it was never the thing protecting the data.
// the only "protection" is in the UI
{session?.user.id === note.ownerId && (
<form action={deleteNote.bind(null, note.id)}>
<button>Delete</button>
</form>
)}
// app/notes/actions.ts
"use server";
export async function deleteNote(noteId: string) {
await db.note.delete({ where: { id: noteId } }); // anyone can call this
}Security lives where the data is touched
An attacker does not need your UI; they can send requests to the server directly. So the question 'may this user do this action on this record?' must be answered in the server code that reads or changes the data. Checks in the UI exist only for user experience.
Core concept: who, what, and where to check
Authentication confirms identity. Usually a successful login creates a session and gives the browser a cookie, which either holds encrypted, signed session data itself or an id pointing to a session in the database. Authorization is the question asked after identity is known: may this user perform this action on this resource? The answer depends on ownership, role or subscription plan. Failed authentication means 401 or a redirect to login; failed authorization means 403, or 404 when you do not want to reveal that the resource exists.
Protect the session cookie with flags. httpOnly stops JavaScript from reading it, so an XSS bug cannot steal the token. secure sends it only over HTTPS, and sameSite: "lax" keeps it off POST requests started by other sites, reducing CSRF. Rather than writing password hashing, OAuth and session rotation yourself, use a maintained auth library; the Next.js authentication guide lists several.
Layer your checks. Middleware (renamed proxy in Next.js 16) can look for the cookie and redirect optimistically. Layouts can check for UX, but because of partial rendering they do not re-run on every navigation. The real check sits closest to the data: a helper such as verifySession() that every data function, Server Action and Route Handler calls.
Write authorization rules as pure functions such as canDeleteNote(user, note): they take data and return true or false, with no session, database or Next.js API inside. That makes every role easy to test, and the component deciding whether to show a button can reuse the very same rule instead of a copy that drifts.
| Question | On failure | Checked in |
|---|---|---|
| Who are you? (authentication) | 401 / redirect to /login | verifySession helper |
| Are you allowed? (authorization) | 403 or 404 | actions and data functions |
| Show the button? | hide the button | component (UX only) |
- Request arrives with a cookie
- Authenticate: read, verify session
- Load the resource from the database
- Authorize: owner or allowed role?
- Only then read or change data
Authorization can only be decided after loading the resource, because the ownerId lives in the database, not in the request.
General pattern
export async function protectedAction(resourceId: string) {
const user = await verifySession(); // who? (401 / redirect)
const resource = await loadResource(resourceId);
if (!resource) return { error: "Not found" }; // 404
if (!canModify(user, resource)) return { error: "Forbidden" }; // what? (403)
await changeResource(resource);
}Verify the session, load the resource, decide with a pure permission function, and only then change the data.
Worked example: deleteNote guarded by verifySession
Checking the session and the owner is the heart of authorization, but a real app also needs to know where the session comes from and to support roles such as admin. Here auth lives in a server-only helper file, the permission rule is a pure function you can test on its own, and errors come back as state the form can show instead of being thrown.
// lib/auth.ts
import "server-only";
import { cache } from "react";
import { cookies } from "next/headers";
import { redirect } from "next/navigation";
import { readSession } from "@/lib/session"; // verifies and decodes the cookie
export type User = { id: string; role: "member" | "admin" };
export const verifySession = cache(async (): Promise<User> => {
const token = (await cookies()).get("session")?.value;
const user = token ? await readSession(token) : null;
if (!user) redirect("/login");
return user;
});
export function canDeleteNote(user: User, note: { ownerId: string }) {
return user.role === "admin" || note.ownerId === user.id;
}
// app/notes/actions.ts
"use server";
import { revalidatePath } from "next/cache";
import { canDeleteNote, verifySession } from "@/lib/auth";
import { db } from "@/lib/db";
export async function deleteNote(noteId: string) {
const user = await verifySession(); // authentication
const note = await db.note.findUnique({
where: { id: noteId },
select: { ownerId: true },
});
if (!note) return { error: "Note not found" };
if (!canDeleteNote(user, note)) return { error: "You can only delete your own notes" };
await db.note.delete({ where: { id: noteId } });
revalidatePath("/notes");
return { ok: true };
}Code breakdown
- Read the cookie on the server
const token = (await cookies()).get("session")?.value;Since Next.js 15, cookies() is async and must be awaited. The token is trusted only after readSession verifies it.
- No session, no entry
if (!user) redirect("/login");redirect() returns never, so after this line TypeScript knows user is a User. Thanks to cache(), verification runs once per request however many times it is called.
- A pure permission rule
return user.role === "admin" || note.ownerId === user.id;Keeping the rule in its own function lets both the UI (to show a button) and the action (to actually protect) share it, and makes it easy to unit test.
- Authenticate inside the action
const user = await verifySession(); // authenticationEven if the page already checked the login, the action checks again, because it can be called directly.
- Authorize before deleting
if (!canDeleteNote(user, note)) return { error: "You can only delete your own notes" };It compares against the ownerId loaded from the database, never an ownerId sent by the client.
A signed-out request is redirected to /login. A member trying to delete someone else's note gets "You can only delete your own notes" and nothing is deleted. The owner, or an admin, deletes the note and the /notes list refreshes.Setting the session cookie
After a successful login, a Server Action or Route Handler sets the cookie. An auth library usually does this for you, but knowing what each flag means makes its configuration easy to review. Never keep the token in localStorage, where every script on the page can read it.
export async function createSessionCookie(token: string, expiresAt: Date) {
(await cookies()).set("session", token, {
httpOnly: true, // invisible to page JavaScript
secure: process.env.NODE_ENV === "production", // HTTPS only in production
sameSite: "lax", // not sent on cross-site POSTs
path: "/",
expires: expiresAt,
});
}In real projects
In real projects
In most production apps a library or hosted service handles authentication, while the team writes the authorization rules itself, because those rules are business logic.
- SaaS apps show an organization's projects only to its members, and scope every query by organizationId.
- Admin dashboards declare role-based rules (admin, editor, viewer) in one permission map, and every action calls a helper such as can(user, "post:publish").
- Content sites let editors change any draft while authors may only change their own.
- Public APIs check an API key from the Authorization header in the Route Handler and allow only that key's scopes.
During a security review, reviewers go through each action asking who can call it and where that is checked. When every action starts with the same helper, that question takes seconds to answer.
Common mistakes
Common auth mistakes
Treating a hidden button as authorization
A missing button does not stop a request. Every Server Action and Route Handler must check permission itself; the UI only reuses the same rule to decide whether to show the button.
Checking once in a layout or middleware and stopping
A layout does not re-run on every navigation, and actions can be called without passing through it. In 2025 a vulnerability even let a crafted header bypass Next.js middleware, a good illustration of why middleware alone is risky.
Trusting a userId or role sent by the client
A role in a form field, query string, localStorage or an unverified token is input the user can edit. Take identity only from a verified session.
Keeping the session token readable by JavaScript
A token in a cookie without httpOnly, or in localStorage, can be stolen by a single XSS bug and used to take over the account.
Best practices
Best practices
- Write permission rules as pure functions such as canDeleteNote and unit test them for every role.
- Scope queries by ownerId or organizationId, so a forgotten check leaks less.
- Use a maintained library for passwords and OAuth instead of writing them yourself, and keep it updated.
Mini challenge
Mini challenge: a permission matrix
Write the authorization rule for updating a note as two pure functions, then print a results matrix for several users and two notes. Admins may update anything, and only admins may update an archived note. Editors may update any note that is not archived, and members only their own.
- canUpdateNote(user, note) returns a boolean
- authorizeUpdate(user | null, note) returns "unauthenticated", "forbidden" or "ok"
- Print the result for a guest, the owner, another member, an editor and an admin for each note
type Role = "member" | "editor" | "admin";
type User = { id: string; role: Role };
type Note = { id: string; ownerId: string; archived: boolean };
type Decision = "ok" | "unauthenticated" | "forbidden";
function canUpdateNote(user: User, note: Note): boolean {
// TODO: admin -> always
// TODO: archived -> nobody else
// TODO: editor -> any note; member -> only their own
}
function authorizeUpdate(user: User | null, note: Note): Decision {
// TODO: no user -> "unauthenticated"; otherwise use canUpdateNote
}
// TODO: two notes (one archived), five people (one of them a guest),
// print one line per note: name=decision ...Expected: For n1 the guest is unauthenticated, ada, eve and root are ok, and bo is forbidden. For the archived n2 only root, the admin, is ok.
Show hint
Check the rules in order: admin first, archived next, then editor and owner. Keeping authentication (is there a user?) and authorization (the rule) in separate functions keeps the 401 versus 403 difference clear.
Show solution
type Role = "member" | "editor" | "admin";
type User = { id: string; role: Role };
type Note = { id: string; ownerId: string; archived: boolean };
type Decision = "ok" | "unauthenticated" | "forbidden";
function canUpdateNote(user: User, note: Note): boolean {
if (user.role === "admin") return true;
if (note.archived) return false;
return user.role === "editor" || note.ownerId === user.id;
}
function authorizeUpdate(user: User | null, note: Note): Decision {
if (!user) return "unauthenticated"; // 401
return canUpdateNote(user, note) ? "ok" : "forbidden"; // 403
}
const people: [string, User | null][] = [
["guest", null],
["ada", { id: "u1", role: "member" }],
["bo", { id: "u2", role: "member" }],
["eve", { id: "u3", role: "editor" }],
["root", { id: "u4", role: "admin" }],
];
const notes: Note[] = [
{ id: "n1", ownerId: "u1", archived: false },
{ id: "n2", ownerId: "u1", archived: true },
];
for (const note of notes) {
const cells = people.map(([name, user]) => `${name}=${authorizeUpdate(user, note)}`);
console.log(`${note.id}${note.archived ? " (archived)" : ""}: ${cells.join(" ")}`);
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Authentication answers 'who are you?' (401 on failure); authorization answers 'may you do this to this resource?' (403 on failure).
- Keep the session cookie httpOnly, secure and sameSite, and never put the token in localStorage.
- Hidden buttons and layout or middleware redirects are UX; the real checks live in actions and data functions.
- Write permission rules as pure functions and take ownerId only from the database.
Next.js — Authentication — Next.js
Next.js — Authentication — Next.js