Lesson 18 of 27Full-stack
Auth and Proxy
Add login with sessions, authorize by role and tenant in the data layer, revoke sessions, and use proxy.ts for optimistic redirects.
Authentication bugs are the most expensive bugs a web app can have, and "where do you check auth in a Next.js app?" is one of the most common senior-level interview questions. The short answer surprises people: not only in proxy.ts (the file formerly called middleware). This lesson shows the layers, the libraries, and what proxy is actually for.
Two different questions
- Authentication asks who are you? The user proves their identity (password, magic link, OAuth with Google or GitHub, a passkey), and you remember the answer in a session.
- Authorization asks are you allowed to do this? An authenticated member may edit their own post but not someone else's.
Every request needs both: first find the session, then check permission for the specific thing being read or changed.
/invoices/17 to /invoices/18 and sees another customer's invoice. Which check is missing?Sessions and cookies
After login, the server sets a cookie: a small value the browser sends back on every request to your domain. There are two main styles of session:
- Stateless: the cookie itself holds the session data (user ID, expiry), signed or encrypted with a secret so it cannot be forged. Libraries like
joseoriron-sessiondo the crypto. No database lookup per request, but you cannot revoke one session easily. - Database sessions: the cookie holds only a random session ID; the session row lives in your database. One lookup per request, but logging out everywhere is just deleting rows.
Whichever you use, set the cookie with safe attributes:
Press Run (⌘ Enter) to see what happens.In Next.js you set it with the cookies() API inside a Server Action or Route Handler:
import "server-only";
import { cookies } from "next/headers";
import { encrypt } from "./crypto"; // e.g. a JWT signed with jose and AUTH_SECRET
export async function createSession(userId: string) {
const expiresAt = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000);
const token = await encrypt({ userId, expiresAt });
(await cookies()).set("session", token, {
httpOnly: true,
secure: true,
sameSite: "lax",
path: "/",
expires: expiresAt,
});
}Libraries or roll your own?
Getting password hashing, OAuth flows, email verification, rate limits and session rotation right is a lot of work. Most teams use a library or a hosted service:
| Option | What it is | Good fit |
|---|---|---|
| Auth.js (NextAuth) | Open-source library; many OAuth providers; JWT or database sessions | You want OAuth logins and to own your data, for free |
| Better Auth | Open-source TypeScript library that stores users in your own database, with plugins (2FA, organisations, passkeys) | Full control, email/password plus OAuth, typed APIs |
| Clerk | Hosted service with prebuilt sign-in UI, user management and organisations | Shipping fast, B2B features, happy to pay per user |
| Supabase Auth, Auth0, WorkOS | Hosted auth tied to a platform or enterprise SSO | Already on that platform, or you need SAML/SSO |
| Roll your own | Sessions with jose or iron-session, passwords hashed with bcrypt or argon2 | Learning, or very simple needs |
Choosing between Auth.js, Better Auth and Clerk
The table tells you what each option is. The decision at work usually turns on five questions, and it pays to ask them before anyone writes a sign-in page, because swapping auth later means migrating every user and every session.
- Where do the users live? Auth.js and Better Auth store users and sessions in your database through an adapter. You own the data, you can join users to orders in one query, and leaving the library is a code change, not a data export. Clerk stores users on its platform. You get a dashboard, user management and impersonation for free, but your app reads users through its API or webhooks, and leaving means exporting users (password hashes included, if the vendor allows it) and re-wiring every check.
- Which login methods do you need? Auth.js grew up around OAuth providers. Its email and password support exists but is deliberately minimal, so teams that need passwords, email verification and reset flows end up writing those parts. Better Auth ships email and password, two-factor, passkeys and organisations as plugins. Clerk ships all of that with prebuilt UI.
- Is this B2B? Organisations, invitations, per-organisation roles and enterprise SSO (SAML, SCIM) are a lot of work. Hosted services such as Clerk or WorkOS sell exactly that. Better Auth has an organisation plugin, and SSO support you should check against your customers' identity providers.
- Who maintains it? Auth.js v5 spent a long time in beta, and in 2025 the project moved under the stewardship of the Better Auth team, who now point new projects towards Better Auth. Existing Auth.js apps keep working and get security fixes, but check the current status on the official sites before you start something new.
- What does it cost at your scale? Hosted services usually charge per active user or organisation, and the bill grows with success. Open-source libraries cost engineering time instead. Compare current pricing pages yourself; they change often.
A common, defensible answer: a consumer app with social logins and a small team picks Better Auth (or keeps an existing Auth.js setup), a B2B product that must sell to enterprises next quarter picks a hosted service, and nobody rolls their own password storage for a real product.
Whatever you pick, the rule for where to check stays the same. The library gives you a session. Authorizing each request is still your code.
The login flow
POST login(email, password)
Put the server side of a login in order.
- Tap the steps below in the right order.
Where to check auth
Think in layers, from cheap and coarse to precise and secure:
- Proxy (optional, optimistic). Read the session cookie and redirect obvious cases, like a logged-out visitor on
/dashboard. No database calls: proxy runs on every matched request, including prefetches. - Data access layer (required, secure). A
server-onlymodule where every function that reads or writes sensitive data first verifies the session and checks permission. Pages, Server Actions and Route Handlers all go through it. - UI (convenience only). Hiding a button is a nicety, not security.
import "server-only";
import { cache } from "react";
import { cookies } from "next/headers";
import { redirect } from "next/navigation";
import { decrypt } from "./session";
import { db } from "@/db";
export const verifySession = cache(async () => {
const token = (await cookies()).get("session")?.value;
const session = await decrypt(token);
if (!session?.userId) redirect("/login");
return { userId: session.userId as string };
});
export async function getInvoice(id: string) {
const { userId } = await verifySession();
const invoice = await db.query.invoices.findFirst({ where: (i, { eq }) => eq(i.id, id) });
if (!invoice || invoice.ownerId !== userId) return null; // authorization, per record
return { id: invoice.id, total: invoice.total }; // return only what the UI needs
}React.cache means a page and its layout calling verifySession() in the same render only decode the cookie once.
Why is proxy alone not enough? Server Actions are POST requests to the route that uses them, so a matcher change can silently stop covering them. Layouts do not re-render on client navigation, so a check in a layout does not run for every page view. And a misconfigured matcher is easy to miss in review. Checks next to the data cannot be skipped by any route.
proxy.ts redirects logged-out users away from /admin/*. A deleteUser Server Action used on /admin/users has no checks of its own. Is that safe?Role-based authorization in the DAL
getInvoice above checks ownership inline. That works for one function. By the twentieth, the checks have drifted: one compares ownerId, another forgets the organisation, a third checks role === "admin" and misses the new owner role. The fix is a few small helpers that every DAL function calls, so the rules live in one file you can read, test and audit.
import "server-only";
import { cache } from "react";
import { redirect } from "next/navigation";
import { verifySession } from "./dal";
import { PERMISSIONS, AuthzError, type Action } from "./permissions"; // the table below
import { db } from "@/db";
export const getCurrentUser = cache(async () => {
const { userId } = await verifySession();
// Read the role from the database, not the cookie, so a demotion takes effect now.
const user = await db.query.users.findFirst({ where: (u, { eq }) => eq(u.id, userId) });
if (!user) redirect("/login");
return { id: user.id, orgId: user.orgId, role: user.role };
});
export async function requirePermission(action: Action) {
const user = await getCurrentUser();
if (!PERMISSIONS[user.role].includes(action)) throw new AuthzError(action);
return user;
}Three design choices separate a helper that holds up from one that leaks:
- Check permissions, not roles. Code that says
can(user, "invoice:delete")survives the day product adds a "billing manager" role. Code that saysrole === "admin"has to be found and edited everywhere. Roles are just named bundles of permissions in one table. - Scope every query by tenant. In a multi-tenant app, the most damaging bug is reading another organisation's row. Put
orgIdinto thewhereclause of every query (or use the database's row-level security), and treat "same organisation" as a check that runs before any role logic. - Decide where the role comes from. A role baked into a stateless cookie is fast but stale: demote someone and they keep admin rights until the token expires. For anything sensitive, read the role from the database once per request (
React.cachekeeps it to one query) or keep tokens short-lived.
Here is the permission check on its own. Run it, then change Ana's role to "admin" and see what changes.
Press Run (⌘ Enter) to see what happens.What should a failed check do? In a page, redirect("/login") for no session and a 404 (notFound()) for a record the user may not see, so you do not confirm that invoice 18 exists. In a Server Action or Route Handler, return or respond with an error the client can show. Next.js also has experimental unauthorized() and forbidden() helpers for 401 and 403 pages; Error Handling in Next.js covers them.
What does this print?
const perms: Record<string, string[]> = { viewer: ["read"], member: ["read", "update"] };
const user = { role: "member", orgId: "acme" };
const doc = { orgId: "globex" };
console.log(perms[user.role].includes("update"));
console.log(perms[user.role].includes("update") && doc.orgId === user.orgId);Session rotation and logout everywhere
A session is a bearer token: whoever holds the cookie is the user. Rotation and revocation decide how long a stolen or stale cookie stays useful.
Rotate on every privilege change. Issue a brand-new session (new ID or new token) at login, at logout, when the user changes their password, and when their role is raised. If you reuse a session ID that existed before login, an attacker who planted that ID in the victim's browser is now logged in as the victim. That attack is called session fixation, and rotating at login removes it.
Expire on two clocks. A sliding expiry (extend the session when the user is active, as the Next.js docs' updateSession() example does) keeps regular users logged in. An absolute expiry (say 30 days after login, no matter what) forces a fresh login eventually, so a cookie copied off a laptop does not live forever. Re-ask for the password before dangerous actions such as changing the email address or deleting the account.
Logout everywhere is where the two session styles from earlier really differ:
- With database sessions, it is
DELETE FROM sessions WHERE user_id = ?. Every device is out on its next request. You can also list sessions ("Chrome on macOS, last seen today") and revoke one. - With stateless tokens, deleting the cookie only logs out this browser. Other copies stay valid until they expire. The usual fix is a session version on the user row: put it in the token, compare it in
verifySession(), and bump it to revoke every older token. That costs a database read per request, which is the price of revocation. The other option is short-lived access tokens with a refresh token stored server-side.
Press Run (⌘ Enter) to see what happens.The stolen token is valid: version 3 matches the user row.
On logout itself, delete the cookie with (await cookies()).delete("session") and invalidate the server side (delete the row or bump the version). Deleting only the cookie is the most common logout bug: the token still works if anyone copied it.
proxy.ts: code that runs before routing
Starting in Next.js 16, the file formerly called middleware.ts is named proxy.ts, and its function is proxy instead of middleware (a codemod does the rename: npx @next/codemod@canary middleware-to-proxy .). The behaviour is the same. The new name reflects what it is: a layer in front of your app that can redirect, rewrite, set headers and cookies, or respond directly before a route renders.
Put one proxy.ts at the project root (or in src/), next to app/:
import { NextResponse, type NextRequest } from "next/server";
const PROTECTED = ["/dashboard", "/settings"];
export function proxy(request: NextRequest) {
const { pathname } = request.nextUrl;
const hasSession = request.cookies.has("session");
if (!hasSession && PROTECTED.some((p) => pathname === p || pathname.startsWith(p + "/"))) {
const url = new URL("/login", request.url);
url.searchParams.set("next", pathname);
return NextResponse.redirect(url);
}
if (pathname.startsWith("/docs/v1")) {
return NextResponse.rewrite(new URL(pathname.replace("/docs/v1", "/legacy-docs"), request.url));
}
const response = NextResponse.next();
response.headers.set("x-frame-options", "DENY");
return response;
}
export const config = {
// skip static files, image optimisation and metadata files
matcher: ["/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)"],
};Three return types do almost everything:
NextResponse.redirect(url): the browser goes to a new URL (and the address bar changes).NextResponse.rewrite(url): serve a different route without changing the address bar. Good for A/B tests, multi-tenant subdomains, legacy paths.NextResponse.next(): continue, optionally with extra request or response headers and cookies.
Things to know: proxy runs on the Node.js runtime by default in Next.js 16 (the runtime option is not allowed in this file). Without a matcher it runs on every request, including static assets, so always set one. It is not the place for slow data fetching, and for fixed redirects use redirects() in next.config.ts instead.
Press Run (⌘ Enter) to see what happens.What does this print?
const prefixes = ["/app"]; const blocked = ["/app", "/apple", "/app/billing"].filter((p) => prefixes.some((x) => p === x || p.startsWith(x + "/"))); console.log(blocked.length);
Why proxy is an optimistic check only
"Optimistic" has a precise meaning here: proxy looks at the cookie and assumes the session behind it is still good. It does not ask the database whether the session was revoked, whether the user was banned an hour ago, or whether they may see invoice 18. Those answers need a query, and proxy runs on every matched request, prefetches included, so a query there would slow the whole site. Proxy is the bouncer glancing at wristbands. The DAL is the person checking the guest list.
There is also a harder reason, and it is a real incident worth knowing by name. In March 2025, CVE-2025-29927 showed that sending a crafted internal header, x-middleware-subrequest, made affected Next.js versions skip middleware entirely. Self-hosted apps whose only auth check lived in middleware were open to anyone who added one header. Apps that also checked in the data layer lost a redirect and nothing else. It was patched in all supported release lines; the lessons are what matter:
- Any single layer can fail. A framework bug, a matcher regex that misses a new route, or a refactor that moves a page out of
/dashboardall remove proxy coverage silently. Defence in depth means a second check that does not depend on the first. - Keep it upgraded. Next.js now publishes security releases on a regular schedule. Securing a Next.js App covers the patch policy and other framework-level protections.
- Strip internal headers at the edge if you run your own reverse proxy, so clients cannot send headers the framework treats as internal.
One nuance from the official docs: a route that is fully static is rendered at build time, so a DAL check inside it runs once, for nobody. Never put per-user data in a prerendered page. Private pages read the cookie, which makes them dynamic, so the DAL check runs on every request. Proxy can still guard a static page that is merely "members only" marketing, because the content itself is the same for everyone.
So what is proxy good for in auth? Fast, cheap UX: sending logged-out visitors to /login?next=... before any rendering, bouncing logged-in users away from /login, and redirecting by locale or tenant (locale routing is covered in Internationalization in Next.js). If deleting proxy.ts would let someone read data they should not, your real checks are in the wrong place.
Write the proxy redirect logic
Your proxy.ts makes an optimistic check from the session cookie only. Write the decision as a pure function proxyDecision(pathname, isLoggedIn).
- Protected areas:
/dashboardand/settings, including anything below them (/dashboard/team), but not look-alikes such as/dashboards. - Logged out on a protected path:
{ type: "redirect", to: "/login?next=" + encodeURIComponent(pathname) } - Logged in on
/loginor/signup:{ type: "redirect", to: "/dashboard" } - Everything else:
{ type: "next" }
proxyDecision("/dashboard/team", false)
→ { type: "redirect", to: "/login?next=%2Fdashboard%2Fteam" }Authorize inside the data layer
Proxy only checks that a cookie exists. The real check belongs next to the data, inside every Server Action and data function. Write canEditPost(user, post).
userisnull(logged out) or{ id, role }whereroleis"admin","editor", or"member"postis{ authorId, locked }
Rules:
- logged out: never
- admin: always, even when locked
- editor: any post that is not locked
- member: only their own posts, and only when not locked
canEditPost({ id: "u1", role: "member" }, { authorId: "u1", locked: false }) → true
canEditPost({ id: "u2", role: "member" }, { authorId: "u1", locked: false }) → false- authentication
- Verifying who the user is, then remembering it in a session.
- authorization
- Checking whether the authenticated user may perform a specific action on a specific resource.
- session cookie
- An HttpOnly, Secure, SameSite cookie holding a signed session or a session ID, sent with every request.
- data access layer
- A
server-onlymodule that all data reads and writes go through, verifying the session and permissions every time. - proxy.ts
- Next.js 16's name for middleware: code that runs before routing to redirect, rewrite, set headers or respond.
- rewrite
- Serving the content of a different route while keeping the URL in the address bar unchanged.
- permission
- A named action such as
invoice:delete. Roles grant permissions, and code checks permissions rather than role names. - tenant scoping
- Filtering every query by the user's organisation so one customer can never read another's rows.
- session rotation
- Issuing a fresh session at login, logout and privilege changes so an old or planted session ID is worthless.
- session fixation
- An attack where a session ID known to the attacker survives the victim's login and becomes an authenticated session.
- session version
- A counter on the user row copied into each token; bumping it revokes every older stateless token at once.
- optimistic check
- A fast check of the cookie alone, as in proxy, that assumes the session is still valid without asking the database.