Send a nonce-based strict CSP ('strict-dynamic', object-src 'none') from proxy.ts on dynamic pages, starting in Report-Only. Set nosniff, Referrer-Policy, Permissions-Policy, X-Frame-Options and HSTS on every route with next.config headers(), and turn off X-Powered-By.
Must-have checklist
Must
On dynamic HTML routes, build the CSP in proxy.ts with a fresh random nonce per request: script-src 'self' 'nonce-…' 'strict-dynamic', object-src 'none', base-uri 'none'.
An allowlist CSP with 'unsafe-inline' still runs injected inline scripts; a per-response nonce does not.
Set the CSP (or Report-Only) header on the forwarded request via NextResponse.next({ request: { headers } }) as well as on the response.
Next.js reads the nonce from the request header; without it its own scripts get no nonce and are blocked.
Render every route that gets the nonce CSP dynamically (await connection() or headers() in the root layout), and do not combine it with cacheComponents (Partial Prerendering).
Prerendered HTML is built with no request, so it has no nonce and its scripts are blocked.
Add 'unsafe-eval' to script-src only when NODE_ENV is development.
React needs eval only for dev debugging; the Next.js CSP guide says neither React nor Next.js uses eval in production.
Pass the nonce to every next/script and @next/third-parties component, and list each vendor's hosts in connect-src, frame-src and img-src.
Under 'strict-dynamic', CSP3 browsers ignore host entries in script-src, so un-nonced vendor scripts are blocked.
Ship a new or tightened CSP as Content-Security-Policy-Report-Only first and enforce it only after reports from real traffic on every page type are clean.
Report-Only blocks nothing, so breakage shows up in reports instead of in front of users.
Send X-Content-Type-Options: nosniff, Referrer-Policy: strict-origin-when-cross-origin and a deny-by-default Permissions-Policy from headers() with source: '/:path*'.
The proxy matcher skips API routes and static files; next.config headers also cover `public/` files.
Block framing with CSP frame-ancestors 'none' (or an origin list) on HTML, plus a matching X-Frame-Options (DENY or SAMEORIGIN) on every response.
frame-ancestors overrides X-Frame-Options where supported; older browsers only know X-Frame-Options.
Send Strict-Transport-Security with max-age of at least 31536000; add includeSubDomains only when every subdomain serves HTTPS, and preload only by explicit decision.
Preload needs includeSubDomains and takes months to undo (hstspreload.org).
In CI, assert the headers on a page, an API route, a public/ file and a 404, and run an e2e pass that fails on any CSP violation.
Should
Add report-to (named in Reporting-Endpoints) and report-uri; the Route Handler accepts application/reports+json and application/csp-report, caps size and rate-limits.
report-uri is deprecated but older browsers only use it; endpoints must be https URLs; report bodies are attacker-controlled.
Set poweredByHeader: false in next.config.
Next.js sends `X-Powered-By: Next.js` by default, and OWASP recommends removing it.
Send Cross-Origin-Opener-Policy: same-origin on HTML pages, or same-origin-allow-popups where OAuth or payment popups must post results back.
same-origin severs the opener link to cross-origin popups.
Keep style-src nonce-based for style elements; if React style props trigger reports, add style-src-attr 'unsafe-inline' instead of 'unsafe-inline' in style-src.
Browsers ignore 'unsafe-inline' in a directive that has a nonce; style-src-attr covers attributes only.
Set each header in one layer only (proxy, headers() or host config), and check the final response in CI.
When layers set the same header, one silently replaces the other.
Decisions to make
Asked before building01Must your HTML pages stay statically generated or cached (static, ISR, or Partial Prerendering with cacheComponents)?
02How is the app served?
03Which third-party scripts or frames will pages load?
04Must other sites embed your pages in an iframe?
05Does every subdomain of your domain serve HTTPS, now and for the long term?
06Do you open OAuth or payment popups that send results back to the opening page?
Options
3 comparedNonce-based strict CSP in proxy.ts
- Pages are already dynamic (authenticated app, dashboards, checkout)
- You handle sensitive data or must avoid 'unsafe-inline'
- Pages must stay static, ISR or use cacheComponents (Partial Prerendering)
- You deploy with output 'export' and have no Next.js server
- Every covered route renders per request, with no static HTML or CDN caching by default
- Every third-party script must receive the nonce
- Proxy runs on every matched request
Static CSP in next.config headers()
- Marketing or docs pages that must stay static, ISR or prerendered
- You want frame-ancestors, object-src, base-uri, form-action and connect-src limits at no per-request cost
- Pages handle sensitive data and you rely on CSP to contain XSS
- App Router inlines RSC payload scripts, so script-src needs 'unsafe-inline', which also lets injected inline scripts run
- experimental.sri adds integrity to JS chunks but does not remove the need for 'unsafe-inline'
Headers set by the host or CDN
Examples, not endorsements: vercel.json headers, Cloudflare response header rules, nginx add_header
- Static export or HTML served from a CDN without a Next.js server
- One baseline policy shared by several apps on one domain
- You need per-request nonces and have no edge code that rewrites HTML
- Same 'unsafe-inline' weakness as a static CSP
- Config lives outside the app, so only a test of the deployed response proves it
Why this approach
A CSP stops injected scripts only when it is strict: a fresh nonce per response plus 'strict-dynamic', with no host allowlist or 'unsafe-inline' deciding which scripts run. In the App Router, Next.js adds the nonce to its own scripts only when it renders the page per request, so the nonce policy belongs in proxy.ts on routes that are already dynamic, which covers most authenticated pages. Pages that must stay static, ISR or prerendered cannot carry a nonce; give them a static CSP from next.config headers() and accept that 'unsafe-inline' scripts weaken its XSS protection. Use host or CDN rules when no Next.js server runs (output: 'export'). Whatever the CSP option, send the other headers on every route from headers().
Lenses
Treat CSP as a second layer behind output encoding. The proxy builds the policy, forwards it on the request so Next.js can read the nonce, and sets it on the response:
Stripe.js also needs its hosts in frame-src (including https://hooks.stripe.com for 3-D Secure) and https://api.stripe.com in connect-src. Stripe does not support cross-origin isolated pages, so skip Cross-Origin-Embedder-Policy: require-corp. Wallet buttons such as Google Pay use the Payment Request API, so keep payment out of a deny-by-default Permissions-Policy on checkout pages. For JSON Route Handlers, OWASP's REST cheat sheet adds Cache-Control: no-store and Content-Security-Policy: frame-ancestors 'none'. Do not send X-XSS-Protection (or send 0), Public-Key-Pins or Expect-CT.
Version notes
middleware.tsis deprecated and renamed toproxy.ts(exportproxy). Proxy always uses the Node.js runtime; aruntimeexport throws.- Next.js reads the nonce from the request's
Content-Security-PolicyorContent-Security-Policy-Report-Onlyheader (script-src, elsedefault-src), so forward it withNextResponse.next({ request: { headers } }). - Nonces need dynamic rendering: static, ISR and Partial Prerendering (
cacheComponents: true) shells have no nonce. Useawait connection()orheaders()in the root layout. experimental.sriaddsintegrityto build-time JS chunks only; the inlineself.__next_fRSC payload scripts still need a nonce or'unsafe-inline'.- Dev needs
'unsafe-eval'for React debugging, production does not.poweredByHeader: falseremoves the defaultX-Powered-By: Next.js.
- The nonce code lives in
middleware.tsexportingmiddleware; the request-header flow is the same as in 16.x. - The 15.x guide's static
headers()example puts'unsafe-eval'in every environment; keep it out of production. experimental.sriworks only with webpack in 15.x, not Turbopack.- Partial Prerendering (
experimental.ppr) is incompatible with a nonce-based CSP.
Verify checks
A page, an API route, a public/ file and a 404 response each carry nosniff, Referrer-Policy, Permissions-Policy and X-Frame-Options, and none carries X-Powered-By.
Two requests to the same page return different nonces, and every script tag in each HTML response carries the nonce from that response's CSP header.
The production CSP builder output contains a nonce source, 'strict-dynamic', object-src 'none', base-uri and frame-ancestors, and contains neither 'unsafe-eval' nor 'unsafe-inline' in script-src.
A test page that renders an inline script without the nonce (as stored XSS would) does not run it, and the browser reports a CSP violation.
Sign-in (including OAuth popups), checkout with the payment provider's frames, and a dashboard page raise zero securitypolicyviolation events under the enforced policy.
A page from another origin cannot display the app in an iframe.
The production build lists every route covered by the nonce matcher as dynamic, and none of them is served from a prerendered file.
Production HTTPS responses carry Strict-Transport-Security with max-age of at least 31536000, and preload appears only if the team chose to submit the domain.
The report endpoint returns 2xx for valid application/reports+json and application/csp-report bodies, rejects oversized bodies, rate-limits bursts, and stores URLs without query strings.
An HTTP header scanner and a CSP evaluator run against the preview deployment report no high-severity header or CSP findings.
Common mistakes
- Generating a nonce in
proxy.tsbut leaving pages statically prerendered, so production scripts carry no nonce and the app does not hydrate. - Setting the CSP only on the response, so Next.js never sees the nonce.
- Listing vendor hosts in
script-srcnext to'strict-dynamic'and expecting that to allow un-nonced scripts. - Shipping
'unsafe-eval'or'unsafe-inline'scripts to production because development needed them. - Enforcing a new policy without a Report-Only phase.
- Relying on the proxy matcher for every header, leaving API routes,
public/files and 404s without them. - Adding
preloadto HSTS by copying a snippet, before every subdomain is HTTPS. - Using
Cross-Origin-Opener-Policy: same-originon pages that open OAuth or payment popups. - Setting
frame-ancestorsor Report-Only through a meta tag, where browsers ignore them. - Sending deprecated headers (
X-XSS-Protection: 1,Public-Key-Pins,Expect-CT).