Skip to content

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.

27 min read0/8 questions

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.

Quick check
A logged-in user changes the URL from /invoices/17 to /invoices/18 and sees another customer's invoice. Which check is missing?
Need a nudge? A hint rules out a wrong answer.

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 jose or iron-session do 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:

TypeScriptset-cookie.ts
type CookieOptions = { httpOnly: boolean; secure: boolean; sameSite: "lax" | "strict" | "none"; path: string; maxAge: number }; function serialize(name: string, value: string, o: CookieOptions) { const parts = [`${name}=${encodeURIComponent(value)}`, `Path=${o.path}`, `Max-Age=${o.maxAge}`, `SameSite=${o.sameSite}`]; if (o.httpOnly) parts.push("HttpOnly"); // JavaScript in the page cannot read it if (o.secure) parts.push("Secure"); // only sent over HTTPS return parts.join("; ");} console.log(serialize("session", "eyJhbGciOi...", { httpOnly: true, secure: true, sameSite: "lax", path: "/", maxAge: 60 * 60 * 24 * 7,}));
Output
Press Run (⌘ Enter) to see what happens.

In Next.js you set it with the cookies() API inside a Server Action or Route Handler:

lib/session.ts
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:

OptionWhat it isGood fit
Auth.js (NextAuth)Open-source library; many OAuth providers; JWT or database sessionsYou want OAuth logins and to own your data, for free
Better AuthOpen-source TypeScript library that stores users in your own database, with plugins (2FA, organisations, passkeys)Full control, email/password plus OAuth, typed APIs
ClerkHosted service with prebuilt sign-in UI, user management and organisationsShipping fast, B2B features, happy to pay per user
Supabase Auth, Auth0, WorkOSHosted auth tied to a platform or enterprise SSOAlready on that platform, or you need SAML/SSO
Roll your ownSessions with jose or iron-session, passwords hashed with bcrypt or argon2Learning, 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.

  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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

Email and password login
BrowserServer ActionDatabaseProxyPagePOST login(email, password)find user, compare hashuser rowSet-Cookie: session; redirect /dashboardGET /dashboard + cookiecookie present: continueverifySession() then load datadashboard HTML

POST login(email, password)

1/8
Put it in order4 steps

Put the server side of a login in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

Where to check auth

Think in layers, from cheap and coarse to precise and secure:

  1. 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.
  2. Data access layer (required, secure). A server-only module 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.
  3. UI (convenience only). Hiding a button is a nicety, not security.
lib/dal.ts
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.

Quick check
Your 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?
Need a nudge? A hint rules out a wrong answer.

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.

lib/authz.ts
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 says role === "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 orgId into the where clause 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.cache keeps 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.

TypeScriptpermissions.ts
type Role = "viewer" | "member" | "admin";type Action = "invoice:read" | "invoice:update" | "invoice:delete" | "member:invite"; // One table, owned by the DAL. Roles grant permissions; code checks permissions.const PERMISSIONS: Record<Role, Action[]> = { viewer: ["invoice:read"], member: ["invoice:read", "invoice:update"], admin: ["invoice:read", "invoice:update", "invoice:delete", "member:invite"],}; type User = { id: string; orgId: string; role: Role };type Invoice = { id: string; orgId: string; ownerId: string }; function can(user: User, action: Action, invoice?: Invoice): boolean { if (!PERMISSIONS[user.role].includes(action)) return false; if (invoice && invoice.orgId !== user.orgId) return false; // tenant boundary first if (action === "invoice:update" && user.role === "member") { return invoice?.ownerId === user.id; // members edit only their own } return true;} const ana: User = { id: "u1", orgId: "acme", role: "member" };const raj: User = { id: "u2", orgId: "acme", role: "admin" };const inv: Invoice = { id: "i9", orgId: "acme", ownerId: "u2" };const other: Invoice = { id: "i5", orgId: "globex", ownerId: "u2" }; console.log("ana update i9:", can(ana, "invoice:update", inv));console.log("raj update i9:", can(raj, "invoice:update", inv));console.log("raj delete globex i5:", can(raj, "invoice:delete", other));console.log("ana invite:", can(ana, "member:invite"));
Output
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.

Predict the outputTypeScript

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);
Need a nudge? Hints walk you through it.

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.
TypeScriptsession-version.ts
// A stateless token carries a copy of the user's sessionVersion.type Token = { userId: string; ver: number; exp: number };const users = new Map([["u1", { sessionVersion: 1 }]]); function issue(userId: string, now: number): Token { return { userId, ver: users.get(userId)!.sessionVersion, exp: now + 7 * 24 * 3600 };} function verify(t: Token, now: number): string { if (now > t.exp) return "expired"; if (users.get(t.userId)!.sessionVersion !== t.ver) return "revoked"; return "ok";} function logoutEverywhere(userId: string) { users.get(userId)!.sessionVersion += 1; // every older token stops matching} const laptop = issue("u1", 0);const phone = issue("u1", 10);console.log("before:", verify(laptop, 100), verify(phone, 100));logoutEverywhere("u1");const fresh = issue("u1", 200);console.log("after: ", verify(laptop, 300), verify(phone, 300), verify(fresh, 300));
Output
Press Run (⌘ Enter) to see what happens.
A password reset that logs out a stolen session
AttackerVictimServerDatabaseGET /dashboard + stolen cookie (ver 3)POST reset passwordsave new hash, sessionVersion = 4Set-Cookie: new session (ver 4)GET /dashboard + stolen cookie (ver 3)redirect /login

The stolen token is valid: version 3 matches the user row.

1/6

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.

Quick check
Your app keeps the same session ID before and after login, and only marks the existing session row as 'authenticated'. What attack does this allow?
Need a nudge? A hint rules out a wrong answer.

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/:

proxy.ts
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.

TypeScriptproxy-logic.ts
function decide(pathname: string, loggedIn: boolean) { const isProtected = ["/dashboard", "/settings"].some((p) => pathname === p || pathname.startsWith(p + "/")); if (isProtected && !loggedIn) return `redirect → /login?next=${encodeURIComponent(pathname)}`; if (loggedIn && pathname === "/login") return "redirect → /dashboard"; return "next";} for (const [path, loggedIn] of [["/dashboard/team", false], ["/dashboard", true], ["/login", true], ["/settingsx", false]] as const) { console.log(path.padEnd(16), loggedIn ? "in " : "out", decide(path, loggedIn));}
Output
Press Run (⌘ Enter) to see what happens.
Predict the outputTypeScript

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);
Need a nudge? Hints walk you through it.

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 /dashboard all 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.

Quick check
An admin bans a user. The user's session cookie is still in their browser and has six days left. Proxy checks only that the cookie exists and is signed. What stops the banned user from loading their dashboard data?
Need a nudge? A hint rules out a wrong answer.
ChallengeMedium

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: /dashboard and /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 /login or /signup: { type: "redirect", to: "/dashboard" }
  • Everything else: { type: "next" }
proxyDecision("/dashboard/team", false)
  → { type: "redirect", to: "/login?next=%2Fdashboard%2Fteam" }
TypeScript
type Decision = { type: "next" } | { type: "redirect"; to: string }; function proxyDecision(pathname: string, isLoggedIn: boolean): Decision { return { type: "next" };}
ChallengeEasy

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).

  • user is null (logged out) or { id, role } where role is "admin", "editor", or "member"
  • post is { 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
TypeScript
type User = { id: string; role: "admin" | "editor" | "member" } | null;type Post = { authorId: string; locked: boolean }; function canEditPost(user: User, post: Post): boolean { return true;}
Key terms
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-only module 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.