← Blog
November 28, 202610 min readVulnerability ResearchAppSecSecurity Engineering

Inside CVE-2025-29927, the header that let requests skip Next.js middleware

In March 2025 one request header, x-middleware-subrequest, let anyone skip the middleware of a self-hosted Next.js app, and with it any authorization check that lived there. A teardown of the loop-prevention code as shipped on npm, the internal-header deny-list it was missing from, the 15.2.3 patch, the disclosure timeline, and where auth checks belong instead.

By The Xalgorix Team

One request header, sent by an anonymous client, was enough to make a self-hosted Next.js server skip its middleware entirely:

GET /admin HTTP/1.1
Host: app.example
x-middleware-subrequest: middleware:middleware:middleware:middleware:middleware

If that middleware was where the app checked the session cookie, /admin rendered for whoever asked. The bug was disclosed on 21 March 2025 as CVE-2025-29927 (GHSA-f82v-jwr5-mffw), rated CVSS 9.1, and credited to researchers Rachid Allam (zhero) and Yasser Allam (inzo_). Public exploit code and a Nuclei template were out within two days.

Twenty months on, the CVE is worth a second look for a reason that outlives Next.js. The flaw was not a parsing trick or a memory bug. It was a framework trusting a message it meant to send only to itself, carried in the one place every client can write to: the request headers. This teardown walks the vulnerable code as shipped on npm, the patch, the disclosure timeline, and what it says about where authorization should live.

A header Next.js used to talk to itself

Next.js middleware runs before routing, in its own sandboxed runtime. Middleware is allowed to call fetch(), including back into the same application. That creates a loop risk: the inner request would hit middleware again, which might fetch again, and so on. To break the loop, the sandbox's patched fetch appends the middleware module's name to a header called x-middleware-subrequest on every outbound request. When a request arrives carrying that name, the sandbox treats it as its own echo and does not run the middleware again.

Here is the check as it ships in the compiled dist/server/web/sandbox/sandbox.js of the next@12.3.4 package (the same logic appears in 13.x):

const subreq = params.request.headers["x-middleware-subrequest"];
const subrequests = typeof subreq === "string" ? subreq.split(":") : [];
if (subrequests.includes(params.name)) {
    return {
        waitUntil: Promise.resolve(),
        response: new runtime.context.Response(null, {
            headers: { "x-middleware-next": "1" }   // "carry on, middleware done"
        })
    };
}

Nothing in that code asks whether the header came from Next.js. params.name is the middleware's module name, which is predictable from the project layout, and the header is read straight from the incoming request. Any client that sends the right string gets the “middleware already ran” response, and the router carries on to the page.

Client request
header set by attacker
Router
forwards headers
Sandbox check
name found in header
Middleware skipped
x-middleware-next: 1
Page renders
no auth check ran
The intended path sets the header from inside middleware. The attack path sets it from outside, and the sandbox cannot tell the difference.

The payload changed with the file layout

Because the header value is just the middleware's name, the exploit string tracks how each Next.js generation named its middleware. Write-ups by ProjectDiscovery and Fastly document three shapes:

  • Before 12.2: middleware lived in pages/_middleware files, so the value is pages/_middleware, or a nested path such as pages/dashboard/_middleware.
  • 12.2 onward: a single root file, so middleware, or src/middleware for projects using a src directory.
  • Later lines: the same name repeated five times, separated by colons.

The repetition comes from a change that let middleware legitimately call itself a few times. In the published packages we checked, it is present from next@14.2.0 and through 15.x; this is the next@15.2.2 code, the last 15.x release before the fix:

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" } }) };
}

The recursion limit turned “name appears once” into “name appears five times”. It changed the payload, not the trust model: the count still came from a header the client controlled.

What skipping middleware actually exposed

The advisory's impact line is precise: it is possible to bypass authorization checks if the authorization check occurs in middleware. How bad that was depended on what each app had put there.

  • Route protection. Apps whose only gate on /admin or /dashboard was a cookie check in middleware served those pages to anyone. Pages that fetched data through a server-side layer that re-checked the session leaked a shell at most.
  • Security headers. Middleware is a common place to set a nonce-based Content Security Policy. Skip it and the response goes out without that policy, which removes a layer of XSS defense.
  • Rewrites and redirects. Geo, locale and A/B routing done in middleware stopped applying. The researchers' write-up also described a cache-poisoning denial of service in some configurations.

Who was exposed depended on hosting more than on code. Vercel's postmortem confirms that self-hosted next start and output: 'standalone' deployments were affected. Static exports were not, because middleware needs a server runtime. Apps hosted on Vercel, Netlify and Cloudflare Workers were not affected either: those platforms run routing in a separate system, so the vulnerable path in the Next.js server never saw the request. Vercel called itself “incidentally invulnerable.”

As of the 27 November 2026 edition of CISA's Known Exploited Vulnerabilities catalog, CVE-2025-29927 is not listed. That means CISA has not added confirmed in-the-wild exploitation, not that nobody tried: a working request was public within days, and scanning a fleet of self-hosted apps for it took one Nuclei template.

The deny-list that was missing one entry

The fix is the most instructive part. Next.js already had a defense against exactly this class of problem. Its router strips a list of internal headers from every external request before anything else sees them. In dist/server/lib/server-ipc/utils.js:

// These are headers that are only used internally and should
// not be honored from the external request
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'
];

x-middleware-subrequest was not on it. It could not simply be added, because the header has to survive when middleware fetches its own app: that inner request also arrives from outside the router's point of view. So 15.2.3 and 14.2.25 authenticate it instead. At startup the router generates a random secret and stores it in a process-global symbol:

// dist/server/lib/router-server.js (next@15.2.3)
const randomBytes = new Uint8Array(8);
crypto.getRandomValues(randomBytes);
const middlewareSubrequestId = Buffer.from(randomBytes).toString('hex');
globalThis[Symbol.for('@next/middleware-subrequest-id')] = middlewareSubrequestId;

The sandbox's fetch attaches that value as x-middleware-subrequest-id on every request middleware makes, and the header filter drops the loop header unless the id matches:

// If this request didn't origin from this session we filter
// out the "x-middleware-subrequest" header so we don't skip
// middleware incorrectly
if (header === 'x-middleware-subrequest' &&
    headers['x-middleware-subrequest-id'] !==
        globalThis[Symbol.for('@next/middleware-subrequest-id')]) {
    delete headers['x-middleware-subrequest'];
}

That is the textbook shape of the fix: an in-band control signal either gets stripped at the trust boundary or carries something an outsider cannot forge. The vulnerable releases had a strip list and simply did not apply it to the one header whose meaning was “skip the security layer”.

Any header your stack uses to tell a later component “this was already checked” (X-Forwarded-For, X-Original-URL, an identity header from an auth proxy, a framework's internal routing hints) is an authorization input. Strip it at the outermost hop you control, or bind it to a secret the client never sees.

Four weeks from report to patch

The postmortem is unusually candid about the timeline, and the gaps in it matter to anyone running a disclosure program. The first report, on 27 February 2025, named only 12.x, which Vercel was planning to drop from support, so it was triaged low. A second email on 1 March widened the scope to current versions. The Next.js team confirmed the bug on 14 March. All times below are as published by Vercel.

Report and triage
27 Feb: private report (12.x)1 Mar: scope widened14 Mar: confirmed
Patch
17 Mar: fix merged, 14.2.2518 Mar: 15.2.3, CVE issued
Disclosure
21 Mar: advisory public22 Mar: 13.5.923 Mar: 12.3.5
Dates from Vercel's postmortem. Backports for 13.x and 12.x shipped after public disclosure, following community feedback.

Vercel also admitted it had not told other hosting providers before disclosure, and responded by setting up a partner mailing list and moving Next.js reports to GitHub private vulnerability reporting. Next.js 11.x never got a patch; the advisory points those users at the workaround of blocking the header at the edge.

Where the authorization check belongs

Before the CVE, the Next.js middleware docs listed authentication and authorization among the scenarios where middleware is “particularly effective”. That sentence was removed in the days after disclosure, DevClass reported. The current authentication guide, which now calls the feature Proxy (proxy.ts), is explicit: use it for optimistic checks that only read the session cookie, because it “should not be your only line of defense in protecting your data”. The real check goes in a Data Access Layer, close to the data:

// lib/dal.ts  -- server-only
import 'server-only';
import { cache } from 'react';
import { cookies } from 'next/headers';
import { redirect } from 'next/navigation';
import { decrypt } from '@/lib/session';
import { db } from '@/lib/db';

export const verifySession = cache(async () => {
  const session = await decrypt((await cookies()).get('session')?.value);
  if (!session?.userId) redirect('/login');
  return { userId: session.userId, role: session.role };
});

export async function getInvoices() {
  const { userId } = await verifySession();   // every read re-checks
  return db.invoice.findMany({ where: { ownerId: userId } });
}

The guide applies the same rule to Server Actions and Route Handlers: treat each as a public API endpoint and verify inside it. The data security guide adds that a page-level check does not extend to the Server Actions defined in that page. An app built this way would have lost its redirect-to-login under CVE-2025-29927 and leaked nothing, because every query still asked who the user was.

Defense in depth still belongs at the edge. Even on patched versions, there is no reason for a client to send Next.js internal headers, so drop them at the reverse proxy:

# nginx, in front of next start
proxy_set_header x-middleware-subrequest "";
proxy_set_header x-middleware-subrequest-id "";

Checking your own apps

For anything self-hosted, the version check is quick: npm ls next (or your lockfile) should show at least 15.2.3, 14.2.25, 13.5.9 or 12.3.5 on the respective line. Then look for the design problem the CVE exposed, which patching does not fix:

  • List every route whose only protection is a matcher in middleware.ts or proxy.ts. Each one should also check the session where it reads data.
  • Search Server Actions and Route Handlers for ones that never call your session helper.
  • On a staging copy you own, request a protected route with and without the five-part header above. A redirect both times is the patched, healthy result.

One caution on automated detection, from Assetnote's analysis: many early checks keyed on rewrite headers in the response, but among the internet-facing apps they looked at, middleware that redirects was more common, and those checks missed it. Version fingerprinting has the opposite problem: it flags a vulnerable build even when every page re-checks auth and nothing leaks. The only way to know is to send the request to a route that should be protected and see what comes back, which means a scanner (Xalgorix included) has to know which routes are meant to be private before it can say the bypass matters.

The broader lesson fits on a sticky note. When one component tells another “the check already happened”, that message is part of your authorization logic. If it travels in a header, assume the client can write it until you have made sure it cannot.

Ready to see it prove a bug?

Start scanning on Cloud →