Skip to content
CyberReps
broken-access-control 7 min read 0 comments 5 cards

Next.js middleware bypass (CVE-2025-29927): when an internal header is client-writable

One request header made self-hosted Next.js skip its middleware, and every auth check inside it. How the recursion guard worked, why the fix had to authenticate the header rather than strip it, and how to spot the same pattern in your own stack.

Before you read

New to security? Four ideas carry this whole story. Any other technical word links to the glossary the first time it appears.

  • Next.js: a popular framework for building websites. An app can run on Vercel's platform or on your own servers (self-hosted), and this bug only hit the second.
  • HTTP header: a line of extra information sent with every web request. Whoever sends the request picks the headers, attackers included.
  • Middleware: code that runs before a page loads, on every request. Many apps use it as their login check: no session, no page.
  • Authorization: deciding who may open what, for example that only logged-in admins reach /admin.

TL;DR

On self-hosted Next.js from 11.1.4 up to the March 2025 patches, sending one header, x-middleware-subrequest, with the middleware's name in it made Next.js skip middleware entirely. Any authorization check that lived only in middleware was gone. Upgrade to 15.2.3, 14.2.25, 13.5.9 or 12.3.5. If you can't, strip that header at your proxy. And stop treating middleware as the only lock on the door.

At a glance

Field Detail
Identifier (CVE, advisory) CVE-2025-29927 · GHSA-f82v-jwr5-mffw
Affected next 11.1.4 to 12.3.4, 13.0.0 to 13.5.8, 14.0 to 14.2.24, 15.0 to 15.2.2
Fixed in 15.2.3 · 14.2.25 · 13.5.9 · 12.3.5 (11.x: workaround only)
Who was exposed Self-hosted apps: next start and output: 'standalone'
Not exposed Vercel, Netlify and Cloudflare Workers deployments; static exports (no middleware)
Severity CVSS 3.1 9.1 Critical (AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:N)
Weakness CWE-285 Improper Authorization
Disclosed 2025-03-21
Exploited in the wild Not listed in CISA KEV (checked 2026-11-03)

The pattern

A component trusts an "internal" signal that arrives on a channel the client can also write to.

Frameworks and proxies pass decisions between their own layers in HTTP headers: this request was already rewritten, this user is authenticated, this is our own subrequest, skip the checks. If the outermost layer doesn't strip or authenticate those headers on the way in, an attacker sends them directly and makes the decision for you.

It's an old family. X-Forwarded-For trusted for an IP allow-list. X-Original-URL overriding the path a backend routes on, behind a proxy that checked a different one. An auth proxy that passes X-Remote-User to a backend you can also reach directly. The fix is always one of two things: strip the header at the edge, or make it unforgeable with a secret only the server knows.

Root cause

Next.js middleware can fetch() the same app. To stop a request from looping through middleware forever, Next.js adds an x-middleware-subrequest header to those subrequests, listing the middleware they passed through. When a request comes in carrying the header, the sandbox that runs middleware counts how often the current middleware's name appears, and at the recursion limit it skips middleware and waves the request through.

This is run() in packages/next/src/server/web/sandbox/sandbox.ts at v15.1.7:

const subreq = params.request.headers[`x-middleware-subrequest`]
const subrequests = typeof subreq === 'string' ? subreq.split(':') : []

const MAX_RECURSION_DEPTH = 5
const depth = subrequests.reduce(
  (acc, curr) => (curr === params.name ? acc + 1 : acc),
  0
)

if (depth >= MAX_RECURSION_DEPTH) {
  return {
    waitUntil: Promise.resolve(),
    response: new runtime.context.Response(null, {
      headers: {
        'x-middleware-next': '1',
      },
    }),
  }
}

x-middleware-next: 1 is what NextResponse.next() sets: carry on to the route. Follow the data:

  • Source: the x-middleware-subrequest request header, fully client-controlled.
  • Decision: depth >= MAX_RECURSION_DEPTH.
  • Effect: the request reaches the route as if middleware had approved it.

params.name is the middleware's name: middleware, or src/middleware in projects with a src/ directory. Older versions didn't count at all. In 12.3.4 the check is subrequests.includes(params.name), so the name had to appear only once. Before 12.2, middleware lived under pages/ and the name was pages/_middleware.

The same run() code is still there in 15.2.3. The fix landed somewhere else.

Exploitation

The whole exploit is one header. In a lab, a fresh Next.js app whose only protection is this middleware:

// middleware.js
import { NextResponse } from "next/server";

export function middleware(req) {
  if (!req.cookies.get("session")) {
    return NextResponse.redirect(new URL("/login", req.url));
  }
}
export const config = { matcher: "/admin/:path*" };

Built with next build, served with next start on localhost, and tested with curl:

curl -i http://127.0.0.1:3000/admin
# 307 -> /login

curl -i http://127.0.0.1:3000/admin \
  -H 'x-middleware-subrequest: middleware:middleware:middleware:middleware:middleware'
# 200, the admin page

Reproduced on 2026-11-03. On 15.2.2: no header gives 307 to /login. Five repetitions give 200 with the admin page. A single middleware still gives 307, because 15.x counts to five. The same three requests against 15.2.3 all give 307.

Auth bypass is the headline, but the researchers showed more. They skipped a Content-Security-Policy that middleware set. On sites that route by locale in middleware, they poisoned the cache with 404s, a denial of service even where nothing sensitive sits behind middleware.

The fix

Next.js already kept a deny-list of internal headers that it deletes from incoming requests. x-middleware-subrequest just wasn't on it:

// packages/next/src/server/lib/server-ipc/utils.ts (15.2.2)
const INTERNAL_HEADERS = [
  'x-middleware-rewrite',
  'x-middleware-redirect',
  'x-middleware-set-cookie',
  'x-middleware-skip',
  'x-middleware-override-headers',
  'x-middleware-next',
  'x-now-route-matches',
  'x-matched-path',
]

Adding it to the list would have broken the loop guard, because the app's own subrequests come back in through the same front door and need the header. So the fix (commit 52a078d, PR #77201, shipped in 15.2.3) authenticates the header instead. Once per process the server picks a random ID. Its own subrequests carry that ID in x-middleware-subrequest-id. Any x-middleware-subrequest that arrives without the matching ID is deleted:

 // router-server.ts: once per server process
+  const randomBytes = new Uint8Array(8)
+  crypto.getRandomValues(randomBytes)
+  const middlewareSubrequestId = Buffer.from(randomBytes).toString('hex')
+  ;(globalThis as any)[Symbol.for('@next/middleware-subrequest-id')] =
+    middlewareSubrequestId

 // server-ipc/utils.ts: filterInternalHeaders(), on every incoming request
+    if (
+      header === 'x-middleware-subrequest' &&
+      headers['x-middleware-subrequest-id'] !==
+        (globalThis as any)[Symbol.for('@next/middleware-subrequest-id')]
+    ) {
+      delete headers['x-middleware-subrequest']
+    }

Fixes that look right and aren't:

  • Moving the auth check earlier in middleware. The whole function is skipped, so nothing inside it runs, wherever it sits.
  • Blocking the header only on /admin at the proxy. It works on any path middleware matches. Strip it on every request.
  • A WAF rule matching the five-times payload. 12.x needs the name once, and src/middleware is a different string. Remove the header; don't pattern-match it.

The deeper fix is in Vercel's own postmortem: "We do not recommend Middleware to be the sole method of protecting routes in your application." Check authorization again where the data is read: in the route handler, the server component, or a shared data-access function.

Finding it in your own code

  • Version: run npm ls next. Self-hosted and inside the ranges above means exposed.
  • Middleware-only auth: find the session check in middleware.* / src/middleware.*, then open the routes it protects. If they never verify the session themselves, you have the pattern, patched or not.
  • Matcher gaps: a matcher of /admin/:path* does not cover /api/admin/.... It's the same failure without any CVE.
  • Edge rule: strip the header for every request. In nginx, proxy_set_header x-middleware-subrequest ""; does it, because an empty value means the header isn't passed on.
  • Logs: a legitimate x-middleware-subrequest only ever comes from the server itself. One arriving from the internet is a probe.
  • Beyond Next.js: list every header your stack treats as internal (X-Forwarded-*, X-Original-URL, X-Remote-User, your own X-Internal-*) and confirm the edge strips or authenticates each one.

Takeaways

  • A header is client input, even when your own framework invented it. Anything an internal layer reads from a request, an attacker can write.
  • Internal signals must be stripped at the edge or authenticated with a secret. A deny-list fails the day someone adds a header and forgets the list.
  • A loop guard that skips security checks is a security check, and deserves the same scrutiny.
  • Middleware is a convenience gate, not the vault door. Re-check authorization where the data is read.
  • When you patch, also strip the header at the proxy, on every path.

References

Found and reported by Rachid Allam (zhero) and Yasser Allam (inzo_).

Timeline

  • 2025-02-27: reported to Vercel through GitHub private reporting
  • 2025-03-01: researchers extend the report to recent versions
  • 2025-03-14: escalated to the Next.js team and confirmed
  • 2025-03-17: fix merged; 14.2.25 released
  • 2025-03-18: 15.2.3 released; CVE assigned
  • 2025-03-21: advisory published
  • 2025-03-22: 13.5.9 backport
  • 2025-03-23: 12.3.5 backport
Upvote1
Share

Keep this one: 5 cards

Add them to your deck and they'll come back for a quick recall right before you'd forget — a minute today, less each time after.

Comments0

No comments yet. Start the conversation.

Log in or create a free account to join the discussion.

Keep reading