To set a strict Next.js Content Security Policy, generate a fresh nonce per request in proxy.ts (the file Next.js 16 renamed from middleware.ts), put it in both the Content-Security-Policy response header and a request header, and let Next.js stamp that nonce onto its own <script> tags during server rendering. Pair the nonce with 'strict-dynamic', and accept the trade-off up front: every page that relies on the nonce must be dynamically rendered, so static generation, ISR and CDN caching of HTML are off for those routes.
This guide walks through a working setup on Next.js 16.4.6 (the current latest on npm as of December 2026, which includes the fixes from the November 2026 security update) with React 19.3: the proxy code, how the nonce reaches your components, the static-page trap that silently breaks hydration, third-party scripts, a report-only rollout using the Reporting API, and how to verify everything with curl and browser devtools. All the header output below comes from a real next build && next start of the code shown.
What changed in Next.js 16: middleware is now proxy
If you are following an older tutorial, the first thing that will not match is the file name. The Next.js proxy.js reference is explicit: "The middleware file convention is deprecated and has been renamed to proxy." Its version history lists v16.0.0 as the release where "Middleware is deprecated and renamed to Proxy. Proxy defaults to the Node.js runtime."
Practical consequences for CSP:
- The file is
proxy.tsat the project root (or insrc/), next toapp/. - It exports a function named
proxy(or a default export) instead ofmiddleware. - It runs on the Node.js runtime by default, and setting a
runtimeexport in the file throws an error. That meansBufferand the Nodecryptoglobal are available without edge-runtime workarounds. - A codemod handles the rename:
npx @next/codemod@canary middleware-to-proxy .
Everything else about nonce handling works as it did in Next.js 13.4.20 and later, which the official CSP guide cites as the recommended minimum for proper nonce parsing.
Why nonces, and what strict-dynamic does
A CSP that allowlists hosts (script-src 'self' https://cdn.example.com) is easy to write and easy to bypass: any JSONP endpoint or old library on an allowlisted host becomes a script gadget. Google's strict CSP guidance recommends the opposite model: only scripts carrying an unguessable nonce run, and the nonce must be "newly generated for every response."
'strict-dynamic' is what makes that practical with a bundler. Per MDN's script-src reference, it propagates the trust given to a nonced script "to all the scripts loaded by that root script", and "any allowlist or source expressions such as 'self' or 'unsafe-inline' will be ignored." So when Next.js's nonced runtime lazy-loads a route chunk, the chunk runs; when an attacker injects <script src="https://evil.example/x.js"> through an XSS bug, it does not.
This is defence in depth, not a substitute for output encoding: a strict CSP is what stops one missed escaping bug from turning into script running in your origin, where even phishing-resistant logins like passkeys cannot protect an already-authenticated session.
That second clause matters later. In a browser that supports 'strict-dynamic', the 'self' and any https://www.googletagmanager.com you add to script-src are ignored. They exist only as a fallback for very old browsers.
The proxy.ts that generates the nonce
This is the setup I ran. It follows the official guide, with two additions: the CSP string lives in a helper so the report endpoint and tests can reuse it, and an environment variable switches between enforcing and report-only.
// lib/csp.ts
export function buildCsp(nonce: string, isDev: boolean) {
return `
default-src 'self';
script-src 'self' 'nonce-${nonce}' 'strict-dynamic'${isDev ? " 'unsafe-eval'" : ''};
style-src 'self' 'nonce-${nonce}';
img-src 'self' blob: data:;
font-src 'self';
connect-src 'self';
object-src 'none';
base-uri 'self';
form-action 'self';
frame-ancestors 'none';
upgrade-insecure-requests;
report-to csp-endpoint;
`.replace(/\s{2,}/g, ' ').trim()
}
// proxy.ts
import { NextRequest, NextResponse } from 'next/server'
import { buildCsp } from './lib/csp'
export function proxy(request: NextRequest) {
const nonce = Buffer.from(crypto.randomUUID()).toString('base64')
const isDev = process.env.NODE_ENV === 'development'
const csp = buildCsp(nonce, isDev)
const headerName =
process.env.CSP_REPORT_ONLY === '1'
? 'Content-Security-Policy-Report-Only'
: 'Content-Security-Policy'
// Request headers: how the nonce reaches the renderer and your components
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: what the browser enforces
response.headers.set(headerName, csp)
response.headers.set('Reporting-Endpoints', 'csp-endpoint="/api/csp-report"')
return response
}
export const config = {
matcher: [
{
source: '/((?!api|_next/static|_next/image|favicon.ico).*)',
missing: [
{ type: 'header', key: 'next-router-prefetch' },
{ type: 'header', key: 'purpose', value: 'prefetch' },
],
},
],
}
A few details that are easy to get wrong:
- Set the CSP on the request, not just the response. Next.js finds the nonce by parsing the
Content-Security-Policyrequest header for the'nonce-…'pattern while rendering. If you only set the response header, the browser enforces a nonce that none of your scripts carry, and the page goes blank. Note that the renderer reads the request header namedContent-Security-Policyeven when you sendContent-Security-Policy-Report-Onlyto the browser. - Use
NextResponse.next({ request: { headers } }). The proxy reference warns thatNextResponse.next({ headers })would expose those headers to the client instead of passing them upstream. - The matcher skips static assets and prefetches. Chunks under
_next/staticdo not need a CSP header, and router prefetches should not burn a render. 'unsafe-eval'in development only. The official guide notes React usesevalin dev to reconstruct server error stacks; "Neither React nor Next.js useevalin production by default."
On nonce entropy: the official snippet base64-encodes a UUID v4, which carries 122 random bits, close to the "ideally 128+ bits" web.dev recommends. If you want a full 128 bits, Buffer.from(crypto.getRandomValues(new Uint8Array(16))).toString('base64') works in the same place.
How Next.js applies the nonce for you
The CSP guide lists what Next.js attaches the nonce to automatically: framework scripts, page bundles, inline styles and scripts Next.js generates, and <Script> components given a nonce prop. You do not hand-annotate the framework's own tags. In my build, every one of the nine <script> tags on the home page carried the same nonce as the response header, including the inline RSC payload scripts.
For your own inline or third-party scripts, read the nonce from the request header in a Server Component:
// app/layout.tsx
import { headers } from 'next/headers'
import Script from 'next/script'
export default async function RootLayout({ children }: { children: React.ReactNode }) {
const nonce = (await headers()).get('x-nonce') ?? undefined
return (
<html lang="en">
<body>
{children}
<Script id="boot" nonce={nonce} strategy="afterInteractive">
{`window.__booted = Date.now()`}
</Script>
</body>
</html>
)
}
Calling headers() in the root layout is itself a dynamic API, so every route under it becomes dynamically rendered unless something overrides that. Which brings us to the trap.
Nonces force dynamic rendering, and static pages break silently
The docs state that when you use nonces, "all pages must be dynamically rendered": static optimization and ISR are disabled, HTML cannot be cached at a CDN without extra work, and Partial Prerendering "is incompatible with nonce-based CSP since static shell scripts won't have access to the nonce." In Next.js 16, Partial Prerendering is the default behaviour when you turn on cacheComponents, so a nonce-based CSP and Cache Components do not mix on the same routes.
The dangerous case is a page that is still static. I added an /about page with export const dynamic = 'force-static' to the same app. The build output shows it prerendered:
Route (app)
┌ ƒ /
├ ƒ /_not-found
├ ○ /about
└ ƒ /api/csp-report
ƒ Proxy (Middleware)
The proxy still runs for /about, so the response carries a brand-new nonce in its CSP header. But the HTML was generated at build time, when no request existed, so its script tags have no nonce at all:
$ curl -sI localhost:3123/about | grep -iE 'content-security|x-nextjs-cache'
content-security-policy: default-src 'self'; script-src 'self' 'nonce-ZjZiNTJk...' 'strict-dynamic'; ...
x-nextjs-cache: HIT
$ curl -s localhost:3123/about | grep -oE '<script[^>]*>' | head -2
<script src="/_next/static/chunks/3nt_u_6ar_mmt.js" async="">
<script src="/_next/static/chunks/3lbm-r_1xmrrq.js" async="">
Because 'strict-dynamic' makes the browser ignore 'self', none of those scripts are allowed to run. The page renders its server HTML and then never hydrates: buttons do nothing, client navigation is dead, and nothing fails at build time. Audit your route table for ○ and ● entries after adding a nonce CSP. For pages that must stay static, either force them dynamic (await connection() from next/server at the top of the page is what the docs recommend) or exclude them from the nonce policy and consider the experimental experimental.sri hash-based approach the same guide describes, which keeps static generation but is App Router only and still marked experimental.
Allowing third-party scripts under a Next.js content security policy
With 'strict-dynamic', third-party loaders work as long as the first script is nonced. Google Tag Manager is the common case, and @next/third-parties accepts a nonce:
// app/layout.tsx (excerpt)
import { GoogleTagManager } from '@next/third-parties/google'
import { headers } from 'next/headers'
export default async function RootLayout({ children }: { children: React.ReactNode }) {
const nonce = (await headers()).get('x-nonce') ?? undefined
return (
<html lang="en">
<body>
{children}
<GoogleTagManager gtmId="GTM-XXXXXXX" nonce={nonce} />
</body>
</html>
)
}
What 'strict-dynamic' does not cover is everything that is not a script. A tag manager that loads scripts is fine; the beacons, images and iframes those scripts create still need their own directives:
| What the vendor does | Directive to extend |
|---|---|
fetch/XHR/sendBeacon to collect events |
connect-src |
| Tracking pixels, avatars | img-src |
| Embedded widgets (video, chat, payments) | frame-src |
| Web fonts from a CDN | font-src |
Injected <style> tags or stylesheets |
style-src |
Inline onclick="…" handlers in their markup |
Not fixable with nonces; needs 'unsafe-hashes' or a different vendor |
That last row is the real compatibility limit. Nonces apply to <script> and <style> elements, not to event-handler attributes, and MDN's guidance is to replace those handlers with addEventListener. Old A/B testing and chat snippets that write onclick attributes will break under any strict policy.
Styles: the part that bites React apps
The policy above also puts a nonce on style-src. That covers <style> elements Next.js generates, but not style="…" attributes in server-rendered HTML, because a nonce cannot be attached to an attribute. Server-rendered style={{ ... }} props and some component libraries emit exactly those. If report-only mode floods you with style-src-attr violations, the pragmatic choice many teams make is to add style-src-attr 'unsafe-inline' while keeping style-src strict. Inline style attributes are a far weaker injection vector than scripts, though CSS injection can still be used for data exfiltration, so treat it as a deliberate trade-off, not a default.
Roll out in report-only mode first
Never ship a strict CSP straight to enforcement on an existing app. Send the same policy as Content-Security-Policy-Report-Only for a week or two, collect what would have been blocked, fix or allow it, then flip to enforcing. In the proxy above that is a single environment variable; with CSP_REPORT_ONLY=1 the response header becomes:
content-security-policy-report-only: default-src 'self'; script-src 'self' 'nonce-...' 'strict-dynamic'; ...
Reports go to the endpoint named by report-to, which you declare in the Reporting-Endpoints header. MDN's report-to page describes the format: a POST with Content-Type: application/reports+json whose body is an array of objects with "type": "csp-violation" and a body containing documentURL, effectiveDirective, blockedURL, disposition and more. The same page marks report-to as Baseline "newly available" since March 2026, and notes that browsers supporting report-to ignore the older report-uri, so if you still care about older browsers you can send both.
A minimal collector as a Route Handler that accepts both formats:
// app/api/csp-report/route.ts
export async function POST(request: Request) {
const reports = await request.json()
for (const r of Array.isArray(reports) ? reports : [reports]) {
// Reporting API uses r.body; legacy report-uri uses r['csp-report']
const b = r.body ?? r['csp-report'] ?? {}
console.warn(
'[csp]',
b.effectiveDirective ?? b['effective-directive'],
b.blockedURL ?? b['blocked-uri'],
b.documentURL ?? b['document-uri'],
)
}
return new Response(null, { status: 204 })
}
I posted a sample report to it to confirm parsing, and the server logged [csp] script-src-elem http://localhost:3123/_next/static/chunks/x.js http://localhost:3123/about. In production, send these to your log pipeline rather than console.warn, rate-limit the route (it is unauthenticated by design), and expect noise from browser extensions injecting scripts; filter on blockedURL values such as chrome-extension before alerting. The matcher above excludes /api, so the report endpoint itself does not get a CSP or a render.
Verifying the Next.js CSP with curl and devtools
From the command line, three checks catch most mistakes. Run them against next start, not next dev, because the dev policy includes 'unsafe-eval'.
# 1. The header is present and the nonce changes per request
curl -sI http://localhost:3000/ | grep -i content-security-policy
curl -sI http://localhost:3000/ | grep -i content-security-policy
# 2. Every script tag on a page carries a nonce (expect 0 without one)
curl -s http://localhost:3000/ | grep -oE '<script[^>]*>' | grep -vc 'nonce='
# 3. The nonce in the HTML matches the header for the same response
curl -s -D headers.txt http://localhost:3000/ -o page.html
grep -oE "nonce-[A-Za-z0-9+/=]+" headers.txt | head -1
grep -oE 'nonce="[^"]+"' page.html | sort -u
Two caveats on check 3. First, browsers hide the nonce attribute from the DOM after parsing (it reads as empty in the Elements panel), so compare the raw HTML from curl or the Network tab's response body, not the inspected DOM. Second, if two consecutive requests return the same nonce, something is caching your HTML; with a dynamic route Next.js sends Cache-Control: private, no-cache, no-store, max-age=0, must-revalidate, which is what I saw on the home page.
In Chrome or Firefox devtools:
- Network tab: click the document request and confirm
Content-Security-Policy(or the report-only variant) in the response headers. - Console: violations appear as errors mentioning the blocked URL and the directive. In report-only mode they are reported but the resource still loads.
- Application tab, Reporting API section (Chrome): shows queued and delivered reports and their target endpoint, which helps when reports seem to vanish.
Finally, run the result through a CSP evaluator such as Google's CSP Evaluator and test a real interaction path (login, checkout, any page with embeds) before switching to enforcement.
If you are wiring authentication into the same proxy, keep the CSP logic separate and remember the proxy reference's warning that Server Functions are covered only by the matcher of the route they are called from; authorization still belongs inside each function. Our Server Actions vs tRPC comparison and Better Auth vs Auth.js guide cover those parts.
Frequently Asked Questions
Does Next.js 16 still support middleware.ts for CSP?
The middleware convention is deprecated in Next.js 16 and renamed to proxy. Rename the file to proxy.ts and the exported function to proxy, or run npx @next/codemod@canary middleware-to-proxy .. The nonce logic itself does not change.
Can I use a nonce-based CSP with static pages or ISR?
No. A nonce has to be unique per response, and static HTML is generated once at build time, so its script tags carry no nonce and are blocked. Make those routes dynamic, or use a policy without nonces (or the experimental SRI hash approach) for them.
Why is my Next.js page blank or not interactive after adding a CSP?
Usually one of three things: the nonce was set only on the response and not on the request Content-Security-Policy header, the page is statically prerendered so its scripts have no nonce, or the proxy matcher skips that route. Check the raw HTML with curl and count script tags without nonce=.
Do I need 'unsafe-inline' for Next.js?
Not for scripts. Next.js nonces its own inline scripts when the page is dynamically rendered. You may choose style-src-attr 'unsafe-inline' if server-rendered style attributes are reported, but keep script-src free of 'unsafe-inline'.
Should I use report-to or report-uri?
Use report-to with a Reporting-Endpoints header; MDN lists it as Baseline since March 2026. Browsers that support report-to ignore report-uri, so adding both is a harmless fallback if you need reports from older browsers.
How do I add Google Analytics or GTM under a strict CSP?
Pass the nonce from headers() to <GoogleTagManager nonce={nonce} /> or <Script nonce={nonce}>. 'strict-dynamic' lets the scripts it loads run, but you still need to add the analytics collection hosts to connect-src and img-src.
Conclusion
A nonce-based Next.js content security policy is about forty lines of proxy.ts plus one decision: are you willing to render those pages dynamically? If yes, generate the nonce per request, set it on both the request and response headers, use 'strict-dynamic', run in report-only mode until the reports go quiet, and then enforce. Audit your build output for leftover static routes before you flip the switch, because that is where a strict CSP breaks without telling you. If you inspect violation reports by hand while tuning, a JSON formatter makes the application/reports+json payloads much easier to read.