A nextjs authentication setup in the App Router is three jobs, not one file. You prove who the user is, you keep a session across requests, and you check that session again before any data or mutation. A lot of apps do the first two, then put a redirect in the old middleware.ts file and assume Server Actions are covered. They are not.
This post builds the session and the two checks, with original code and 17 tests that run in Node’s test runner. The route-level check belongs in proxy.ts, which is what Next.js 16 calls the old middleware file. The real check belongs next to the data, which is the same idea as the auth and access-control section in my web application security checklist.
What this post covers
- Tested versions
- Three layers, and what each one is for
- An encrypted session cookie
- Optimistic checks in proxy.ts
- Server Action checks that actually authorize
- What the tests check
- What I did not test
- FAQ
Tested versions
| Tool | Version |
|---|---|
| Node.js | v24.22.1 |
| Session crypto | Node’s built-in node:crypto, AES-256-GCM |
| Tests | test-auth.mjs with node --test: 17 tests, all passing |
| Next.js APIs referenced | App Router proxy.ts (Next.js 16; middleware.ts is deprecated), async cookies(), Server Actions |
The dashboard paths, user ids and display names in the tests are invented. They are not from a real product. The session, path and decision functions run as plain modules, which is what the tests exercise. I did not boot a Next.js app.
Three layers, and what each one is for
The official Next.js authentication guide splits the work the same way: authentication, session management, then authorization. I’m staying with a custom session so the moving parts stay visible. If you already want a library, that page lists options such as Auth.js, and it recommends Jose or iron-session for the cookie itself. Use one of those in production if you don’t want to maintain your own crypto.
- The session cookie is the only thing the browser holds. It is set on the server after a successful login, marked HttpOnly, and encrypted so the payload isn’t sitting in plain text.
- Proxy (the file that used to be
middleware.ts) looks at that cookie and redirects unauthenticated requests away from protected pages. It should not query a database. It runs on navigations and prefetches, so a slow check there shows up everywhere. - Server Actions, Route Handlers and data loaders verify the session again before they read or write anything. Hiding a button in the UI is not a security check.
For the broader application picture (headers, input, access control), Diligent Creators has a short web app security basics guide.
An encrypted session cookie
The cookie carries userId, role, issuedAt and expiresAt. AES-256-GCM both encrypts and authenticates the payload, so a flipped bit or a token built with a different key decrypts to nothing. The key comes from SESSION_SECRET, which has to be at least 32 characters, then hashed down to 32 bytes.
export function secretFromEnv(env = process.env) {
const raw = env.SESSION_SECRET;
if (typeof raw !== "string" || raw.length < 32) {
throw new Error("SESSION_SECRET must be a string of at least 32 characters");
}
// Derive a 32-byte key so a passphrase and a hex key both work.
return crypto.createHash("sha256").update(raw).digest();
}
export function encryptSession(payload, key) {
const iv = crypto.randomBytes(12);
const cipher = crypto.createCipheriv("aes-256-gcm", key, iv);
const plaintext = Buffer.from(JSON.stringify(payload), "utf8");
const ciphertext = Buffer.concat([cipher.update(plaintext), cipher.final()]);
const tag = cipher.getAuthTag();
return [iv, ciphertext, tag].map((b) => b.toString("base64url")).join(".");
}
export function decryptSession(token, key) {
if (typeof token !== "string") return null;
const parts = token.split(".");
if (parts.length !== 3) return null;
try {
const [iv, ciphertext, tag] = parts.map((p) => Buffer.from(p, "base64url"));
if (iv.length !== 12 || tag.length !== 16 || ciphertext.length === 0) return null;
const decipher = crypto.createDecipheriv("aes-256-gcm", key, iv);
decipher.setAuthTag(tag);
const plaintext = Buffer.concat([decipher.update(ciphertext), decipher.final()]);
const payload = JSON.parse(plaintext.toString("utf8"));
if (!payload || typeof payload !== "object") return null;
return payload;
} catch {
return null;
}
}
readSession() decrypts, then rejects a missing user id or a timestamp that has passed. buildSession() defaults to a seven-day expiry, which you can shorten.
export function readSession(token, key, now = new Date()) {
const payload = decryptSession(token, key);
if (!payload) return null;
if (typeof payload.userId !== "string" || payload.userId.length === 0) return null;
if (typeof payload.expiresAt !== "number") return null;
if (now.getTime() >= payload.expiresAt) return null;
return payload;
}
Set the cookie on the server, never from client code. The flags I use are the ones the Next.js guide and the Set-Cookie page on MDN both call for: HttpOnly so JavaScript can’t read it, SameSite=Lax so it isn’t sent on most cross-site POSTs, Path=/, and Secure in production so it only travels over HTTPS. Web hosting with free SSL is the hosting side of that last flag: without HTTPS, a production session cookie should not be sent.
export function sessionCookieOptions({ expiresAt, secure = true }) {
return {
httpOnly: true,
secure,
sameSite: "lax",
path: "/",
expires: new Date(expiresAt),
};
}
HttpOnly stops a script on the page from stealing the cookie, but it doesn’t stop the script from acting as the user in the browser. That’s why I still want a tight Content Security Policy in Next.js, rather than treating the cookie flags as the whole XSS defence.
export async function createSessionCookie(userId, cookieStore, env, now = new Date()) {
const key = secretFromEnv(env);
const session = buildSession({ userId, now });
const token = encryptSession(session, key);
cookieStore.set(COOKIE_NAME, token, sessionCookieOptions({
expiresAt: session.expiresAt,
secure: env.NODE_ENV === "production",
}));
}
In a real Server Action you’d call this only after the credentials have been checked, then redirect() to the page the user asked for. The snippet assumes a cookie store with a set method, which is the shape of Next.js’s async cookies() API. Secure is off in development so you can still sign in on http://localhost.
Optimistic checks in proxy.ts
From Next.js 16, middleware.ts is deprecated and renamed to proxy.ts. The export is now proxy, and the default runtime is Node.js. Next.js ships a codemod that renames an existing middleware file and function.
I keep the decision in a plain function so it can be tested without starting Next.js. It only reads the path and the cookie.
export const PUBLIC_PATHS = new Set(["/", "/login", "/signup"]);
export function normalizePathname(pathname) {
if (typeof pathname !== "string" || pathname.length === 0) return "/";
const noQuery = pathname.split("?")[0].split("#")[0];
if (noQuery.length > 1 && noQuery.endsWith("/")) return noQuery.slice(0, -1);
return noQuery || "/";
}
export function isPublicPath(pathname) {
const path = normalizePathname(pathname);
if (PUBLIC_PATHS.has(path)) return true;
// Login return URLs and static files should not be treated as app pages.
if (path.startsWith("/_next/")) return true;
if (path === "/favicon.ico") return true;
return false;
}
export function isProtectedPath(pathname) {
return !isPublicPath(pathname);
}
export function proxyDecision({ pathname, cookieValue, key, now = new Date() }) {
const path = normalizePathname(pathname);
if (!isProtectedPath(path)) {
return { action: "next" };
}
const session = readSession(cookieValue, key, now);
if (!session) {
const login = new URLSearchParams({ from: path });
return { action: "redirect", location: `/login?${login.toString()}` };
}
return { action: "next", session };
}
Public paths (/, /login, /signup, plus /_next assets) go through with no cookie. A protected path with a missing, tampered or expired cookie redirects to /login?from=.... A valid cookie is enough for the Proxy to call next(). There is no database call in this path, on purpose.
import { NextResponse } from "next/server";
import { secretFromEnv, COOKIE_NAME } from "./session";
import { proxyDecision } from "./proxyDecision";
export function proxy(request) {
const decision = proxyDecision({
pathname: request.nextUrl.pathname,
cookieValue: request.cookies.get(COOKIE_NAME)?.value,
key: secretFromEnv(),
});
if (decision.action === "redirect") {
return NextResponse.redirect(new URL(decision.location, request.url));
}
return NextResponse.next();
}
export const config = {
matcher: ["/((?!_next/static|_next/image|favicon.ico).*)"],
};
Two details from the Next.js docs are easy to miss:
- Server Actions are not their own routes. They arrive as POST requests to the page that rendered the form. If your matcher excludes that page, the Proxy also skips the action. Don’t treat a matcher as authorization.
- Don’t look up the user in Proxy. It runs often, including for prefetches. Read the cookie, maybe refresh an expiry, and move on. Load the user later, in the Data Access Layer or the action.
The matcher skips static files and the favicon so those requests don’t go through auth. That’s a convenience, not a security boundary.
Server Action checks that actually authorize
Treat every Server Action like a public endpoint. Someone can POST to it without visiting the page first, so the function has to verify the session on its own. requireSession() is that check. updateDisplayName() calls it before it touches the store.
export function requireSession({ cookieValue, key, now = new Date() }) {
const session = readSession(cookieValue, key, now);
if (!session) {
return { ok: false, error: "unauthorized" };
}
return { ok: true, session };
}
export async function updateDisplayName({ cookieValue, key, name, userStore, now = new Date() }) {
const auth = requireSession({ cookieValue, key, now });
if (!auth.ok) {
return { ok: false, error: auth.error };
}
const invalid = validateDisplayName(name);
if (invalid) {
return { ok: false, error: "invalid", message: invalid };
}
const displayName = name.trim();
await userStore.updateDisplayName(auth.session.userId, displayName);
return { ok: true, displayName };
}
The tests pass in a fake userStore. When the cookie is missing, expired or torn, or the name is too short, the store is never called. A valid session and name produce a write keyed by session.userId, not by an id from the form.
In an App Router project this would be a Server Action: add 'use server', read the cookie with const cookieStore = await cookies(), then call the same helper. Keep the check in the helper so a Route Handler can use it too.
What the tests check
The 17 tests in test-auth.mjs cover the session, the Proxy decision and the action: encrypt/decrypt, including a fresh IV on each encrypt; rejection of tampered, truncated, missing and wrong-key tokens; expiry; cookie flags; Proxy allows public paths and redirects protected ones when the session is bad; and updateDisplayName() writes only for a valid session, keyed by session.userId.
The two I’d keep if I cut the rest are the tamper check and the ‘store was not called’ check on the action. Those are the failures that look fine in a browser and then show up as a support ticket.
What I did not test
- A running Next.js app. I did not start the dev server or send a Server Action POST against a real route.
- Auth.js, Clerk, or any other library on the Next.js list. This sample is a custom session so the checks stay readable.
- Password hashing, OAuth, two-factor auth, or revoking a session in a database. A stateful session (an id in the cookie, the record on the server) is how you sign one user out without rotating the secret for everyone.
- The supply chain around an auth library. If you use one, composer audit, npm audit and Dependabot is the habit I want around it.
FAQ
Is middleware.ts still valid for Next.js authentication?
In Next.js 16 it is deprecated and renamed to proxy.ts. Run the official codemod if you already have a middleware file. The job does not change: an early, cookie-only redirect, with the real authorization in your actions and data layer.
Can I protect Server Actions with Proxy alone?
No. Server Actions can be called with a POST, and a matcher that skips a path also skips actions on that path. Verify the session inside the action.
Should I use Auth.js instead of a custom session?
If you need social login, MFA or a maintained session implementation, start with a library. This sample is for seeing the three layers and for tests you can run without a framework.
Why is the Secure flag off in development?
Browsers won’t send a Secure cookie over HTTP, and local development is usually http://localhost. Turn Secure on in production, which means the site has to be on HTTPS.
How do I revoke a session if the cookie is stateless?
You can’t, except by waiting for expiry or rotating the secret, which signs everyone out. To log one user out of every device, store the session server-side and keep only an id in the cookie.
I’m Shahrukh Akhtar (Shaz3e), CTO & Co-Founder of Diligent Creators Pvt. Ltd., a Technology Executive & Product Builder. I run client delivery and build SaaS products, including EloSync. You can find me on X, LinkedIn, Peerlist and GitHub.
