Mustlist

HTTP security headers and CSP for a Next.js App Router app

VerifiedLast verified 15 Nov 2026R@RIDAM7v1.0.0
Suggest a change

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.

Forweb-appsaasdashboarde-commercemarketing-site
Not forpages-router-only-appapi-only-service

Must-have checklist

10 must · 5 should

Must

01

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.

Security
02

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.

Security
03

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.

Performance
04

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.

Security
05

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.

Security
06

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.

UX
07

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.

Security
08

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.

Security
09

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

Security
10

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.

Security

Should

11

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.

Data
12

Set poweredByHeader: false in next.config.

Next.js sends `X-Powered-By: Next.js` by default, and OWASP recommends removing it.

Security
13

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.

UX
14

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.

Security
15

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.

Security

Decisions to make

Asked before building

01Must 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 compared
RecommendedFits your answers

Nonce-based strict CSP in proxy.ts

Best fit when
  • Pages are already dynamic (authenticated app, dashboards, checkout)
  • You handle sensitive data or must avoid 'unsafe-inline'
Avoid when
  • Pages must stay static, ISR or use cacheComponents (Partial Prerendering)
  • You deploy with output 'export' and have no Next.js server
Trade-offs
  • 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()

Best fit when
  • 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
Avoid when
  • Pages handle sensitive data and you rely on CSP to contain XSS
Trade-offs
  • 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

Best fit when
  • Static export or HTML served from a CDN without a Next.js server
  • One baseline policy shared by several apps on one domain
Avoid when
  • You need per-request nonces and have no edge code that rewrites HTML
Trade-offs
  • 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:

ts · 15 lines · illustration
1import { NextResponse, type NextRequest } from 'next/server';
2
3export function proxy(request: NextRequest) {
4 const nonce = Buffer.from(crypto.getRandomValues(new Uint8Array(16))).toString('base64'); // 128 bits
5 const dev = process.env.NODE_ENV === 'development' ? " 'unsafe-eval'" : '';
6 const csp = `script-src 'self' 'nonce-${nonce}' 'strict-dynamic'${dev}; ` +
7 `style-src 'self' 'nonce-${nonce}'; object-src 'none'; base-uri 'none'; ` +
8 `frame-ancestors 'none'; form-action 'self'; default-src 'self'; report-to csp`;
9 const headers = new Headers(request.headers);
10 headers.set('x-nonce', nonce);
11 headers.set('Content-Security-Policy', csp); // Next.js reads the nonce here
12 const response = NextResponse.next({ request: { headers } });
13 response.headers.set('Content-Security-Policy', csp);
14 return response;
15}

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

next>=16.0.0 <17.0.0
  • middleware.ts is deprecated and renamed to proxy.ts (export proxy). Proxy always uses the Node.js runtime; a runtime export throws.
  • Next.js reads the nonce from the request's Content-Security-Policy or Content-Security-Policy-Report-Only header (script-src, else default-src), so forward it with NextResponse.next({ request: { headers } }).
  • Nonces need dynamic rendering: static, ISR and Partial Prerendering (cacheComponents: true) shells have no nonce. Use await connection() or headers() in the root layout.
  • experimental.sri adds integrity to build-time JS chunks only; the inline self.__next_f RSC payload scripts still need a nonce or 'unsafe-inline'.
  • Dev needs 'unsafe-eval' for React debugging, production does not. poweredByHeader: false removes the default X-Powered-By: Next.js.
next>=15.0.0 <16.0.0
  • The nonce code lives in middleware.ts exporting middleware; 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.sri works only with webpack in 15.x, not Turbopack.
  • Partial Prerendering (experimental.ppr) is incompatible with a nonce-based CSP.

Verify checks

10 checks
01

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.

integrationSecurity
02

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.

integrationSecurity
03

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.

unitSecurity
04

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.

e2eSecurity
05

Sign-in (including OAuth popups), checkout with the payment provider's frames, and a dashboard page raise zero securitypolicyviolation events under the enforced policy.

e2eUX
06

A page from another origin cannot display the app in an iframe.

e2eSecurity
07

The production build lists every route covered by the nonce matcher as dynamic, and none of them is served from a prerendered file.

integrationPerformance
08

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.

integrationSecurity
09

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.

integrationData
10

An HTTP header scanner and a CSP evaluator run against the preview deployment report no high-severity header or CSP findings.

scanSecurity

Common mistakes

  • Generating a nonce in proxy.ts but 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-src next 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 preload to HSTS by copying a snippet, before every subdomain is HTTPS.
  • Using Cross-Origin-Opener-Policy: same-origin on pages that open OAuth or payment popups.
  • Setting frame-ancestors or Report-Only through a meta tag, where browsers ignore them.
  • Sending deprecated headers (X-XSS-Protection: 1, Public-Key-Pins, Expect-CT).

Sources

28 sources
Next.js: How to set a Content Security Policynextjs.orgNext.js 15: How to set a Content Security Policynextjs.orgNext.js headers config (security header examples)nextjs.orgNext.js proxy.js reference (matcher, runtime, execution order)nextjs.orgNext.js poweredByHeadernextjs.orgNext.js cacheComponents (Partial Prerendering by default)nextjs.orgNext.js static exports (headers and proxy unsupported)nextjs.orgNext.js source: nonce parsing from request CSP headersgithub.comNext.js source: inline RSC payload scriptsgithub.comOWASP HTTP Headers Cheat Sheetcheatsheetseries.owasp.orgOWASP Content Security Policy Cheat Sheetcheatsheetseries.owasp.orgOWASP REST Security Cheat Sheet (security headers)cheatsheetseries.owasp.orgW3C Content Security Policy Level 3 (Working Draft)www.w3.orgweb.dev: Mitigate XSS with a strict CSPweb.devMDN: CSP script-src ('strict-dynamic')developer.mozilla.orgMDN: CSP report-todeveloper.mozilla.orgMDN: CSP report-uri (deprecated)developer.mozilla.orgMDN: Reporting-Endpointsdeveloper.mozilla.orgMDN: CSP style-src-attrdeveloper.mozilla.orgMDN: Strict-Transport-Securitydeveloper.mozilla.orgMDN: Cross-Origin-Opener-Policydeveloper.mozilla.orgMDN: Referrer-Policydeveloper.mozilla.orgMDN: Permissions-Policy payment directivedeveloper.mozilla.orgHSTS preload list submission requirementshstspreload.orgVercel: Encryption and TLS (default HSTS)vercel.comVercel: Response headersvercel.comStripe: Integration security guide (CSP directives)docs.stripe.comGoogle Tag Platform: Use a Content Security Policydevelopers.google.com