Nexus Void Research
Next.js, React, Server Actions, Middleware, CVE-2025-29927, CVE-2025-55182, Content Security Policy, How-to
How to Secure a Next.js App: Server Actions, Auth and CSP
How to secure a Next.js app: authorize in every Server Action and route, not just middleware, protect secrets, add headers and CSP, and patch fast.
To secure a Next.js app, check authentication and authorization inside every Server Action, Route Handler and data-access function, not only in middleware. Validate all input on the server, keep secrets out of NEXT_PUBLIC_ variables and client components, set security headers and a Content Security Policy, restrict next/image remote hosts, and keep Next.js and React patched.
Next.js blurs the line between frontend and backend: a single file can render on the server, run in the browser, or expose a public endpoint through a Server Action. That makes it easy to forget which code is reachable from the internet. This guide covers the checks that matter for the App Router, with code you can copy, and the two framework vulnerabilities that show why patching matters.
Why is middleware not enough to protect routes?
Middleware runs before a request reaches a page or route, which makes it a convenient place to redirect logged-out users. It should not be your only check:
It can be bypassed by bugs. CVE-2025-29927, disclosed in March 2025, let attackers skip Next.js middleware entirely by sending a crafted
x-middleware-subrequestheader, so apps that did authorization only in middleware were open. It was fixed in 12.3.5, 13.5.9, 14.2.25 and 15.2.3. Details are in the NVD entry for CVE-2025-29927.Matchers drift. A new route that does not match the middleware's
matcheris unprotected.Server Actions are separate endpoints. They can be called directly with a POST request, regardless of which page imported them.
Use middleware for redirects and coarse checks, and enforce access where the data is read or changed.
Step 1: Put authorization in a data access layer
Centralise data reads and writes in server-only functions that check the user every time:
The server-only package makes the build fail if this file is ever imported into a client component. Scoping by ownerId is the IDOR fix.
Step 2: Treat every Server Action as a public API
Any exported Server Action can be called with a POST request by anyone who finds its ID. Authenticate, authorize and validate inside each one:
Next.js compares the Origin and Host headers on Server Action requests to block cross-site submissions; if you run behind a proxy with a different host, set serverActions.allowedOrigins deliberately rather than turning the check off.
Step 3: Secure Route Handlers the same way
Route Handlers (app/api/.../route.ts) are ordinary HTTP endpoints. Each one needs:
Authentication and authorization at the top of the handler.
Input validation for params, query strings and bodies.
Rate limiting on login, signup, password reset and expensive operations.
Generic error responses with no stack traces.
Step 4: Keep secrets on the server
Only
NEXT_PUBLIC_variables reach the browser, and they are embedded at build time. Never put secret keys, database URLs or service tokens in them.Do not pass sensitive data as props to client components. Anything passed from a Server Component to a Client Component is serialised into the page. Pass only the fields the UI needs.
Import secrets only in server-only modules.
See how to store API keys securely.
Step 5: Set security headers and a CSP
Add headers in next.config.js:
For a Content Security Policy, the Next.js CSP guide shows how to generate a per-request nonce in middleware and apply it to scripts. A nonce-based policy without 'unsafe-inline' is the strongest common setup against XSS.
Step 6: Avoid XSS escape hatches
React escapes JSX by default. XSS in Next.js apps comes from:
dangerouslySetInnerHTMLwith unsanitised content: sanitise with DOMPurify first.href={userUrl}withjavascript:URLs: allow onlyhttp:andhttps:.Markdown or MDX rendered from user input without sanitisation.
Step 7: Restrict next/image and outbound requests
next/image fetches and optimises remote images on your server. Allow only the hosts you use:
An open pattern lets anyone use your server to fetch and resize arbitrary images, costing you money and opening an SSRF path. Apply the same care to any server code that fetches a user-supplied URL; see how to prevent SSRF.
Step 8: Set cookies safely
HttpOnly keeps the session out of reach of injected scripts; sameSite limits cross-site requests.
Step 9: Keep Next.js and React patched
Framework bugs can undo good application code. Besides the 2025 middleware bypass, CVE-2025-55182 in React Server Components allowed remote code execution and was added to CISA's Known Exploited Vulnerabilities catalog on December 5, 2025, after attackers began using it. Apps on affected React and Next.js versions needed to upgrade immediately.
Subscribe to Next.js and React security advisories.
Upgrade promptly when a security release ships.
Run dependency scanning in CI. See how to fix npm audit vulnerabilities.
Next.js security checklist
Check | Done when |
|---|---|
Auth in the data layer | Every read and write checks the user, not just middleware |
Server Actions protected | Each action authenticates, authorizes and validates input |
Route Handlers protected | Auth, validation, rate limits and generic errors |
No secrets in the client | Nothing sensitive in |
server-only imports | Secret-handling modules import |
Headers and CSP | HSTS, nosniff, frame protection, nonce-based CSP |
XSS escape hatches reviewed |
|
next/image restricted |
|
Patched | Next.js and React on current security releases |
How does ARGUS help secure Next.js apps?
Dependency scanning with reachability reads your
package-lock.json,yarn.lockorpnpm-lock.yaml, matches Next.js, React and every other package against OSV advisories, flags CISA KEV entries such as CVE-2025-55182, and marks whether your code imports the vulnerable package.Static analysis and AI taint analysis find XSS sinks such as
dangerouslySetInnerHTML, SSRF and injection in your TypeScript and JavaScript, and follow user input across files.AI business logic analysis looks for missing authorization, IDOR and authentication bypass in Server Actions and Route Handlers.
Secret scanning catches keys committed to the repository, including ones placed in
NEXT_PUBLIC_variables.Pull request review comments before merge, and Assign to Agent opens a fix pull request, including dependency upgrades, for you to review and merge.
Limits: AI passes run when AI scanning is enabled; ARGUS analyses code and does not check the headers your deployed site sends. See ARGUS SCA, or scan a repository free.
Frequently asked questions
How do I secure a Next.js app?
Check authentication and authorization inside every Server Action, Route Handler and data-access function, validate input on the server, keep secrets out of NEXT_PUBLIC_ variables and client components, add security headers and a nonce-based CSP, restrict next/image hosts, set HttpOnly cookies, and keep Next.js and React updated.
Is Next.js middleware enough to protect routes?
No. Middleware is useful for redirects, but CVE-2025-29927 showed it can be bypassed, matchers can miss new routes, and Server Actions can be called directly. Enforce authorization where data is read or changed, in a server-only data access layer and inside each action and handler.
Are Next.js Server Actions secure?
Server Actions are public POST endpoints that anyone can call once they know the action ID. Next.js adds origin checks against cross-site requests, but you must authenticate, authorize and validate input inside every action, exactly as you would in an API route.
How do I protect API routes in Next.js?
In each Route Handler, verify the session, check that the user may access the specific resource, validate params and bodies with a schema library such as Zod, rate-limit sensitive endpoints, and return generic errors. Do not rely on middleware alone.
Are NEXT_PUBLIC_ environment variables safe?
They are safe only for values meant to be public, such as a publishable key or analytics ID. Next.js embeds NEXT_PUBLIC_ variables into the JavaScript sent to browsers at build time, so anyone can read them. Keep secret keys in variables without the prefix, used only on the server.
How do I add a Content Security Policy in Next.js?
Generate a random nonce per request in middleware, set a Content-Security-Policy header that allows scripts with that nonce, and pass the nonce to your scripts. The Next.js documentation has a CSP guide for the App Router. Avoid 'unsafe-inline', which removes most of the protection.
What was CVE-2025-29927 in Next.js?
A critical middleware bypass disclosed in March 2025. A crafted x-middleware-subrequest header made Next.js skip middleware, so apps doing authorization only in middleware were exposed. It was fixed in Next.js 12.3.5, 13.5.9, 14.2.25 and 15.2.3.
How do I prevent XSS in Next.js?
Rely on React's JSX escaping, sanitise any HTML passed to dangerouslySetInnerHTML with DOMPurify, allow only http: and https: URLs in links, sanitise user-supplied Markdown or MDX, and add a nonce-based Content Security Policy as a second layer.
DATA SOURCES
NVD CVE-2025-29927: https://nvd.nist.gov/vuln/detail/CVE-2025-29927 ; CISA KEV (CVE-2025-55182) ; Next.js CSP guide: https://nextjs.org/docs/app/guides/content-security-policy