Security · Nov 15, 2026 · 19 min read

Nonce-Based CSP in Next.js 15: Strict Policy, Report-Only Rollout & Reports

Ship a strict, nonce-based Content Security Policy in Next.js 15 without breaking analytics or styles: middleware, report-only rollout and violation reporting.

Nonce-Based CSP in Next.js 15: Strict Policy, Report-Only Rollout & Reports

Most Next.js apps either ship no Content Security Policy at all or ship one copied from a blog post that includes 'unsafe-inline' in script-src. That second kind feels like security but does almost nothing against cross-site scripting: if an attacker can inject an inline <script>, the policy allows it.

This guide builds a strict, nonce-based CSP for a Next.js 15 App Router project. It covers the middleware, how Next.js picks up the nonce for its own scripts, third-party tools such as analytics, a report-only rollout, a violation-report endpoint you can actually read, and the real cost: nonces force dynamic rendering. A note on Next.js 16 is included at the end, because the file name of the middleware has changed.

What a strict CSP actually protects against

A CSP is a response header that tells the browser which resources a page is allowed to load and execute. For XSS defence, the important directive is script-src. There are two broad styles:

  • Allowlist CSP: script-src 'self' https://www.googletagmanager.com https://cdn.example.com. Easy to read, but allowlists of whole hosts are often bypassable. If any allowed host serves JSONP endpoints or old versions of libraries such as AngularJS, an attacker can use that host to run code. Google's research on this problem is the reason its CSP Evaluator flags many allowlist policies as weak.
  • Strict CSP: script-src 'nonce-R4nd0m' 'strict-dynamic'. Only scripts carrying the per-response random nonce run. Scripts those trusted scripts create programmatically are also allowed, thanks to 'strict-dynamic'. Injected markup can't guess the nonce, so it doesn't run.

The nonce must be unpredictable and unique per response. A nonce that is the same on every request, or cached in HTML at the CDN, is just a password printed on the front page.

Two limits worth stating up front:

  • CSP is a second line of defence. It does not fix the injection bug. You still need to avoid dangerouslySetInnerHTML with untrusted input, sanitize rich text and validate URLs used in href.
  • 'strict-dynamic' allows scripts created with document.createElement('script') by trusted code. If a trusted script has a gadget that loads attacker-controlled URLs, CSP won't save you. That's a much narrower attack surface than "any inline script".

The policy we're aiming for

Here is the target production policy, formatted for readability:

default-src 'self';
script-src 'self' 'nonce-{NONCE}' 'strict-dynamic';
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;

What each line is doing:

  • script-src: 'self' is a fallback for older browsers that don't understand 'strict-dynamic'. Browsers that do support it ignore 'self' and host allowlists when a nonce plus 'strict-dynamic' is present.
  • style-src: nonce-protected styles. This is the line most likely to break things; there's a section on it below.
  • object-src 'none': blocks <object> and <embed>, an old script-execution path.
  • base-uri 'self': stops an injected <base href> from rewriting where your relative script URLs point. It's easy to forget and important with nonces, because nonce-bearing scripts with relative src would otherwise load from the attacker's host.
  • form-action 'self': injected forms can't post credentials elsewhere.
  • frame-ancestors 'none': clickjacking protection, the modern replacement for X-Frame-Options: DENY. Use 'self' or specific origins if you're embedded somewhere legitimately.

Step 1: Generate the nonce in middleware

Next.js has built-in support for this pattern. If the request reaching the renderer carries a Content-Security-Policy header containing a nonce, Next.js parses it and adds that nonce to the framework scripts it injects (the runtime, page chunks, and inline hydration data). Your middleware therefore needs to do three things: generate a nonce, put the policy on the forwarded request, and put it on the response.

Create middleware.ts at the project root (or in src/ if you use that layout):

// middleware.ts
import { NextRequest, NextResponse } from 'next/server';

function buildCsp(nonce: string, isDev: boolean): string {
  const directives: Record<string, string[]> = {
    'default-src': ["'self'"],
    'script-src': [
      "'self'",
      `'nonce-${nonce}'`,
      "'strict-dynamic'",
      // React uses eval in development for better stack traces
      ...(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'"],
  };

  const policy = Object.entries(directives)
    .map(([key, values]) => `${key} ${values.join(' ')}`)
    .join('; ');

  return isDev ? policy : `${policy}; upgrade-insecure-requests`;
}

export function middleware(request: NextRequest) {
  const nonce = Buffer.from(crypto.randomUUID()).toString('base64');
  const isDev = process.env.NODE_ENV === 'development';
  const csp = buildCsp(nonce, isDev);

  // Forward the nonce and policy to the renderer
  const requestHeaders = new Headers(request.headers);
  requestHeaders.set('x-nonce', nonce);
  requestHeaders.set('Content-Security-Policy', csp);

  const response = NextResponse.next({
    request: { headers: requestHeaders },
  });

  // Send the policy to the browser
  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' },
      ],
    },
  ],
};

Some details matter here:

  • Nonce generation. crypto.randomUUID() gives a v4 UUID with 122 random bits from a cryptographically secure source, which is plenty. The Next.js docs use this exact approach. If you prefer raw bytes, crypto.getRandomValues(new Uint8Array(16)) then base64-encode works just as well. Never use Math.random().
  • The matcher. Static assets and API routes don't render HTML, so they don't need a policy, and running middleware on them is wasted work. Prefetch requests are skipped because their responses are RSC payloads, not documents.
  • upgrade-insecure-requests off in development. On http://localhost this directive can cause confusing failures, so it is only added in production.
  • Existing middleware. If you already have middleware for auth or i18n, merge this logic into it. Next.js supports a single middleware file, and the nonce headers must be set on whatever NextResponse you finally return, including redirects and rewrites that render pages.

Step 2: Force dynamic rendering and read the nonce

This is the part people miss. A statically prerendered page is generated at build time, before any request and therefore before any nonce exists. Its HTML contains scripts without a nonce, and your shiny strict policy then blocks your own app. The symptom is a page that renders server HTML but never hydrates: buttons don't work, client components are dead, and the console fills with CSP errors.

Any page served under a nonce policy must render dynamically. Reading request headers does that:

// app/layout.tsx
import { headers } from 'next/headers';
import Script from 'next/script';
import type { ReactNode } from 'react';

export default async function RootLayout({ children }: { children: ReactNode }) {
  const nonce = (await headers()).get('x-nonce') ?? undefined;

  return (
    <html lang="en">
      <body>
        {children}
        <Script
          src="https://plausible.io/js/script.js"
          data-domain="example.com"
          strategy="afterInteractive"
          nonce={nonce}
        />
      </body>
    </html>
  );
}

In Next.js 15, headers() is async, so you await it. Calling it in the root layout opts the whole tree into dynamic rendering. If a page has no reason to read headers but must still be dynamic, call await connection() from next/server at the top of the page component, which exists for exactly this purpose.

You only need to pass nonce manually to scripts you add: next/script components, inline JSON-LD blocks, or theme scripts that prevent a flash of the wrong colour scheme. Next.js handles its own framework scripts automatically.

Inline scripts you write yourself

A common example is a dark-mode script that must run before paint:

<script
  nonce={nonce}
  dangerouslySetInnerHTML={{
    __html: `
      try {
        const t = localStorage.getItem('theme');
        if (t === 'dark') document.documentElement.classList.add('dark');
      } catch {}
    `,
  }}
/>

The content is static, so the use of dangerouslySetInnerHTML is safe here. Never interpolate user data into such a string. If you use a library like next-themes, check whether it accepts a nonce prop; recent versions do, but verify against the version in your lockfile.

Things CSP will block that you might not expect

  • Inline event handlers in raw HTML such as <button>. React's onClick is fine because it isn't an HTML attribute. This mostly bites when you render HTML from a CMS.
  • javascript: URLs. These are blocked, which is a feature.
  • eval and new Function. Some older charting or templating libraries use them. You'll see violations with effectiveDirective: script-src and a blockedURL of eval. The right fix is replacing the library; adding 'unsafe-eval' in production weakens the policy considerably.

Step 3: Decide what to do about styles

Styles are where strict CSPs most often get abandoned, so it's worth deciding this deliberately.

With style-src 'self' 'nonce-...':

  • Stylesheets from your own origin (Tailwind output, CSS Modules, global CSS) work.
  • <style> tags need the nonce. CSS-in-JS libraries that inject styles at runtime (Emotion, styled-components, some component libraries built on them) must be configured with the nonce, typically through a cache or provider option. Each library does this differently, so check its docs.
  • Inline style attributes are blocked when they appear in server-rendered HTML. Nonces can't be attached to attributes. React's style={{...}} set through the DOM after hydration is applied via CSSOM and is generally not blocked, but SSR output that includes style="..." attributes will produce violations. Many UI libraries render these.

You have three realistic options:

  1. Fully strict styles. Best if your project is Tailwind or CSS Modules with few dependencies. Test thoroughly.
  2. Split the directive: keep style-src-elem 'self' 'nonce-...' strict for <style> and <link> elements while allowing style-src-attr 'unsafe-inline' for attributes. This is a useful middle ground; inline style attributes are a much weaker injection vector than full <style> blocks.
  3. style-src 'self' 'unsafe-inline'. A pragmatic choice many production sites make. CSS injection isn't harmless (it can be used for UI redressing and, in some setups, for leaking attribute values via selectors), but it's far less dangerous than script injection.

One important gotcha: if you include a nonce in a directive, browsers ignore 'unsafe-inline' in that same directive. So style-src 'self' 'nonce-abc' 'unsafe-inline' behaves like a strict nonce policy in modern browsers. Pick one approach per directive.

My recommendation for most teams: start with option 2, look at the reports, and tighten to option 1 if the attribute violations turn out to be few and fixable.

Step 4: Roll out in report-only mode

Deploying a new CSP straight to enforcement on a live product is how you discover, from a customer, that checkout uses a payment widget nobody listed. The browser supports a dry run: the Content-Security-Policy-Report-Only header. Violations are reported and logged in the console, but nothing is blocked.

Make the mode an environment variable so promotion to enforcement is a config change, not a code change:

// in middleware()
const enforce = process.env.CSP_ENFORCE === 'true';
const reportDirectives =
  '; report-uri /api/csp-report; report-to csp-endpoint';
const cspWithReporting = csp + reportDirectives;

// The renderer reads the nonce from the request header either way
requestHeaders.set('Content-Security-Policy', csp);

const response = NextResponse.next({ request: { headers: requestHeaders } });

response.headers.set(
  enforce ? 'Content-Security-Policy' : 'Content-Security-Policy-Report-Only',
  cspWithReporting,
);
response.headers.set(
  'Reporting-Endpoints',
  'csp-endpoint="https://example.com/api/csp-report"',
);
return response;

Why both report-uri and report-to? report-uri is deprecated in the spec but still widely supported. report-to plus the Reporting-Endpoints header is the modern Reporting API, but browser support has historically been uneven, with Firefox being the notable laggard. The spec says browsers that support report-to should ignore report-uri, so sending both doesn't double-report in well-behaved browsers. Check current support on MDN before dropping either.

Note that Reporting-Endpoints requires an absolute HTTPS URL. Use an environment variable for the origin so staging reports go to staging.

Step 5: A report endpoint you'll actually read

The two reporting mechanisms send different payloads:

  • report-uri sends Content-Type: application/csp-report with a body like {"csp-report": {"document-uri": ..., "blocked-uri": ..., "effective-directive": ...}}, using hyphenated keys.
  • report-to sends Content-Type: application/reports+json with an array of reports, each with type: "csp-violation" and a body using camelCase keys such as documentURL, blockedURL and effectiveDirective. Browsers may batch and delay these.

Normalize both into one shape:

// app/api/csp-report/route.ts
import { NextRequest } from 'next/server';

type Violation = {
  documentURL: string;
  blockedURL: string;
  directive: string;
  sourceFile?: string;
  lineNumber?: number;
  disposition?: string;
};

const NOISE_PREFIXES = [
  'chrome-extension://',
  'moz-extension://',
  'safari-web-extension://',
];

function normalize(payload: unknown): Violation[] {
  // Reporting API: array of reports
  if (Array.isArray(payload)) {
    return payload
      .filter((r) => r?.type === 'csp-violation' && r.body)
      .map((r) => ({
        documentURL: String(r.body.documentURL ?? ''),
        blockedURL: String(r.body.blockedURL ?? ''),
        directive: String(r.body.effectiveDirective ?? ''),
        sourceFile: r.body.sourceFile,
        lineNumber: r.body.lineNumber,
        disposition: r.body.disposition,
      }));
  }
  // Legacy report-uri format
  const legacy = (payload as any)?.['csp-report'];
  if (legacy) {
    return [{
      documentURL: String(legacy['document-uri'] ?? ''),
      blockedURL: String(legacy['blocked-uri'] ?? ''),
      directive: String(
        legacy['effective-directive'] ?? legacy['violated-directive'] ?? '',
      ),
      sourceFile: legacy['source-file'],
      lineNumber: legacy['line-number'],
      disposition: legacy['disposition'],
    }];
  }
  return [];
}

export async function POST(req: NextRequest) {
  const raw = await req.text();
  if (raw.length > 64_000) return new Response(null, { status: 413 });

  let payload: unknown;
  try {
    payload = JSON.parse(raw);
  } catch {
    return new Response(null, { status: 400 });
  }

  const violations = normalize(payload).filter(
    (v) =>
      !NOISE_PREFIXES.some(
        (p) => v.blockedURL.startsWith(p) || v.sourceFile?.startsWith(p),
      ),
  );

  for (const v of violations) {
    // Replace with your logger / error tracker
    console.warn('[csp]', JSON.stringify(v));
  }

  return new Response(null, { status: 204 });
}

Points to keep in mind when operating this endpoint:

  • It's unauthenticated by design. Anyone can POST garbage to it. Cap the body size (done above), don't store raw payloads without limits, and add rate limiting at your edge or with a store such as Upstash if traffic gets noisy. Never render report contents into an admin page without escaping; blockedURL is attacker-controllable.
  • Strip query strings from documentURL before storing if your URLs can contain tokens or personal data. Browsers already trim some data for cross-origin blockedURL values, but your own page URLs are sent in full.
  • Expect noise. Browser extensions inject scripts and styles into pages and generate violations you can't fix. The prefix filter handles the obvious ones; you'll also see reports with blockedURL values of inline that come from extensions. Group by directive + blockedURL host + sourceFile and look at what recurs across many sessions.
  • Hosted alternatives exist. Sentry, report-uri.com and similar services accept CSP reports and handle aggregation for you. That's often a better use of time than building dashboards.

Worked example: triaging a week of reports

Here's how a typical triage goes, using the kinds of reports you'd expect from a SaaS marketing site plus app. Suppose the grouped reports show these recurring entries:

  1. script-src, blockedURL: https://js.stripe.com/v3, source: your checkout page. Your code loads Stripe.js with a plain <script> tag in a component without a nonce. Fix: load it via next/script with nonce, or through Stripe's loadStripe from @stripe/stripe-js, which injects the script dynamically. If injected by your nonce-bearing bundle, 'strict-dynamic' covers it. Stripe also needs frame-src https://js.stripe.com https://hooks.stripe.com and connect-src https://api.stripe.com; Stripe publishes its required CSP directives in its docs, so copy from there rather than guessing.
  2. connect-src, blockedURL: https://plausible.io. The analytics script loaded fine (nonce) but its beacon request is blocked. Fix: add the host to connect-src. 'strict-dynamic' only affects scripts; fetches, images and frames still need their own directives.
  3. img-src, blockedURL: https://lh3.googleusercontent.com. User avatars from Google sign-in. Fix: add the host, or proxy avatars through next/image so they're served from your origin.
  4. style-src-attr, many entries from a date-picker component. Decision: if you chose option 2 earlier, these won't appear. If you went fully strict, either switch the component or accept style-src-attr 'unsafe-inline'.
  5. script-src, blockedURL: inline, sourceFile from a moz-extension:// URL. Ignore. Add to the noise filter if your prefix filter missed it.

After fixing, redeploy in report-only, confirm the categories you fixed have stopped appearing, and only then flip CSP_ENFORCE=true. Keep the reporting directives in the enforced policy; reports after enforcement are how you learn that a new feature or an injection attempt hit the policy.

Third-party scripts and tag managers

'strict-dynamic' makes most third-party scripts workable: load the entry script with the nonce, and whatever it injects via DOM APIs is trusted. A few patterns still cause trouble:

  • Google Tag Manager loads with a nonce via next/script (or @next/third-parties), and tags it injects as script elements are allowed under 'strict-dynamic'. Custom HTML tags that rely on document.write are parser-inserted and won't be covered. GTM has documented nonce-aware setups; follow Google's current guidance. More importantly, recognise that a tag manager lets anyone with GTM access run arbitrary JavaScript on your pages. Your CSP effectively trusts every person with publish rights in that container.
  • Embedded widgets in iframes (YouTube, Calendly, Intercom's messenger) need frame-src entries. The script inside the iframe runs under the iframe's own policy, not yours.
  • Scripts that use eval. Some A/B testing and session-replay tools historically required 'unsafe-eval'. Check whether the vendor offers a CSP-compatible mode before weakening the policy for everyone.

A useful exercise: list every third party that appears in your final policy and write down who at your company owns the relationship with it. Hosts nobody can account for are good candidates for removal.

The performance and caching trade-off

Nonces have a real cost: every HTML response is unique, so pages can't be statically prerendered and their HTML can't be cached at a CDN. For an app behind login, that's often fine because those pages were dynamic anyway. For a marketing site that previously served static HTML from the edge, it means server rendering on every request, higher time-to-first-byte and higher compute bills.

Options to consider:

  • Scope the nonce policy. Apply the strict nonce policy to the authenticated app (/app/*, /dashboard/*), where XSS is most dangerous because sessions and user data live there, and use a different policy for static marketing pages. Tighten the matcher accordingly.
  • Hash-based CSP for static pages. Instead of a nonce, list SHA-256 hashes of allowed scripts: script-src 'sha256-...' 'strict-dynamic'. Hashes are fixed at build time, so they're cache-friendly. Next.js 15 has an experimental Subresource Integrity option (experimental.sri.algorithm in next.config) that adds integrity hashes to framework scripts at build time, aimed at this use case. It was webpack-only and experimental when introduced, so check the current docs for your exact version before relying on it.
  • Static page, separate concern. A marketing page with no user data, no login state and no user-generated content has much less to lose from XSS. A moderate policy (no 'unsafe-inline' scripts, strong object-src, base-uri and frame-ancestors) is a reasonable compromise there.

Testing the policy in CI

Policies rot. Someone adds a script tag without a nonce, and it only fails in production. A small Playwright test catches the two most common regressions: the header disappearing and violations on key pages.

// e2e/csp.spec.ts
import { test, expect } from '@playwright/test';

const PAGES = ['/', '/login', '/dashboard', '/checkout'];

for (const path of PAGES) {
  test(`no CSP violations on ${path}`, async ({ page }) => {
    const violations: string[] = [];

    await page.addInitScript(() => {
      document.addEventListener('securitypolicyviolation', (e) => {
        (window as any).__csp = (window as any).__csp || [];
        (window as any).__csp.push(`${e.effectiveDirective} ${e.blockedURI}`);
      });
    });

    const response = await page.goto(path);
    const header =
      response?.headers()['content-security-policy'] ??
      response?.headers()['content-security-policy-report-only'];

    expect(header).toBeTruthy();
    expect(header).toContain("'strict-dynamic'");
    expect(header).not.toMatch(/script-src[^;]*'unsafe-inline'/);

    await page.waitForLoadState('networkidle');
    violations.push(...(await page.evaluate(() => (window as any).__csp ?? [])));
    expect(violations).toEqual([]);
  });
}

test('nonce changes between requests', async ({ request }) => {
  const a = (await request.get('/')).headers()['content-security-policy'];
  const b = (await request.get('/')).headers()['content-security-policy'];
  const nonce = (h?: string) => h?.match(/'nonce-([^']+)'/)?.[1];
  expect(nonce(a)).toBeTruthy();
  expect(nonce(a)).not.toEqual(nonce(b));
});

The last test is the important one. A nonce that stays the same between requests usually means a caching layer (your CDN, a reverse proxy, or a page that accidentally became static) is serving stored HTML. That silently turns your nonce into a constant.

Run the tests against a production build (next build && next start), not the dev server, because dev adds 'unsafe-eval' and behaves differently.

Also paste the final policy into Google's CSP Evaluator once; it flags common mistakes like a missing object-src or base-uri.

Optional hardening: Trusted Types

Once the strict CSP is stable, the next step is DOM-XSS protection with Trusted Types: require-trusted-types-for 'script'. This makes dangerous sinks such as innerHTML and script.src reject plain strings, so only values produced by a policy you define get through. It's very effective, but it's well supported in Chromium-based browsers and has been arriving in other engines more recently, so check current browser support. Expect third-party libraries to violate it. Roll it out with Content-Security-Policy-Report-Only as a separate header so you can collect Trusted Types violations without touching your enforced script policy. Browsers evaluate both policies independently.

A note on Next.js 16

Next.js 16 renamed middleware.ts to proxy.ts, and the exported function from middleware to proxy, to better describe what the file does. The CSP pattern in this article carries over: generate a nonce per request, forward it in request headers, set the response header, and render dynamically. When upgrading, use the official codemod and re-run the CSP tests above. They will tell you quickly if the nonce stopped reaching the renderer.

Rollout checklist

  1. Add the middleware with the nonce policy and reporting directives, in report-only mode via CSP_ENFORCE=false.
  2. Make sure every page under the matcher renders dynamically: headers() in the layout, or connection() where needed.
  3. Pass nonce to every next/script and every inline <script> or <style> you write.
  4. Decide your style strategy: fully strict, split style-src-elem/style-src-attr, or 'unsafe-inline', and don't mix a nonce with 'unsafe-inline' in one directive.
  5. Deploy, collect reports, filter extension noise, and fix real violations by adding nonces or specific hosts to connect-src, img-src and frame-src.
  6. Add the Playwright tests, including the nonce-uniqueness check, to CI.
  7. Verify your CDN is not caching HTML for nonce-protected routes.
  8. Flip to enforcement, keep reporting on, and review new report categories after each release.

A strict CSP won't stop you writing an injection bug, but it changes the outcome of one: instead of an attacker running script in your users' sessions, you get a blocked request and a report telling you where to look.

Keep reading

Related Articles