CSP for Next.js: nonces or a static policy, and where AdSense fits
A nonce gives a strict script policy but ends static rendering; a static header keeps pages cached but needs unsafe-inline. How to choose on a Next.js 16 site.
A Content Security Policy for a Next.js site comes down to one choice, and the list of directives is secondary. Either every response carries a fresh nonce, which gives a strict script policy and costs you static rendering, or the policy is a fixed header that keeps pages cacheable and has to allow inline script. Both are legitimate. Which one fits depends on what the site does, and on whether it runs Google ads, because AdSense publishes its own rules about CSP.
The Next.js specifics here come from the documentation that ships with Next.js 16, including the rename of the middleware file convention to proxy.
What the browser does with the policy#
The mechanics below are from the MDN CSP guide and decide everything that follows.
- Once a policy has
default-srcorscript-src, inline<script>content, inline event handler attributes,javascript:URLs andeval()-style APIs are blocked. - A nonce re-allows specific inline scripts. The server generates an unpredictable value per response, puts it in the policy as
'nonce-...'and in thenonceattribute of the intended tags. The server therefore cannot serve the same HTML to everyone. - A hash re-allows a specific script by the SHA-256, 384 or 512 digest of its content. Hash policies can be static, but any change to the script means a new hash.
'strict-dynamic'lets a script that carries a valid nonce or hash load further scripts that carry neither. That is what makes third-party tags manageable: you trust the loader and it vouches for what it loads.'unsafe-inline'is ignored when a nonce or hash is present in the same directive, so a policy can carry it as a fallback for old browsers.Content-Security-Policy-Report-Onlyreports violations without blocking, and a response can carry both headers. It does not work in a<meta>element, and neither doesframe-ancestors, which must be a header and does not fall back todefault-src.
The options, and what each costs#
The Next.js CSP guide describes three approaches. A fourth, a policy that restricts everything except scripts, is worth stating separately because it is what many sites should ship.
| Approach | Script strictness | Rendering | CDN caching | Main cost |
|---|---|---|---|---|
Nonce set in proxy | Strict, no 'unsafe-inline' needed | Every matched page is dynamic | None by default | A server render per request |
Static header with 'unsafe-inline' | Weak: injected inline script runs | Static and ISR keep working | Unchanged | The main XSS benefit of a script policy is gone |
Hashes through experimental.sri | Strict, hash-based | Static generation kept | Works | Experimental, App Router only, cannot handle dynamically generated scripts |
| Static header without any script rule | None for scripts | Unchanged | Unchanged | No script protection, but the other attack classes are covered |
The guide is blunt about nonces. With a nonce policy all pages must be rendered dynamically, so static optimisation and incremental static regeneration stop working, pages cannot be cached by a CDN without extra configuration, and Partial Prerendering is incompatible because the static shell has no access to the nonce. It lists slower initial loads, more server load and higher hosting costs as the consequence. There is no way around the mechanism: a nonce has to differ per response, and a page that was rendered once at build time or revalidation time cannot differ per response.
Why the static script policy needs unsafe-inline#
The static header is the cheapest to run, and its weak spot has a concrete cause. Next.js's App Router streams the server-component payload to the browser inside inline script tags of the form self.__next_f.push(...), emitted into the HTML next to the content. Their content is different on every page, so a header that is the same for every response cannot name a nonce for them, and listing a hash per page is impractical because the content is not known when the header is configured. The SRI option hashes the build's script files, and its limitations section says outright that it cannot handle dynamically generated scripts.
So a static policy that blocks inline script would stop the page from hydrating at all. That leaves script-src 'self' 'unsafe-inline', which lets the page work and means a cross-site scripting bug that manages to inject an inline script is not stopped by the script rule. Say so in the pull request that adds the header, so the next person knows it was a decision.
The other directives keep their value either way. object-src 'none', base-uri 'self', form-action 'self' and frame-ancestors 'none' stop plugin content, base-tag hijacking, form redirection to another origin and clickjacking, and none of them costs a cache hit.
What AdSense changes#
If the site will serve AdSense ads, the third-party tag is no longer a detail. AdSense's CSP guidance says publishers are not required to use a CSP, and that if you do, you must follow its guidance or risk disruption of ad serving. It states that AdSense supports only a strict, nonce-based policy, because the domains it uses change over time and a domain allowlist would go out of date and break ads. Its recommended directives are:
object-src 'none';
script-src 'nonce-{random}' 'unsafe-inline' 'unsafe-eval' 'strict-dynamic' https: http:;
base-uri 'none';The same page says to apply the nonce to every script tag on the page, including the AdSense code and the inline adsbygoogle.push() call, and to test with Content-Security-Policy-Report-Only first. The 'unsafe-inline', https: and http: entries are fallbacks for browsers without 'strict-dynamic' support; browsers that support it ignore them and trust only the nonce.
That rules out the middle row of Table 1 for any page that carries ads. A static script-src 'self' 'unsafe-inline' blocks the ad script, because Google's host is not allowed, and adding a Google host list is the allowlist Google says it does not support. Two options remain for ad pages: a nonce policy on those pages, or no script-src rule on them at all.
Which one for which situation#
| Situation | Policy | Why |
|---|---|---|
| Public content site, no ads, no accounts | Static header, non-script directives only, or with 'unsafe-inline' | Pages stay static; the realistic threats are clickjacking and plugin content, which the other directives stop |
| Site with accounts, payments or other sensitive data | Nonce policy on those routes | An XSS bug has a real target; the cost of dynamic rendering is justified |
| Content site with AdSense | Nonce policy on ad pages, or no script rule while ads are on | Allowlists are unsupported by Google; the nonce route costs static rendering on exactly the pages you are monetising |
| Compliance requirement for a strict policy | Nonce, or SRI if you accept an experimental feature and can roll back | The requirement decides; measure the hosting cost afterwards |
For the AdSense row the choice is a trade between a script rule and cached pages. For a content site the pages that carry ads are the article pages, which are also the ones ISR keeps cheap. The honest default is to enforce the non-script directives and no script rule, run a nonce policy in report-only on the ad pages to see what it would cost and what it would catch, and enforce it only if the threat model asks for it. The hosting-cost side of that comparison is yours to measure: multiply monthly page views by your render time and compare it with what the cached version costs on your host. The consent article covers the scripts that run before and after a consent choice, which are the same scripts this policy has to admit, and static bundles served from GCS shows what the cache headers on the static side look like.
Roll it out in report-only mode#
Whichever policy you choose, start by reporting. Next.js sets headers through an async headers() function in the config. This one is the non-script policy, which is safe to run with or without ads:
const policy = [
"object-src 'none'",
"base-uri 'self'",
"form-action 'self'",
"frame-ancestors 'none'",
"upgrade-insecure-requests",
"report-to csp-endpoint",
].join("; ");
module.exports = {
async headers() {
return [
{
source: "/(.*)",
headers: [
{ key: "Reporting-Endpoints", value: 'csp-endpoint="https://www.example.com/api/csp-report"' },
{ key: "Content-Security-Policy-Report-Only", value: policy },
],
},
];
},
};report-to is the current mechanism and report-uri is deprecated, though MDN advises declaring both until report-to is supported everywhere. The two formats differ, and an endpoint that accepts both has to parse both. For a policy that includes default-src and script-src, take the baseline from the Next.js guide: default-src 'self', script-src 'self' 'unsafe-inline', style-src 'self' 'unsafe-inline', img-src 'self' blob: data:, font-src 'self' and the directives above. The guide adds that 'unsafe-eval' is needed in development only, because React uses eval to rebuild server error stacks in the browser, and is not required in production.
Reports arrive as a POST with Content-Type: application/reports+json: an array of objects whose type is csp-violation and whose body holds blockedURL, effectiveDirective, disposition, sample and lineNumber. A route handler that logs a compact line is enough, and it should cap the body because it is an unauthenticated public endpoint by design:
export async function POST(request: Request) {
const text = await request.text();
if (text.length > 8192) return new Response(null, { status: 413 });
let reports: unknown;
try {
reports = JSON.parse(text);
} catch {
return new Response(null, { status: 400 });
}
for (const r of Array.isArray(reports) ? reports : [reports]) {
const body = (r as { body?: Record<string, unknown> })?.body;
if (!body) continue;
console.log(
JSON.stringify({
msg: "csp-violation",
directive: body.effectiveDirective,
blocked: body.blockedURL,
disposition: body.disposition,
}),
);
}
return new Response(null, { status: 204 });
}Group the reports by effectiveDirective and blockedURL after a few days of traffic and sort the findings into four piles. Your own inline script, such as a theme initialiser, either moves to a file or is accepted knowingly. A host you forgot, such as a font CDN or an embed, goes into the one directive that needs it, never into default-src. Browser extensions produce blockedURL values with extension schemes; ignore them, and de-duplicate in the log pipeline, not the browser, because they are a steady source of noise. Eval-like use in a dependency needs the package found and replaced, with 'unsafe-eval' in production as the last resort.
If you take the nonce route#
The mechanism, from the Next.js guide: a proxy file generates a fresh nonce per request, writes it into the Content-Security-Policy header and an x-nonce request header, and Next.js extracts the nonce from the header during rendering and applies it to framework scripts, page bundles and the inline scripts it generates. Your own <Script> tags need the nonce passed by hand, read from headers() in a server component.
import { NextRequest, NextResponse } from "next/server";
export function proxy(request: NextRequest) {
const nonce = Buffer.from(crypto.randomUUID()).toString("base64");
const csp = [
"object-src 'none'",
"base-uri 'none'",
`script-src 'nonce-${nonce}' 'strict-dynamic' 'unsafe-inline' 'unsafe-eval' https: http:`,
"report-to csp-endpoint",
].join("; ");
const headers = new Headers(request.headers);
headers.set("x-nonce", nonce);
headers.set("Content-Security-Policy", csp);
const response = NextResponse.next({ request: { headers } });
response.headers.set("Content-Security-Policy", csp);
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" },
],
},
],
};The script-src line follows AdSense's recommended policy, including 'unsafe-eval'; whether you can drop that entry is something the report-only stream will show. The matcher is the guide's: it skips API routes, static assets and prefetches. Scope it further, for example to the article routes that carry ads, and pages the proxy does not match keep their static rendering, though the guide's general rule remains that pages receiving a nonce must render dynamically, and a page may need await connection() to be forced into that. Then pass the nonce to the AdSense tag in a server component:
import { headers } from "next/headers";
import Script from "next/script";
export async function AdScript({ client }: { client: string }) {
const nonce = (await headers()).get("x-nonce") ?? undefined;
return (
<Script
id="ad-script"
async
strategy="afterInteractive"
nonce={nonce}
crossOrigin="anonymous"
src={`https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=${client}`}
/>
);
}A nonce page must never be cached with its nonce in the markup, because every visitor would then share it and the protection is gone. That is the reason the guide requires dynamic rendering; do not try to cache these pages without understanding it. 'strict-dynamic' also means whatever a nonced script loads is trusted, so give nonces only to scripts you chose.
Enforce, and keep the next draft reporting#
When the report-only stream is quiet for the pages that matter, rename the header from Content-Security-Policy-Report-Only to Content-Security-Policy, and keep a second report-only header with the next, stricter draft. That gives you a standing way to try tighter rules without risk. A blocked script produces a console message and not an alert, so watch the report volume after every deploy, and read the browser console on key pages as part of the release test, as in E2E tests against a live staging environment. If preview deployments use different origins, build the policy from a value read in one place instead of a hard-coded host list.
And if nobody will read the reports, do not enforce. An enforced policy that no one watches fails silently the next time a third party changes a host.
Related articles
All articles →Design for a site in eight languages with one maintainer: next-intl routing, ICU plurals, CI checks for broken messages, stale-translation tracking, hreflang.
13 min
Register a denied Consent Mode v2 default ahead of the AdSense script in Next.js, let a certified CMP send the updates, and check the order in the browser.
12 min
Derive a width sweep from your own CSS breakpoints, assert no horizontal scroll and 24 px targets in Playwright, and keep screenshots to a reviewed handful.
11 min