Threats
5
min read

Next.js Under Attack: CVE-2025-29927 Header Injection and How to Block It

Matthias Luft
March 26, 2025

A single HTTP header. That’s all it takes to bypass authentication in vulnerable Next.js apps.

At the heart of CVE-2025-29927 is a dangerous assumption: that internal headers are out of reach. But when that trust boundary breaks, even robust middleware becomes a liability. Attackers don’t need credentials or exploits—they just need your app to believe the request has already been vetted.

In this post, we’ll break down how the flaw works, demonstrate the real-world impact, and show you how to protect your apps today.

What Is CVE-2025-29927?

CVE-2025-29927 is a critical vulnerability in Next.js that allows attackers to bypass authentication, input validation, and other middleware-based controls by injecting a special HTTP header:x-middleware-subrequest.

This header is meant to be used internally by Next.js to indicate that a request has already passed through its middleware stack. But if an external actor adds this header to their request, Next.js trusts it by default—resulting in middleware logic being skipped.

Why This Vulnerability Is Dangerous

Unlike traditional exploits that require crafted payloads or memory corruption, this issue stems from a logic flaw. It lets attackers use a well-formed, innocuous-looking header to completely bypass critical controls.

The risks include:

  • Authentication bypass: Access to protected routes without credentials.
  • Validation and rate-limit evasion: Middleware that blocks suspicious inputs or limits traffic can be skipped.
  • Silent failure: The exploit doesn’t trigger errors or logs—it looks like a normal request.

Who’s Affected?

Any Next.js application that relies on middleware for security could be at risk. The vulnerability affects multiple versions, with the header’s expected value varying by version:

Next.js Version Required Header Value Required Header Value
(if using /src directory)
< 12.2 x-middleware-subrequest: pages/_middleware
12.2 – 13.1 x-middleware-subrequest: middleware x-middleware-subrequest: src/middleware
≥ 13.2.0 x-middleware-subrequest:
middleware:middleware:middleware:middleware:middleware
x-middleware-subrequest:
src/middleware:src/middleware:src/middleware:src/middleware:src/middleware

Note: Apps deployed on Vercel or Netlify, or apps using static export, are not affected, as middleware isn’t executed in these environments (source)

While there are no official numbers on how many Next.js apps use middleware, Next.js is one of the top 5 most popular web frameworks globally and has over 130,000 stars on GitHub. With many self-hosted apps using middleware for authentication and routing, the number of potentially exposed applications is significant—especially outside managed platforms like Vercel and Netlify.

Want to explore the technical details behind this CVE?

Demonstrating the Bypass

Here’s a simplified example. Imagine a route at /authenticated that is protected by the following Next.js middleware:

// middleware.ts

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

export function middleware(request: NextRequest) {
    const path = request.nextUrl.pathname
	
    const token = request.cookies.get('auth_token')?.value || ''

    if (path === '/authenticated') {
        // Obviously you don't want your authentication logic to look like this
        if (!token || token !== 'valid_user_token') {
            return new NextResponse(null, { 
                status: 403, 
                statusText: 'Forbidden' 
            })
        }
    }
}

export const config = {
    matcher: ['/', '/authenticated']
}

Without the header — request is denied:

curl -s -o /dev/null -w "%{http_code}" http://localhost:3000/authenticated
# 403 Forbidden

With the injected header — request is granted:

curl -H 'x-middleware-subrequest: middleware:middleware:middleware:middleware:middleware' -s -o /dev/null -w "%{http_code}" http://localhost:3000/authenticated
# 200 OK

This demonstrates how middleware can be completely bypassed using a single header.

Multiple security researchers, including ProjectDiscovery and Checkmarx, have highlighted the ease of exploiting this vulnerability—especially in production environments with relaxed header filtering at the edge. These findings reinforce that this is not a theoretical risk.

How to Protect Your Applications

1. Update to a Patched Next.js Version

The Next.js team has patched this issue in the following versions:

  • Next.js 15.x: Fixed in 15.2.3
  • Next.js 14.x: Fixed in 14.2.25
  • Next.js 13.x: Fixed in 13.5.9
  • Next.js 12.x: Fixed in 12.3.5

Official advisory and GitHub Security Advisory detail the fixes.

If you’re running older versions and can’t patch immediately, block requests containing x-middleware-subrequest headers at your load balancer or WAF.

2. Block Suspicious Headers at the Edge (WAF or Load Balancer)

The best short-term protection is to block external requests that include the x-middleware-subrequest header. These headers should never come from the public internet.

Example: AWS WAF Rule

{
  "Name": "filter-nextjs-middleware-header",
  "Priority": 3,
  "Statement": {
    "RegexMatchStatement": {
      "RegexString": ".+",
      "FieldToMatch": {
        "Headers": {
          "MatchPattern": {
            "IncludedHeaders": [
              "x-middleware-subrequest"
            ]
          },
          "MatchScope": "KEY",
          "OversizeHandling": "MATCH"
        }
      },
      "TextTransformations": [
        {
          "Priority": 0,
          "Type": "NONE"
        }
      ]
    }
  },
  "Action": { "Block": {} },
  "VisibilityConfig": {
    "SampledRequestsEnabled": true,
    "CloudWatchMetricsEnabled": true,
    "MetricName": "filter-nextjs-middleware-header"
  }
}

Example: Azure WAF Rule

"customRules": {
    "rules": [
      {
        "action": "Block",
        "enabledState": "Enabled",
        "groupBy": [],
        "matchConditions": [
          {
            "matchValue": [],
            "matchVariable": "RequestHeader",
            "negateCondition": false,
            "operator": "Any",
            "selector": "x-middleware-subrequest",
            "transforms": []
          }
        ],
        "name": "nextjsheaders",
        "priority": 10,
        "rateLimitDurationInMinutes": 1,
        "rateLimitThreshold": 100,
        "ruleType": "MatchRule"
      }
    ]
  }

With the WAF rule deployed, the same malicious request would now return:

$ curl -s -o /dev/null -w "%{http_code}" -H 'x-middleware-subrequest: middleware:middleware:middleware:middleware:middleware' nextjs-demo.us-east-1.elb.amazonaws.com/authenticated
# 403 Forbidden

How Averlon Helps Security Teams Move Faster

While patches and WAF rules are essential, they rely on knowing what to fix. In complex environments, that’s the hard part.

Averlon helps security teams detect and neutralize these issues before they’re exploited:

  1. Discover applications exposed to internal header trust issues.
  2. Leverage attack chain analysis to identify and prioritize the issues that, if exploited, can lead to high-value data.
  3. Autonomously highlight the instance of this vulnerability that matters most—based on business impact, not just CVSS ratings—and when fixed provides the highest value.
  4. Provide enriched context for every finding: where the risk exists, how it can be exploited, and what actions to take to address it.
  5. Automate protection, including generating WAF rules like the one above to mitigate the issue without delay.

Want to see how Averlon identifies logic flaws like this before they go live?

Takeaway: Review Middleware Trust Boundaries

Modern web frameworks like Next.js are powerful—but they’re also shifting security assumptions.

What used to be internal-only signals (like x-middleware-subrequest) are now vulnerable if your app is exposed to the internet. And with edge networks, reverse proxies, and third-party services in the mix, these trust boundaries are blurry at best as various recent attack techniques have shown.

Security teams must ask:

  • Are we trusting headers that users can inject?
  • Do our apps assume internal logic is protected by default?
  • Can we detect and fix these logic flaws before attackers find them?

If any answer is “not sure,” it’s time to act.

Next Steps

  1. Audit your middleware for usage of x-middleware-subrequest
  2. Upgrade your software to the fixed version of Next.js
  3. Deploy WAF rules to block unauthorized headers
  4. Use tools like Averlon to proactively discover and mitigate application-layer risks

Ready to Reduce Cloud Security Noise and Act Faster?

Discover the power of Averlon’s AI-driven insights. Identify and prioritize real threats faster and drive a swift, targeted response to regain control of your cloud. Shrink the time to resolution for critical risk by up to 90%.

CTA image