# How to secure a Next.js app

CVE-2025-29927 and React2Shell showed where Next.js apps break. How to secure middleware, Server Actions and data in Next.js.

Next.js had a hard 2025. In March, a header let attackers skip middleware entirely. In December, a flaw in React Server Components gave unauthenticated attackers code execution, and attackers were using it within hours. Both are patched. The lessons apply to every Next.js app.

## Upgrade first: two critical flaws you must be patched against

| Flaw | CVE | What it did | Fixed in |
|---|---|---|---|
| Middleware bypass | [CVE-2025-29927](https://nvd.nist.gov/vuln/detail/CVE-2025-29927) (CVSS 9.1) | A request with the `x-middleware-subrequest` header skipped middleware, including any auth check done there | Next.js 12.3.5, 13.5.9, 14.2.25, 15.2.3 |
| React2Shell | [CVE-2025-55182](https://nvd.nist.gov/vuln/detail/CVE-2025-55182) (CVSS 10.0) | A crafted request to a React Server Components endpoint ran code on the server, without login | React server packages 19.0.1, 19.1.2, 19.2.1, and patched Next.js releases |

React2Shell affected apps that supported Server Components even if they defined no Server Functions. CISA added it to its Known Exploited Vulnerabilities list on December 5, 2025, two days after disclosure. AWS reported China-linked groups exploiting it within hours.

Those were not the last fixes. Next.js shipped more security releases through 2026, including further middleware bypasses in May ([CVE-2026-44573](https://nvd.nist.gov/vuln/detail/CVE-2026-44573), 44574 and 44575) and image-optimizer fixes in October. In November 2026 the safe minimum is **15.5.28 on the 15 line or 16.4.1 on the 16 line**. Run `npm ls next` and upgrade to the latest patch on your line.

## Never put authorization only in middleware

CVE-2025-29927 worked because many apps checked sessions in `middleware.ts` and nowhere else. One header turned that check off, and the May 2026 bypasses found new ways to skip it again. Next.js 16 renamed the file to `proxy.ts`; the rule is the same. It is a good place to redirect logged-out users. It is not a security boundary.

```tweet
author: zhero;
handle: zhero___
date: 2025-03-22
url: https://x.com/zhero___/status/1903482630986977587
Authorization Bypass in Next.js Middleware - CVE-2025-29927

research paper soon! https://t.co/WyFYAxIKsc pic.twitter.com/N04JdAL7ER
```

```tweet
author: Next.js
handle: nextjs
date: 2025-03-22
url: https://x.com/nextjs/status/1903522002431857063
Next.js 15.2.3 includes a security vulnerability patch.

We recommend updating to 15.2.3 or backported patches. If you cannot update, we have included guidance for how to protect your application.

Apps on Vercel, Netlify, and Cloudflare are not affected.https://t.co/9rLVZf1HCt
```

Check access where the data is read:

```ts
// lib/dal.ts — a data access layer
import "server-only";
import { cache } from "react";

export const getInvoice = cache(async (id: string) => {
  const session = await verifySession();          // throws if not signed in
  const invoice = await db.invoice.findFirst({
    where: { id, accountId: session.accountId },  // scope to the owner
  });
  if (!invoice) notFound();
  return invoice;
});
```

Every page, route handler and Server Action calls the data layer, so a skipped middleware or a new route cannot skip the check. The `server-only` import makes the build fail if this file is ever bundled for the browser.

## Treat every Server Action as a public API endpoint

A Server Action compiles to an HTTP endpoint that anyone can call with any arguments. Hiding the button that calls it does nothing.

```ts
"use server";

export async function deleteProject(projectId: string) {
  const session = await verifySession();
  const id = z.string().uuid().parse(projectId);   // validate input
  await db.project.deleteMany({
    where: { id, ownerId: session.userId },        // check ownership
  });
}
```

Server Actions accept only POST requests, and Next.js compares the `Origin` and `Host` headers to block cross-site posts. If you run behind a proxy that changes the host, list trusted origins in `experimental.serverActions.allowedOrigins` rather than turning the check off. On the 16 line, upgrade past 16.1.7: [CVE-2026-27978](https://nvd.nist.gov/vuln/detail/CVE-2026-27978) let a request with a `null` Origin header slip past this check.

If you self-host, make sure you are past 14.1.1: [CVE-2024-34351](https://nvd.nist.gov/vuln/detail/CVE-2024-34351) let a modified `Host` header make Server Actions that redirect fetch attacker-chosen URLs.

## Do not pass whole records to Client Components

Anything passed as a prop to a Client Component is serialized into the page. Passing a full user row sends its password hash, internal flags and email to the browser.

```tsx
// Bad: the whole row reaches the browser
<Profile user={user} />

// Good: pick the fields the component needs
<Profile user={{ name: user.name, avatarUrl: user.avatarUrl }} />
```

Return plain, minimal objects from your data layer for anything the client renders.

## Keep secrets out of NEXT_PUBLIC_ variables

Any environment variable starting with `NEXT_PUBLIC_` is compiled into the JavaScript bundle and is public. Only publishable keys belong there. In April 2026, Vercel disclosed that an attacker who reached its internal systems through a compromised third-party AI tool decrypted customers' environment variables that were not marked sensitive. Vercel advised rotating them and marking secrets as sensitive. Do that for every real secret.

## Lock down the dev server and headers

- Route Handlers and Pages Router API routes have no built-in CSRF protection. Use `SameSite` cookies and check the `Origin` header, or use bearer tokens.
- Do not expose `next dev` to a network. A related bug in Vite's dev server ([CVE-2025-31125](https://nvd.nist.gov/vuln/detail/CVE-2025-31125)) let anyone who could reach it with `--host` read arbitrary files, and CISA has listed it as exploited.
- Set a Content-Security-Policy, `X-Frame-Options` or `frame-ancestors`, and `Referrer-Policy` in `next.config.js` `headers()` or middleware.
- Avoid `dangerouslySetInnerHTML` with any user content; React escapes everything else.
- Restrict `images.remotePatterns` to hosts you trust.

## A Next.js security checklist

1. Next.js on 15.5.28 or 16.4.1 or later; React server packages patched.
2. Auth checked in a server-only data layer, not just middleware or `proxy.ts`.
3. Every Server Action checks session, ownership and input.
4. Client Components receive only the fields they display.
5. No secrets in `NEXT_PUBLIC_` variables; secrets marked sensitive on your host.
6. Security headers set; dev server never exposed.

## AgentProof tests the running app

Upgrades and code review cover the first two items. The rest only show up at runtime, such as a Server Action that deletes another user's project. AgentProof's [Attack Agent](/attack/) calls your actions and routes as different test users, and its [Defense Agent](/defense/) adds the missing checks in your repository.

Sources: [Next.js data security guide](https://nextjs.org/docs/app/guides/data-security), [CVE-2025-29927 research](https://zhero-web-sec.github.io/research-and-things/nextjs-and-the-corrupt-middleware), [React security advisory](https://react.dev/blog/2025/12/03/critical-security-vulnerability-in-react-server-components), [AWS on React2Shell exploitation](https://aws.amazon.com/blogs/security/china-nexus-cyber-threat-groups-rapidly-exploit-react2shell-vulnerability-cve-2025-55182/), [Vercel April 2026 bulletin](https://vercel.com/kb/bulletin/vercel-april-2026-security-incident).

[AgentProof for apps built with AI tools](/solutions/ai-built-apps/) checks database settings, exposed keys and unprotected pages in apps made with AI coding tools.
