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

Upgrade first: two critical flaws you must be patched against
FlawCVEWhat it didFixed in
Middleware bypassCVE-2025-29927 (CVSS 9.1)A request with the x-middleware-subrequest header skipped middleware, including any auth check done thereNext.js 12.3.5, 13.5.9, 14.2.25, 15.2.3
React2ShellCVE-2025-55182 (CVSS 10.0)A crafted request to a React Server Components endpoint ran code on the server, without loginReact 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, 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.

Check access where the data is read:

// 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.

"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 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 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.

// 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) 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 calls your actions and routes as different test users, and its Defense Agent adds the missing checks in your repository.

Sources: Next.js data security guide, CVE-2025-29927 research, React security advisory, AWS on React2Shell exploitation, Vercel April 2026 bulletin.

AgentProof for apps built with AI tools checks database settings, exposed keys and unprotected pages in apps made with AI coding tools.