Advanced

Next.js Authentication Bypass Vulnerability: What You Should Know

Next.js is a React-based web development framework created and maintained by Vercel. It is widely used to build fast, scalable, and SEO-friendly web applications.

Table of Contents


Module 1 — Background: Next.js and the Attack Surface

What Is Next.js?

Next.js is a React-based web development framework created and maintained by Vercel. It is widely used to build fast, scalable, and SEO-friendly web applications.

Key capabilities of Next.js include:

  • Hybrid rendering: supports both static site generation (SSG) and server-side rendering (SSR)
  • API routes: built-in support for backend API endpoints without a separate server
  • File system-based routing: directory structure maps directly to URL routes
  • Built-in CSS and SCSS support
  • Middleware layer: a programmable request interception layer that executes before route handlers

Why Next.js Popularity Matters for Security

Next.js has experienced significant growth in adoption among developers. According to the Stack Overflow Developer Survey:

  • In 2022, Next.js ranked 11th among web frameworks
  • In 2023, it climbed to 6th place

This meteoric rise in popularity means that a significant vulnerability in Next.js sends ripples across a very large segment of the web development community. Any serious flaw has a correspondingly broad blast radius.

How Next.js Middleware Works

Middleware in Next.js is code that runs between an incoming request and the response being sent. Middleware can be stacked, meaning multiple layers can be configured in sequence, with each layer able to inspect, modify, or short-circuit the request or response.

Common middleware use cases include:

Use CaseDescription
Authentication / AuthorizationValidate session tokens or redirect unauthenticated users
Content Security Policy (CSP) validationEnforce security headers on responses
URL rewriting and redirectionRewrite paths or redirect users based on conditions
Rate limitingThrottle requests before they reach route handlers
Geo-blockingRestrict access by geographic region

Middleware is intended to act as a security gate — but as this CVE demonstrates, that gate can be bypassed entirely.


Module 2 — The Vulnerability: CVE-2025-29927

Vulnerability Overview

FieldValue
CVE IDCVE-2025-29927
VendorVercel
Productnext.js
Affected Versions12.x, 13.x, 14.x, 15.x
Vulnerability TypeImproper Authorization
CNA (CVE Numbering Authority)GitHub
CVSS Score9.1 (Critical)

CVE-2025-29927 is an improper authorization flaw affecting self-hosted Next.js applications that rely on middleware for security controls.

Important scope note: This vulnerability specifically targets self-hosted Next.js deployments. Applications hosted on Vercel’s own platform benefit from additional infrastructure-level protections that are not available in self-hosted environments.

CWE Classification

This vulnerability maps to CWE-285: Improper Authorization.

CWE-285 describes situations where software does not perform an access control check, or performs a check in an incorrect location relative to where the protected resource is accessed. In this case, the authorization check (middleware) can be skipped entirely before the route handler runs, resulting in unauthorized access to protected resources.

The x-middleware-subrequest Header: Root Cause

The root cause of this vulnerability is a design flaw in how Next.js handles the internal HTTP header:

x-middleware-subrequest

This header was originally introduced to prevent infinite middleware execution loops. When Next.js makes an internal subrequest (a request triggered by middleware itself), it attaches this header so that the framework knows not to re-execute middleware for that internal call — thereby avoiding infinite recursion.

The problem: any external attacker can forge this header in an inbound HTTP request, causing the middleware stack to be skipped entirely.

How the Exploit Works — Step by Step

  1. An attacker identifies a protected route in a Next.js application — for example, /admin or /api/internal/data.
  2. The attacker crafts an HTTP request to that route and manually adds the x-middleware-subrequest header with a specific value.
  3. Next.js interprets the header as a signal that this request originated internally (i.e., it is already a subrequest), and therefore skips middleware execution to avoid the infinite loop protection.
  4. The request proceeds directly to the route handler, bypassing any authentication or authorization checks that were configured in middleware.
  5. The attacker receives a response as if they were an authenticated, authorized user — achieving unauthorized access.

Header Values by Version

The exact value used in the exploit varies by Next.js version:

For versions prior to 12.2 (legacy page-based routing):

x-middleware-subrequest: pages/_middleware

This value mimics the path of the middleware file in the older Pages Router architecture, which is sufficient to signal to the framework that middleware should be skipped.

For versions 12.2 and above (modern App Router and later):

x-middleware-subrequest: middleware

Or, to exploit the recursion check introduced in Next.js 15, the value can be a repeated pattern — the middleware name repeated five times, colon-separated:

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

The repetition triggers the recursion depth limit check, causing the framework to treat the request as having already gone through middleware the maximum number of times and therefore skip it.

Attack Flow Diagram

sequenceDiagram
    participant A as Attacker
    participant N as Next.js Server
    participant M as Middleware (Auth Check)
    participant R as Route Handler (/admin)

    A->>N: GET /admin<br/>x-middleware-subrequest: middleware
    Note over N: Header detected — <br/>treats as internal subrequest
    N-->>M: SKIP (middleware execution bypassed)
    N->>R: Request forwarded directly
    R->>A: 200 OK — Protected content returned
    Note over A: Unauthorized access achieved

Middleware Bypass Mechanism Diagram

flowchart TD
    A[Incoming HTTP Request] --> B{Does request contain\nx-middleware-subrequest header?}
    B -- No --> C[Execute Middleware Stack]
    C --> D{Auth check passes?}
    D -- Yes --> E[Route Handler]
    D -- No --> F[Redirect / 401 Unauthorized]
    B -- Yes --> G[SKIP Middleware\nVulnerable behavior]
    G --> E
    E --> H[Response returned to client]

    style G fill:#c0392b,color:#fff
    style F fill:#27ae60,color:#fff
    style E fill:#2980b9,color:#fff

Module 3 — CVSS Score and Risk Assessment

CVSS Vector Breakdown

The CVSS v3.1 score for CVE-2025-29927 is 9.1 (Critical). GitHub is the CNA (CVE Numbering Authority) for this vulnerability.

CVSS MetricValueExplanation
Attack VectorNetworkExploitable remotely over the internet
Attack ComplexityLowNo special conditions required — simply send the crafted header
Privileges RequiredNoneNo account or credentials needed by the attacker
User InteractionNoneVictim does not need to click anything or take any action
ScopeUnchangedThe vulnerable component and the impacted component are the same
Confidentiality ImpactHighAttacker can read protected data (APIs, files, records)
Integrity ImpactHighAttacker can modify protected data or state
Availability ImpactNoneThe attack does not directly cause a denial of service

CVSS Score Summary Table

CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:N
Score: 9.1 — CRITICAL

The combination of no privileges required, no user interaction, network-based attack vector, and high impacts on both confidentiality and integrity drives this score into the critical range. This is essentially the worst-case scenario for an authorization bypass: zero-friction exploitation with significant downstream consequences.


Module 4 — Affected Versions and Impact Scope

Affected Versions Diagram

graph LR
    subgraph Affected["Affected Next.js Versions"]
        V12["12.x\nAll builds < 12.3.5"]
        V13["13.x\nAll builds < 13.5.9"]
        V14["14.x\nAll builds < 14.2.2.5"]
        V15["15.x\nAll builds < 15.2.3"]
    end

    subgraph Safe["Patched / Safe"]
        P12["12.3.5"]
        P13["13.5.9"]
        P14["14.2.2.5"]
        P15["15.2.3"]
    end

    V12 -->|Patch to| P12
    V13 -->|Patch to| P13
    V14 -->|Patch to| P14
    V15 -->|Patch to| P15

    style V12 fill:#c0392b,color:#fff
    style V13 fill:#c0392b,color:#fff
    style V14 fill:#c0392b,color:#fff
    style V15 fill:#c0392b,color:#fff
    style P12 fill:#27ae60,color:#fff
    style P13 fill:#27ae60,color:#fff
    style P14 fill:#27ae60,color:#fff
    style P15 fill:#27ae60,color:#fff

Who Is Affected?

This vulnerability affects organizations running self-hosted Next.js applications across four major version lines (12, 13, 14, and 15) that use middleware for authentication or security enforcement.

Risk is not uniform across all deployments. The actual impact depends entirely on what the middleware is protecting:

  • An application using middleware to protect a personal shopping list: minimal impact
  • An enterprise application using middleware to gate access to internal APIs, admin panels, or sensitive user data: severe impact

Impact Categories

1. Data Exposure

An attacker who bypasses middleware gains direct access to:

  • Internal APIs
  • Databases
  • Sensitive files
  • Configuration endpoints

This can lead to the exfiltration of:

  • Customer records
  • Intellectual property
  • Proprietary business analytics

2. Regulatory Compliance Violations

Enterprise applications frequently handle data subject to regulation. A breach resulting from this vulnerability could trigger violations of:

RegulationScope
GDPRPersonal data of EU residents
HIPAAProtected health information (PHI)
PCI DSSCardholder data and payment systems

Consequences include fines, legal liability, and reputational damage.

3. Operational Disruption

Unauthorized access to internal services opens the door to:

  • Destruction or corruption of business-critical data
  • Deployment of ransomware
  • Disruption of service availability

4. Privilege Escalation

Once inside, an attacker may be able to elevate privileges within the application or connected systems, gaining administrator-level access.

5. Persistence and Advanced Threats

After gaining initial access, a sophisticated attacker may:

  • Install backdoors to maintain long-term access
  • Move laterally to other systems
  • Conduct supply chain attacks if the compromised system interfaces with vendors, partners, or other business units

Attack Chain and Escalation Diagram

flowchart TD
    A[Initial Access\nMiddleware bypass via\nx-middleware-subrequest] --> B[Data Exposure\nInternal APIs, databases,\nfiles, analytics]
    B --> C[Compliance Violations\nGDPR / HIPAA / PCI DSS\nfines and legal liability]
    A --> D[Operational Disruption\nRansomware deployment\nService interruption]
    A --> E[Privilege Escalation\nAdministrator access\nacross the application]
    E --> F[Persistence\nBackdoors installed\nLong-term presence]
    F --> G[Supply Chain Attack\nCompromise of vendors\nor connected systems]

    style A fill:#c0392b,color:#fff
    style G fill:#8e44ad,color:#fff

Module 5 — Known Exploitation Status

At the time of publication, no confirmed breaches or active exploitation in the wild had been reported for CVE-2025-29927.

However, a proof-of-concept (PoC) exploit had been published publicly. The existence of a public PoC significantly lowers the barrier for attackers and should be treated as a strong signal to prioritize patching and detection.

The published PoC enables security teams to:

  • Emulate the attack to verify whether their environment is vulnerable
  • Test different types of detection logic (e.g., WAF rules, log alerting) to determine if an attack has taken place
  • Implement and verify mitigations in a controlled environment using tools such as Burp Suite

Recommendation: Do not wait for confirmed exploitation before patching. The CVSS score of 9.1 and the public PoC justify treating this as an urgent remediation item.


Module 6 — Patching and Remediation

Official Patches

Vercel has released official patches across all four affected version lines. Notably, Vercel initially considered not backporting fixes to the older 12.x line given its age, but responded to community feedback and released a patch — a commendable decision.

Patched Versions Diagram

graph TD
    subgraph Required["Required Minimum Patch Level"]
        direction LR
        R15["Next.js 15.x\nUpgrade to 15.2.3"]
        R14["Next.js 14.x\nUpgrade to 14.2.2.5"]
        R13["Next.js 13.x\nUpgrade to 13.5.9"]
        R12["Next.js 12.x\nUpgrade to 12.3.5"]
    end

    style R15 fill:#27ae60,color:#fff
    style R14 fill:#27ae60,color:#fff
    style R13 fill:#27ae60,color:#fff
    style R12 fill:#27ae60,color:#fff
Version LineMinimum Safe Version
15.x15.2.3
14.x14.2.2.5
13.x13.5.9
12.x12.3.5

Workarounds When Patching Is Not Immediately Possible

If an organization cannot patch immediately, the vulnerability can be mitigated by stripping or blocking any incoming request that contains the x-middleware-subrequest header at the infrastructure layer — specifically at a reverse proxy, load balancer, or web application firewall (WAF) sitting in front of the Next.js application.

Critical requirement: The header stripping must be done at the infrastructure level, outside the Next.js application itself. The vulnerability triggers before application-level logic runs, so any mitigation applied within the application code will not be effective.

nginx Workaround

Add the following directive to the relevant location or server block in your nginx configuration to strip the header from all incoming requests before they are proxied to Next.js:

proxy_set_header x-middleware-subrequest "";

This sets the header value to an empty string, effectively removing it from the request seen by the Next.js server.

Apache Workaround

For Apache HTTP Server, use the RequestHeader directive in your virtual host or .htaccess configuration:

RequestHeader unset x-middleware-subrequest

This removes the header entirely from the incoming request before it is forwarded to the Next.js backend.


Module 7 — Defense in Depth and Security Best Practices

Patching and workarounds address the immediate vulnerability, but a robust security posture requires thinking beyond a single fix. The following defense-in-depth measures reduce both the likelihood of exploitation and the blast radius if exploitation occurs.

Four Core Defensive Measures

mindmap
  root((Defense in Depth\nCVE-2025-29927))
    Avoid Sole Reliance on Middleware
      Add server-side validation in API routes
      Validate auth in page handlers
      Never trust middleware as the only gate
    Strengthen RBAC
      Define roles with least privilege
      Limit what bypassed middleware exposes
      Segment sensitive operations by role
    Monitor for x-middleware-subrequest
      Log all incoming request headers
      Alert on presence of this header
      Correlate with unusual access patterns
    Tabletop Exercises
      Simulate exploitation scenarios
      Practice incident response
      Sharpens response time and muscle memory

Defense-in-Depth Remediation Diagram

flowchart LR
    A[Incoming Request] --> B[WAF / Reverse Proxy\nStrip x-middleware-subrequest]
    B --> C[Next.js Middleware\nAuth check — first gate]
    C --> D[Route Handler / API Route\nServer-side re-validation — second gate]
    D --> E{RBAC Check\nDoes user role\npermit this action?}
    E -- Yes --> F[Authorized Response]
    E -- No --> G[403 Forbidden]

    style B fill:#e67e22,color:#fff
    style C fill:#2980b9,color:#fff
    style D fill:#2980b9,color:#fff
    style E fill:#8e44ad,color:#fff
    style F fill:#27ae60,color:#fff
    style G fill:#c0392b,color:#fff

Server-Side Validation Pattern

The fundamental architectural lesson from this CVE is: do not rely solely on middleware for critical security checks. Middleware is a convenience layer — not a security boundary.

The correct pattern is to implement redundant server-side validation in API routes and page handlers, independently of whether middleware runs:

// Example: API route with explicit server-side auth validation
// pages/api/admin/data.ts  (or app/api/admin/data/route.ts)

import { getServerSession } from "next-auth/next";
import { authOptions } from "../auth/[...nextauth]";
import type { NextApiRequest, NextApiResponse } from "next";

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  // Validate the session independently of middleware
  const session = await getServerSession(req, res, authOptions);

  if (!session) {
    return res.status(401).json({ error: "Unauthorized" });
  }

  // Additionally enforce role-based access control
  if (session.user.role !== "admin") {
    return res.status(403).json({ error: "Forbidden" });
  }

  // Safe to proceed — auth is validated at the handler level
  const data = await fetchAdminData();
  return res.status(200).json(data);
}

This pattern ensures that even if middleware is bypassed (via this CVE or any future flaw), the route handler independently rejects unauthorized requests.

Logging and Alerting

Monitoring incoming requests for the presence of the x-middleware-subrequest header is a key indicator of exploitation attempts (IoC). Implement:

  • Structured logging that captures all request headers for routes that are protected by middleware
  • Alerting rules that fire whenever x-middleware-subrequest is detected in an inbound external request
  • Correlation of these alerts with unusual access patterns (e.g., access to /admin, /api/internal/*, or other protected namespaces)
# nginx: log all headers for detection purposes
log_format detailed '$remote_addr - $remote_user [$time_local] '
                    '"$request" $status $body_bytes_sent '
                    '"$http_x_middleware_subrequest"';

access_log /var/log/nginx/access.log detailed;

Tabletop Exercises

Tabletop exercises simulate attack scenarios in a controlled, discussion-based environment. For CVE-2025-29927 specifically, a tabletop exercise should cover:

  1. Detection: How would your team detect an active exploitation attempt? Do your logs capture the relevant header? Are alerting thresholds configured?
  2. Containment: What is the first action taken once an alert fires? Who is notified? What systems are isolated?
  3. Remediation: What is the patching runbook? Who owns it? What is the target time-to-patch?
  4. Post-incident review: What data may have been accessed? What breach notification obligations apply (GDPR 72-hour rule, etc.)?

Regular practice sharpens response time and builds “muscle memory” for the team, reducing chaos during a real incident.


Module 8 — Key Information Summary

FieldDetails
CVECVE-2025-29927
VendorVercel
Productnext.js
Affected Versions12.x, 13.x, 14.x, 15.x (self-hosted deployments)
CWECWE-285: Improper Authorization
CNAGitHub
CVSS Score9.1 — Critical
Attack VectorNetwork
Attack ComplexityLow
Privileges RequiredNone
User InteractionNone
Confidentiality ImpactHigh
Integrity ImpactHigh
Availability ImpactNone
Root Causex-middleware-subrequest header can be forged by external attackers to skip middleware execution
Patch — 15.x15.2.3
Patch — 14.x14.2.2.5
Patch — 13.x13.5.9
Patch — 12.x12.3.5
WorkaroundStrip x-middleware-subrequest header at the reverse proxy / WAF level
IoCsPresence of x-middleware-subrequest header in inbound external requests
Active ExploitationNone confirmed at time of publication (public PoC exists)
Key MitigationsAvoid middleware-only security checks; server-side re-validation; RBAC; monitor for IoC header

Module 9 — References and Further Reading


Search Terms

next.js · authentication · bypass · vulnerability · know · briefings · networking · systems · security · diagram · affected · attack · cvss · versions · header · impact · middleware · patching · remediation · score · workaround · works

More Vulnerability Briefings courses

View all 30

Interested in this course?

Contact us to book it or get a custom training plan for your team.