Skip to content

Lesson 22 of 27Production Next.js

Securing a Next.js App

Treat Server Actions as public endpoints, never trust proxy alone, keep secrets out of the bundle, set CSP and headers, and patch fast.

17 min read0/4 questions

Your app is deployed, so now it has to stay safe, tested, fast and observable. That is this unit. It is a Friday afternoon and a message lands in the team channel: a critical advisory for React Server Components, rated 10 out of 10, and exploit code is already public. Does it affect you? Which version fixes it? Are your Server Actions even part of the problem? A month later the penetration test report arrives with three findings: an action that lets any logged-in user delete any project, an API key visible in the client bundle, and no Content Security Policy. Every item is specific to how Next.js works. This lesson is the security model a senior brings to a Next.js codebase: what the framework protects, where its protection stops, and the habits that keep you out of incident reports.

Where an attacker can reach your app

Start by listing the doors. A Next.js app looks like a website, but it exposes more server endpoints than most people realize, and only some of them appear in your app/ folder as obvious routes.

The attack surface of a Next.js app
Any client: curl, a script, a browserAny clientcurl, a script, a browserproxy.ts: runs firstproxy.tsruns firstPages and RSC: GET, params, searchParamsPages and RSCGET, params, searchParamsServer Actions: POST + Next-ActionServer ActionsPOST + Next-ActionRoute Handlers: route.tsRoute Handlersroute.tsImage optimizer: /_next/imageImage optimizer/_next/imageDAL: auth checks hereDALauth checks hereDatabaseDatabasematcher skips it

Assume every request is hand-written. The attacker does not use your UI, so anything the UI enforces is a suggestion.

1/5

Server Actions are public endpoints

You saw the rule in Server Actions and Forms. Here is why it is true at the protocol level. When you mark a function with "use server" and use it, Next.js gives it an ID and the client calls it with a plain HTTP POST to the current route, carrying a Next-Action header with that ID and the serialized arguments in the body. Nothing about that request requires your page, your button or your JavaScript. Anyone who has loaded your site once can copy the ID from the network tab and replay it with curl, changing the arguments however they like.

Three consequences follow:

  • Every exported function in a "use server" file is an endpoint. A helper like export async function markAllPaid() in actions.ts, written "for internal use", is callable from the internet if it is referenced from client code. Keep helpers in server-only modules, and keep "use server" files to the actions themselves.
  • TypeScript types do not exist at runtime. deleteProject(id: string) can receive an object, an array or a 10 MB string. Validate every argument with a schema.
  • IDs are guessable. A project ID in a URL or a hidden input is not a secret. Authorization means checking that this user may touch this record, every time. Skipping that check is an IDOR (insecure direct object reference), and it is the most common finding in real Next.js pen tests.
app/projects/actions.ts
"use server";
 
import * as z from "zod";
import { updateTag } from "next/cache";
import { deleteProjectForCurrentUser } from "@/data/projects"; // server-only DAL
 
const Input = z.object({ projectId: z.uuid() });
 
export async function deleteProject(raw: unknown) {
  const parsed = Input.safeParse(raw);
  if (!parsed.success) return { error: "Invalid request" };
 
  // The DAL verifies the session and that the user is an owner of THIS project,
  // inside the WHERE clause of the delete. It throws or returns null otherwise.
  const result = await deleteProjectForCurrentUser(parsed.data.projectId);
  if (!result) return { error: "Not allowed" };
 
  updateTag("projects");
  return { ok: true }; // return only what the UI needs, never the deleted row
}

A page-level check does not cover the actions on that page. If app/admin/page.tsx redirects non-admins, an action defined in the same file still has to check the admin role itself, because the POST never renders the page.

What Next.js does for you, and where it stops

The framework adds real protection. Know each one and its limit, because "Next.js handles that" is a red flag in a security review.

  • Origin check. Actions compare the Origin header with the Host (or X-Forwarded-Host) and reject mismatches. Together with SameSite cookies and POST-only actions, this stops classic CSRF. Behind a reverse proxy that rewrites the host, add your public domain to experimental.serverActions.allowedOrigins. The limit: a request with no Origin header is allowed through with a warning, so the check stops browsers being tricked, not scripts. Scripts were never the CSRF threat anyway; your auth checks handle them.
  • Unguessable, rotating action IDs and dead code elimination: actions that nothing uses are dropped from the build and get no endpoint. The limit: IDs of actions you do use are in your client JavaScript for anyone to read.
  • Encrypted closures. Variables an inline action captures are encrypted before they travel to the browser and back. The limit: encryption is not a place for secrets; don't capture them. When you self-host several instances, set the same NEXT_SERVER_ACTIONS_ENCRYPTION_KEY on all of them, or an action rendered by one instance fails on another.
  • Body size limit (1 MB by default, configurable with experimental.serverActions.bodySizeLimit), which caps the cheapest denial-of-service.
Quick check
A security engineer runs curl -X POST against your app with a valid Next-Action header, a stolen session cookie and no Origin header. Which protection stops the request?
Need a nudge? A hint rules out a wrong answer.

Never rely on proxy alone

In March 2025, CVE-2025-29927 showed why. Middleware (now proxy.ts) used an internal header, x-middleware-subrequest, to avoid running itself recursively. Next.js trusted that header on incoming requests too. An attacker who sent it with the right value made Next.js skip middleware entirely. Apps that did all their auth in middleware were wide open; apps that also checked in the data layer were not. Self-hosted apps were exposed; major hosting platforms were not, because they handled routing differently. It was fixed in 15.2.3, 14.2.25, 13.5.9 and 12.3.5.

CVE-2025-29927: skipping middleware with one header
AttackerNext.js servermiddleware.tsAdmin pageGET /admin (no cookie)run middleware307 to /loginGET /admin + x-middleware-subrequestheader says: already ran, skipadmin HTML

A normal request without a session.

1/6

The general lesson is defence in depth: proxy is for optimistic redirects, headers and rewrites; the binding checks live next to the data. As a cheap extra layer, configure your load balancer or CDN to strip internal framework headers from incoming requests.

Keep secrets out of the browser

Leaks into the client happen in four ways, and each has a guard.

NEXT_PUBLIC_ variables. Any variable with this prefix is inlined into the client JavaScript at build time as a string literal. Rename STRIPE_SECRET_KEY to NEXT_PUBLIC_STRIPE_SECRET_KEY "to make it work in a component" and the secret is now in a public file on your CDN, forever, in every cached copy. Rotating the key is the only fix. Because values are inlined at build time, changing a NEXT_PUBLIC_ value at runtime also does nothing until you rebuild.

Imports. A Client Component that imports a module containing database code pulls that module into the client graph. import "server-only" at the top of every DAL and secrets module makes such an import a build error instead of a leak.

Props and return values. Anything a Server Component passes to a Client Component, and anything an action returns, is serialized into the response. Pass DTOs, as covered in Databases and the Data Access Layer.

Taint, as a backstop. React's experimental taint APIs (experimental_taintObjectReference, experimental_taintUniqueValue, enabled with experimental.taint in next.config.ts) make React throw if a marked object or value crosses to the client. They track by reference, so a copy or a derived value is not protected. Use them as a seatbelt on things like a user row or an API token, not as the plan.

Predict the outputTypeScript

What does this print?

// What the bundler does to client code at build time, simplified:
const env = { NEXT_PUBLIC_API_URL: "https://api.acme.dev", DB_PASSWORD: "hunter2" };
const source = 'fetch(process.env.NEXT_PUBLIC_API_URL); connect(process.env.DB_PASSWORD);';
const bundled = source.replace(/process\.env\.(\w+)/g, (_, name) =>
name.startsWith("NEXT_PUBLIC_") ? JSON.stringify(env[name as keyof typeof env]) : "undefined");
console.log(bundled);
Need a nudge? Hints walk you through it.

Security headers and a Content Security Policy

Set the baseline headers once in next.config.ts:

next.config.ts
import type { NextConfig } from "next";
 
const securityHeaders = [
  { key: "Strict-Transport-Security", value: "max-age=63072000; includeSubDomains; preload" },
  { key: "X-Content-Type-Options", value: "nosniff" },
  { key: "Referrer-Policy", value: "strict-origin-when-cross-origin" },
  { key: "Permissions-Policy", value: "camera=(), microphone=(), geolocation=()" },
  { key: "X-Frame-Options", value: "DENY" }, // older browsers; CSP frame-ancestors is the modern form
];
 
const nextConfig: NextConfig = {
  poweredByHeader: false,
  async headers() {
    return [{ source: "/(.*)", headers: securityHeaders }];
  },
};
 
export default nextConfig;

A Content Security Policy tells the browser which scripts may run, which is your main defence when an XSS bug slips through (the browser-side theory is in Web Security for JS Developers). A strict CSP uses a nonce: a random value generated per request, put in the header, and attached to every script tag you trust. Next.js supports this directly. Generate the nonce in proxy.ts, set the CSP on both the request and the response, and Next.js reads it while rendering and adds it to its own framework scripts automatically:

proxy.ts
import { NextResponse, type NextRequest } from "next/server";
 
export function proxy(request: NextRequest) {
  const nonce = Buffer.from(crypto.randomUUID()).toString("base64");
  const dev = process.env.NODE_ENV === "development";
  const csp = [
    "default-src 'self'",
    `script-src 'self' 'nonce-${nonce}' 'strict-dynamic'${dev ? " 'unsafe-eval'" : ""}`,
    `style-src 'self' 'nonce-${nonce}'`,
    "img-src 'self' blob: data:",
    "object-src 'none'",
    "base-uri 'self'",
    "form-action 'self'",
    "frame-ancestors 'none'",
  ].join("; ");
 
  const requestHeaders = new Headers(request.headers);
  requestHeaders.set("x-nonce", nonce);
  requestHeaders.set("Content-Security-Policy", csp);
 
  const response = NextResponse.next({ request: { headers: requestHeaders } });
  response.headers.set("Content-Security-Policy", csp);
  return response;
}

The trade-off interviewers probe: a nonce must be unique per request, so nonce pages cannot be prerendered. A static page built once has one fixed nonce, which defeats the point. Pages that need the nonce must render at request time (for example by calling await connection()), which costs you the CDN cache. Alternatives: a CSP without nonces set in next.config.ts headers (weaker, since it needs 'unsafe-inline' for scripts), or the experimental Subresource Integrity option (experimental.sri), which uses build-time hashes so pages stay static. Roll out any CSP with Content-Security-Policy-Report-Only first, so you collect violations from third-party scripts before you start blocking them.

Rate limiting and server-side request forgery

Server Actions and Route Handlers that send email, call paid APIs or check passwords need rate limits, or one script runs up your bill or brute-forces logins. The limit must live in a shared store such as Redis: an in-memory counter on serverless resets on every cold start and is separate per instance, so an attacker spread across instances never hits it. Also enable your host's firewall or rate limiting rules; they stop traffic before it costs you compute. Key the limit by user ID for logged-in actions and by IP (from your platform's trusted header) for anonymous ones. Here is the fixed-window logic most limiters start from:

TypeScriptrate-limit.ts
const LIMIT = 3;const WINDOW_MS = 60_000;const store = new Map<string, { count: number; windowStart: number }>(); // Redis in production function allow(key: string, now: number): boolean { const entry = store.get(key); if (!entry || now - entry.windowStart >= WINDOW_MS) { store.set(key, { count: 1, windowStart: now }); return true; } entry.count += 1; return entry.count <= LIMIT;} const attempts = [0, 5_000, 10_000, 15_000, 20_000, 61_000];for (const t of attempts) { console.log(`t=${String(t / 1000).padStart(2)}s login:alice ->`, allow("login:alice", t) ? "200" : "429");}
Output
Press Run (⌘ Enter) to see what happens.

SSRF (server-side request forgery) is when an attacker makes your server fetch a URL of their choice, often an internal one like a cloud metadata endpoint at 169.254.169.254 that hands out credentials. Next.js apps meet it in three places:

  • The image optimizer. /_next/image?url=... fetches remote images that match images.remotePatterns. A pattern of hostname: "**" turns your server into a free image proxy for the whole internet. List exact hosts and path prefixes.
  • Your own fetch calls. A "preview this link" feature or a webhook URL setting fetches user-supplied URLs. Allow-list hosts, resolve and block private IP ranges, disable redirects or re-check after each one, and set a timeout.
  • Trusting the Host header. CVE-2024-34351 let an attacker who controlled the Host header make a Server Action's relative redirect() fetch from a server of their choice (fixed in 14.1.1). The general lesson: never build absolute URLs from request headers unless your infrastructure overwrites them.
Match the pairs0/6 matched

Match each finding to the fix.

Choose an item, then its match on the other side.

Patch like it matters

The biggest risk to most Next.js apps is not a clever bug in your code. It is an old version of the framework. On 3 December 2025, React disclosed CVE-2025-55182 (tracked for Next.js as CVE-2025-66478): a flaw in how React Server Components decoded incoming requests to server function endpoints let an unauthenticated attacker run code on the server. It scored the maximum 10.0. Two details made it severe. First, an app was exposed just by using the App Router with affected versions, even if it defined no Server Actions, because the vulnerable decoding happened before any action was looked up. Second, attacks against unpatched servers were reported within days. Follow-up advisories a week later fixed a denial-of-service and a source code exposure in the same area, so teams that patched once had to patch again.

Next.js security incidents worth knowing
  1. 2024

    CVE-2024-34351

    Host header SSRF through a Server Action's relative redirect. Fixed in 14.1.1.

  2. Mar 2025

    CVE-2025-29927

    Middleware skipped with the internal x-middleware-subrequest header. Self-hosted apps with auth only in middleware were exposed.

  3. Dec 2025

    CVE-2025-55182 / CVE-2025-66478

    Unauthenticated remote code execution in React Server Components request decoding. CVSS 10.0. Apps with no Server Actions were still affected.

  4. Dec 2025

    Follow-up advisories

    Denial of service and source code exposure in the same code path. A second round of upgrades.

What a mature team does:

  • Know your versions. next, react and react-dom are security-critical dependencies. Dependabot or Renovate opens the upgrade PR; a fast CI pipeline lets you merge it the same day.
  • Use the upgrade tooling. npx next upgrade moves you to the latest version with codemods. In Next.js 16, next dev and next build can also remind you when a security advisory affects your installed version (the default policy of experimental.agentUpgrade is security).
  • Watch the official channels. Subscribe to the Next.js and React security advisories on GitHub. Next.js now publishes security releases on a regular schedule, plus emergency releases for critical issues; check the official blog for the current cadence and supported versions.
  • Stay on a supported line. Fixes land on recent major versions. An app stuck two majors behind may have no patched version to move to.
Put it in order4 steps

A critical Next.js advisory is published. Order the response.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
Key terms
IDOR
Insecure direct object reference: changing an ID in a request to access a record the user is not authorized for.
Origin check
Next.js rejects Server Action requests whose Origin host does not match the app's host; requests with no Origin are allowed.
defence in depth
Several independent layers of protection, so one bypassed check (like proxy) does not expose data.
nonce
A random value generated per request and placed in the CSP header and on trusted scripts, so injected scripts cannot run.
SSRF
Server-side request forgery: tricking your server into fetching a URL the attacker chooses, often an internal address.
taint API
Experimental React APIs that throw if a marked object or value is passed to a Client Component.
NEXT_SERVER_ACTIONS_ENCRYPTION_KEY
An environment variable that gives every self-hosted instance the same key for encrypting Server Action closures.