In March 2025 a single request header let attackers skip Next.js middleware entirely. Any application that did its authorization only in middleware.ts was open: send the header, and the protected route rendered as if the check had passed. The fix shipped quickly, but the lesson outlasts the patch.
Next.js has since said the quiet part out loud. Version 16 renamed middleware.ts to proxy.ts to make the network boundary explicit, and the official authentication guide says proxy checks should not be your only line of defense. This post covers what the CVE was, the three reasons middleware is not authorization even when patched, and where the checks should live.
What CVE-2025-29927 was
Next.js uses an internal header, x-middleware-subrequest, to stop middleware from recursing into itself. The framework did not distinguish an internal subrequest from an external request that carried the same header, so a client could add it and the middleware would not run. The GitHub advisory GHSA-f82v-jwr5-mffw summarises the impact: it is possible to bypass authorization checks within a Next.js application if the authorization check occurs in middleware.
| Detail | Value |
|---|---|
| CVE | CVE-2025-29927, CVSS 9.1 (GitHub as CNA) |
| Published | 21 March 2025 |
| Fixed in | 12.3.5, 13.5.9, 14.2.25, 15.2.3 |
| Exposed | Self-hosted apps using next start or output: 'standalone', per the Vercel postmortem |
| Workaround | Strip x-middleware-subrequest from external requests before they reach the app |
The postmortem's own advice is the point of this post: "We do not recommend Middleware to be the sole method of protecting routes in your application."
If you still run an affected version anywhere, upgrade it, and strip the header at your load balancer or reverse proxy as well. Removing client-sent x-middleware-* headers at the edge costs nothing.
Reason 1: the matcher decides what is protected
Middleware runs only on the paths its matcher selects. That list is maintained by hand, and it drifts.
// proxy.ts (middleware.ts before Next.js 16)
import { NextRequest, NextResponse } from "next/server";
export default function proxy(req: NextRequest) {
if (!req.cookies.get("session")) {
return NextResponse.redirect(new URL("/login", req.url));
}
return NextResponse.next();
}
export const config = { matcher: ["/dashboard/:path*"] };This protects pages under /dashboard. It does nothing for /api/invoices/123, which the dashboard calls. Even the example matcher in the Next.js authentication guide excludes api paths, because it is written for redirects, not for data protection. Every new route handler outside the matcher is public until someone remembers to widen it, and matcher patterns are easy to get subtly wrong for trailing slashes, locales and rewritten paths.
Reason 2: middleware can only be optimistic
The Next.js guide splits authorization into optimistic checks (read the session cookie, redirect if absent) and secure checks (validate the session against the database, check what this user may do). It recommends proxy only for the optimistic kind, because it runs on every route, including prefetches, and should avoid database calls.
That leaves out the check that matters most. Middleware sees a path, not a record. It cannot know that invoice 123 belongs to another customer, so it cannot stop an insecure direct object reference. Object-level authorization has to run where the record is loaded.
Reason 3: there is more than one way in
A Next.js app has several entry points, and middleware coverage differs between them:
- Route handlers (
app/**/route.ts) are plain HTTP endpoints. - Server actions are POST endpoints that any client can call directly with the action id, from any page. The guide says to treat them like public API endpoints.
- Server components fetch data during render, and their output travels in the RSC payload.
- Layouts do not re-render on client navigation, so a check in a layout is not run on every route change, and a layout that hides its children does not stop them from rendering.
Authorization that lives in one place at the edge cannot follow all of these.
Where the checks belong
Put authorization next to the data. The Next.js guide calls this a Data Access Layer: one server-only module that verifies the session and that every data read and write goes through.
// app/lib/dal.ts
import "server-only";
import { cookies } from "next/headers";
import { decrypt } from "@/app/lib/session";
export async function getSessionUser() {
const token = (await cookies()).get("session")?.value;
const session = await decrypt(token);
return session?.userId ? { id: String(session.userId) } : null;
}A route handler without its own check, protected only by a matcher that does not cover it:
// app/api/invoices/[id]/route.ts
export async function GET(_req: Request, { params }: { params: Promise<{ id: string }> }) {
const { id } = await params;
const invoice = await db.invoice.findUnique({ where: { id } });
return Response.json(invoice);
}The same handler with authentication, ownership in the query and a narrow response:
import { getSessionUser } from "@/app/lib/dal";
export async function GET(_req: Request, { params }: { params: Promise<{ id: string }> }) {
const user = await getSessionUser();
if (!user) return new Response(null, { status: 401 });
const { id } = await params;
const invoice = await db.invoice.findFirst({ where: { id, ownerId: user.id } });
if (!invoice) return new Response(null, { status: 404 });
return Response.json({ id: invoice.id, total: invoice.total, status: invoice.status });
}And a server action, which needs the same treatment even though it is only called from your own form:
"use server";
import { getSessionUser } from "@/app/lib/dal";
export async function deleteInvoice(id: string) {
const user = await getSessionUser();
if (!user) throw new Error("Unauthorized");
await db.invoice.deleteMany({ where: { id, ownerId: user.id } });
}Keep the proxy for what it is good at: redirecting signed-out users to the login page, and protecting static pages that are rendered at build time and never reach your data layer.
Review checklist
- List every
route.tsand every"use server"function. Each one should call the session check itself or go through a data function that does. - Every query keyed by an id from the request should also be scoped to the caller or their tenant.
- Search for authorization logic in
middleware.ts,proxy.tsand layouts, and make sure nothing depends on it alone. - Return explicit fields from handlers and pass narrow objects to client components, not whole database rows.
- Check the
nextversion in every deployed app, and stripx-middleware-*headers from client requests at the edge.
Finding middleware-only auth with Vulkro
Vulkro Core reads the middleware or proxy.ts matcher and the route tree, then asks whether each handler checks anything itself:
vulkro scan . --format json > findings.json
vulkro rbac .
vulkro explain nextjs-middleware-only-auth| Rule | What it flags |
|---|---|
nextjs-middleware-only-auth |
A route handler authenticated only by middleware on a next version affected by CVE-2025-29927, or sitting outside an authenticating matcher, that checks nothing itself |
nextjs-server-action-no-authz |
A server action that writes, or reads by its own arguments, with no authentication |
AUTHZ-HDR-001 |
An auth decision that trusts a client-controlled header, including x-middleware-* |
AUTHZ-PATH-002 |
Middleware that authorizes on a path different from the routed path |
nextjs-rsc-full-record-prop |
A server component passing a full database row to a client component |
vulkro rbac prints which login level each endpoint requires as a matrix, which is a quick way to spot the route handler that nobody wrapped. Whether a given user should see a given record is a business rule, so object-level checks that need that knowledge are reported as not checked rather than passed.
FAQ
What is CVE-2025-29927?
An authorization bypass in Next.js middleware, published in March 2025. A client could send the internal x-middleware-subrequest header to skip middleware, so auth checks done only in middleware did not run. It is fixed in 12.3.5, 13.5.9, 14.2.25 and 15.2.3.
Should I do authentication in Next.js middleware?
Use it for optimistic checks, such as redirecting signed-out users. Do the real checks in route handlers, server actions and a data access layer, close to the data, as the Next.js authentication guide recommends.
What is proxy.ts in Next.js 16?
Next.js 16 replaced middleware.ts with proxy.ts to make the app's network boundary explicit. It runs on the Node.js runtime. middleware.ts still works for Edge runtime use but is deprecated.
See the API security use case and the rbac command docs, or start a 14-day trial. Related: Next.js server actions are public endpoints and IDOR prevention in Express and NestJS.