No. 40Next.js9 min read2,428 words
Next.js authentication in 2026: patterns that hold up
Next.js authentication for App Router teams: sessions vs JWTs, proxy.ts checks, a data access layer, and how to secure Server Actions against direct calls.
- Written by
- Lazy Devs
- Published
- Updated
- Sources
- Cited inline

Key takeaways ยท 05
The short version
- 01In the Next.js App Router, the real security boundary is the code that reads or writes data. Route protection in proxy.ts or a layout is a UX convenience, not access control.
- 02Every Server Action is reachable by a direct POST request, so each one must check the session and the caller's right to touch that specific record, even if the page that renders it is protected.
- 03In Next.js 16, middleware.ts is renamed to proxy.ts and runs on the Node.js runtime. Keep it to an optimistic cookie check; never query the database there.
- 04For most products, an opaque session token in an HttpOnly, Secure, SameSite=Lax cookie backed by a database row beats a long-lived JWT, because you can revoke it instantly.
- 05Centralise session lookup and authorization in a server-only data access layer, wrap the lookup in React cache(), and scope every query to the current user or tenant.
On this page ยท 10
Next.js authentication goes wrong in one predictable way: a check runs in the wrong place. The rule that fixes it is simple. Verify the session and the user's permissions inside the code that touches data, every Server Action, Route Handler and query, and treat proxy.ts and protected layouts as convenience, not security. Everything else in this guide is detail on how to do that cleanly.
The App Router gives you several places where server code runs: Proxy (formerly Middleware), layouts, pages, Server Components, Server Actions and Route Handlers. Guard the wrong one and you get a login screen that looks secure sitting in front of a data layer that hands out everything to anyone who asks. These are the patterns we ship on production Next.js projects, and the reasons behind them.
The rule: verify next to the data, not next to the UI
Route protection and data protection are different jobs. Hiding a page is a UX nicety. Refusing to return a row is the security boundary.
A redirect in Proxy stops a casual visitor from seeing a dashboard. It does nothing to stop someone who calls your Server Action directly with a crafted payload. The Next.js data security guide is explicit: an exported Server Action is reachable by a direct POST request, not just through your UI, and a page-level auth check does not extend to the actions defined in that page.
So the verification that matters happens in the function that reads or writes the database, every time, with no exceptions for "the proxy already checked". Broken access control sits at the top of the OWASP Top 10 for a reason: it is the bug teams ship when they assume another layer has it covered.
| Where code runs | What it is good for | What it must not be trusted for |
|---|---|---|
proxy.ts | Redirecting signed-out users before render, cheap cookie presence checks | Authorization, role checks that guard data |
| Layouts | Shared UI, showing or hiding navigation | Protecting child pages (layouts do not re-render on every navigation) |
| Pages and Server Components | Reading data scoped to the current user | Protecting the Server Actions they render |
| Server Actions | Mutations, after verifying session and ownership | Skipping checks because "the page is protected" |
| Route Handlers | Webhooks, public APIs, file downloads | Anything without its own session or signature check |
Sessions: database-backed cookies by default
For most products we reach for a stateful session: a random, opaque token in an HttpOnly cookie, with the session record stored server side in Postgres or Redis. It is boring, it revokes instantly, and you never have to reason about a leaked token that stays valid for an hour after you ban someone.
Creating a session
Generate the token with a cryptographically secure random source, store only a hash of it, and set the cookie with strict attributes. Storing the hash means a leaked database backup does not hand out working sessions.
// lib/session.ts
import "server-only";
import { randomBytes, createHash } from "node:crypto";
import { cookies } from "next/headers";
import { db } from "@/lib/db";
const COOKIE = "session";
const THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1000;
const hash = (token: string) =>
createHash("sha256").update(token).digest("hex");
export async function createSession(userId: string) {
const token = randomBytes(32).toString("base64url");
const expiresAt = new Date(Date.now() + THIRTY_DAYS_MS);
await db.session.create({
data: { tokenHash: hash(token), userId, expiresAt },
});
const store = await cookies();
store.set(COOKIE, token, {
httpOnly: true,
secure: true,
sameSite: "lax",
path: "/",
expires: expiresAt,
});
}Issue a brand new token on every login and on privilege changes (like enabling admin rights). Reusing a pre-login session ID is the classic session fixation bug, and the OWASP Session Management Cheat Sheet covers it along with idle and absolute timeouts.
Reading the session once per request
// lib/session.ts (continued)
import { cache } from "react";
export const getCurrentUser = cache(async () => {
const store = await cookies();
const token = store.get(COOKIE)?.value;
if (!token) return null;
const row = await db.session.findUnique({
where: { tokenHash: hash(token) },
select: {
expiresAt: true,
user: { select: { id: true, email: true, role: true } },
},
});
if (!row || row.expiresAt < new Date()) return null;
return row.user;
});
export async function requireUser() {
const user = await getCurrentUser();
if (!user) throw new Error("UNAUTHENTICATED");
return user;
}Two details earn their keep. The server-only import makes the build fail if this module is ever imported into client code, so your database handle and session logic can never leak into a browser bundle. And React's cache deduplicates the lookup within a single request, so calling getCurrentUser() from a layout, a page and three Server Components hits the database once.
Note that cookies() is async. Since Next.js 16 the synchronous form is gone entirely, so older snippets that call cookies().get() without await fail: TypeScript flags them, and plain JavaScript breaks at runtime.
Sessions vs JWTs: how to decide
| Database session | Stateless JWT | |
|---|---|---|
| Revoke immediately (logout everywhere, ban) | Yes, delete the row | No, valid until expiry unless you add a denylist |
| Lookup per request | One indexed query (cacheable per request) | Signature check only |
| Payload size in cookie | Small opaque token | Grows with claims |
| Infrastructure | A sessions table or Redis | A signing secret and rotation plan |
| Best for | Most SaaS products, anything with admin powers or billing | Service-to-service calls, short-lived access tokens |
If you choose JWTs, the honest middle ground is short-lived access tokens (minutes) plus a stored refresh token you can kill. Pick based on whether instant revocation matters for your product, not on which one sounds more modern. The official Next.js authentication guide walks through both approaches.
Proxy (formerly Middleware): a cheap gate, not a guard
In Next.js 16, middleware.ts is deprecated and renamed to proxy.ts, and the exported function is renamed to proxy. Proxy now runs on the Node.js runtime, and the runtime cannot be changed. The Proxy reference has the details; the version 16 codemod does the rename for you.
Proxy runs before the route renders, which makes it the right place to bounce signed-out traffic away from a whole section of the app. Keep it dumb. It should check for the presence of a session cookie and redirect, nothing more. It runs on every matched request, including prefetches, so a database query here multiplies your load for no security gain.
// proxy.ts
import { NextResponse, type NextRequest } from "next/server";
export function proxy(req: NextRequest) {
if (!req.cookies.has("session")) {
const url = new URL("/login", req.url);
url.searchParams.set("next", req.nextUrl.pathname);
return NextResponse.redirect(url);
}
return NextResponse.next();
}
export const config = {
matcher: ["/dashboard/:path*", "/settings/:path*"],
};Note what this does not do: it does not confirm the session is valid, only that a cookie exists. That is fine. The cookie could be expired or forged, and the real check downstream will catch it. Proxy's job is to save a wasted render for signed-out visitors, not to stand between an attacker and your data.
One more trap: if you redirect to the next parameter after login, validate that it is a relative path on your own site. An unchecked redirect target turns your login page into an open redirect for phishing.
Server Actions: the place teams forget
Here is the pattern that catches teams out. You build a settings page, protect the route in Proxy, and ship a Server Action to rename a project. The action looks safe because it lives next to a protected page. It is not safe. Anyone can POST to it.
So every mutation follows the same three steps:
- Establish identity from the session.
- Validate the input, because anything from the client can be modified.
- Check authorization against the specific record being touched, ideally in the same query that reads or writes it.
// app/settings/actions.ts
"use server";
import { z } from "zod";
import { requireUser } from "@/lib/session";
import { db } from "@/lib/db";
const Schema = z.object({
projectId: z.string().uuid(),
name: z.string().min(1).max(80),
});
export async function renameProject(input: unknown) {
const user = await requireUser();
const { projectId, name } = Schema.parse(input);
// Scope the write to the caller: never trust that they own projectId.
const result = await db.project.updateMany({
where: { id: projectId, ownerId: user.id },
data: { name },
});
if (result.count === 0) throw new Error("FORBIDDEN");
}The ownership filter (ownerId: user.id) prevents the classic insecure direct object reference, where user A passes user B's projectId and edits a record they never owned. Authentication tells you who is calling. Authorization, scoped to the row, tells you whether they are allowed. You need both, in the action, not the page.
What Next.js already does for you
Server Actions only accept POST, and Next.js compares the Origin header to the Host header and aborts the request if they differ. Together with SameSite=Lax cookies, that blocks most cross-site request forgery. Action IDs are also encrypted and non-deterministic, and unused actions are removed from the client bundle. None of this replaces the checks above: the docs still tell you to treat every action as a public endpoint.
Route Handlers you write yourself do not get the Origin check. If a Route Handler mutates data using cookie authentication, add CSRF protection along the lines of the OWASP CSRF Prevention Cheat Sheet.
A data access layer: make the secure path the easy path
Repeating requireUser() and ownership filters by hand works until someone forgets one. The Next.js docs recommend a data access layer (DAL): a server-only module that is the only code allowed to query user data, with authorization built into every function.
// lib/dal/projects.ts
import "server-only";
import { requireUser } from "@/lib/session";
import { db } from "@/lib/db";
export async function listMyProjects() {
const user = await requireUser();
return db.project.findMany({
where: { ownerId: user.id },
select: { id: true, name: true, updatedAt: true }, // a DTO, not the raw row
orderBy: { updatedAt: "desc" },
});
}Pages then become simple callers:
// app/dashboard/page.tsx
import { listMyProjects } from "@/lib/dal/projects";
export default async function Dashboard() {
const projects = await listMyProjects();
return <ProjectList projects={projects} />;
}Because the query carries ownerId: user.id, you cannot render someone else's data even if route protection fails. The explicit select matters too: whatever a Server Component passes to a Client Component is serialized into the page, so returning only the fields the UI needs keeps password hashes and internal flags out of the browser. We go deeper on how this shapes data loading in data fetching patterns in React Server Components.
In a multi-tenant product the same idea applies one level up: scope every query by tenant as well as user. We cover that in multi-tenant architecture without the headaches.
Auth and caching do not mix casually
If you use "use cache" or other caching, never cache a function that reads cookies and returns user-specific data under a shared key. Read the session outside the cached function and pass the user ID in as an argument so it becomes part of the cache key, or do not cache it at all. Our guide to Next.js caching explains how the cache keys work.
Cookie settings that matter
Whatever library you use, check the session cookie's attributes against the MDN Set-Cookie reference:
HttpOnly: JavaScript cannot read it, which limits what a cross-site scripting bug can steal.Secure: sent over HTTPS only.SameSite=Lax: a sane default that survives normal links into your app while blocking most cross-site POSTs. UseStrictfor admin-only apps if the UX cost is acceptable.Path=/and noDomain: keeps the cookie on your exact host. Adding the__Host-name prefix makes the browser enforce this.- A real expiry: pair it with a server-side idle timeout so abandoned sessions die.
For flows that genuinely cross origins, use SameSite=None together with explicit CSRF tokens rather than loosening everything. Cookie flags are one line in a broader web application security checklist that is worth running before launch.
Common mistakes we find in Next.js auth code
When we review an existing Next.js codebase, the same issues come up again and again:
- Auth only in Proxy or a layout. The page redirects correctly, but the Server Actions and Route Handlers behind it have no checks.
- Role checks in the client. Hiding the "Delete" button for non-admins while the action itself accepts anyone.
- Fetching by ID without scoping.
findUnique({ where: { id } })with no owner or tenant filter. - Passing whole database rows to Client Components. Sensitive fields end up in the serialized page payload.
- Long-lived JWTs with no revocation. A fired employee keeps access until the token expires.
- No rate limiting on login and password reset. Credential stuffing goes unnoticed until it succeeds.
- Open redirects through an unvalidated
nextorreturnToparameter.
Should you use an auth library?
Yes, for the tedious parts. Auth.js, Better Auth and hosted providers such as Clerk, Auth0 and WorkOS all handle OAuth callbacks, password hashing, email verification and multi-factor flows better than a hand-rolled version. Check that the library supports the App Router and the Node.js runtime Proxy now uses. If you are rolling your own password storage, follow NIST SP 800-63B for password rules rather than inventing complexity requirements.
The point of this guide is not to talk you out of a library. It is that no library decides where you check ownership of a row. That part is always yours, and it is the part that gets breached.
A pre-launch checklist
- Proxy redirects signed-out users and does nothing else.
- Session lookup lives in one
server-onlymodule, wrapped in Reactcache. - Every Server Action calls the session helper, validates input and scopes its query to the user or tenant.
- Every Route Handler that changes data has its own authentication (session or signature) and CSRF protection where cookies are used.
- Data passed to Client Components is a minimal DTO.
- Session cookies are
HttpOnly,Secure,SameSite=Laxand expire. - Sessions are rotated on login and revocable on logout and password change.
- Login and reset endpoints are rate limited, and redirect targets are validated.
If you can answer "where does this exact query refuse to return another user's row?" for every data access in your app, your Next.js authentication is in good shape. If you cannot, that is the next thing to fix.
We review and build auth flows as part of our API and backend engineering work. If you want a second set of eyes before launch, or need auth built properly from day one, get in touch.
Choosing a provider rather than rolling your own? See our comparison of the best authentication providers in 2026.
FAQ ยท 05 questions
Frequently asked questions
Is Next.js middleware (proxy) enough to protect my pages?
No. Proxy runs before a route renders and is good for redirecting signed-out users, but it only sees the request, and the Next.js docs recommend it for optimistic checks only. Server Actions, Route Handlers and data reads must each verify the session themselves, because they can be called without going through the page you protected.
Should I use JWTs or database sessions with Next.js?
Use database-backed sessions unless you have a specific reason not to. They revoke instantly when a user logs out, changes password or is banned. Stateless JWTs avoid a database lookup, but they stay valid until they expire, so if you use them, keep access tokens short-lived and pair them with a revocable refresh token.
Do Server Actions protect against CSRF automatically?
Partly. Server Actions only accept POST requests, and Next.js compares the Origin header with the Host header and rejects mismatches, which blocks most cross-site request forgery in modern browsers. Combined with SameSite=Lax session cookies that covers the common cases, but Route Handlers you write yourself do not get the Origin check, so protect those explicitly.
Which authentication library should I use with the Next.js App Router?
Any maintained library that supports the App Router and your hosting runtime is fine: Auth.js, Better Auth and hosted providers like Clerk or Auth0 all handle OAuth flows, password hashing and email verification well. The library choice matters less than where you check authorization, which no library does for you.
How do I log a user out everywhere in Next.js?
With database sessions, delete every session row for that user and every device is signed out on its next request. With stateless JWTs you cannot do this directly; you need a token version or denylist checked on each request, which reintroduces the database lookup that JWTs were meant to avoid.