Security11 min read

How Do You Implement Content Security Policy in a Next.js App Router Application?

Implement Content Security Policy in Next.js App Router: nonce generation in middleware, strict CSP directives, report-only testing, and violation reporting.

Content Security Policy (CSP) is the browser's built-in mechanism for blocking cross-site scripting attacks before they execute. It works by declaring an allowlist of trusted script sources — no other scripts run, even if an attacker injects them into your page. For a Next.js SaaS application, CSP is one of the highest-leverage security controls you can ship: a correct policy stops injected script execution entirely, turning a full XSS compromise into a blocked request and a console error.

The challenge is that Next.js App Router generates and injects inline scripts to hydrate server components and pass data to the client — the same inline scripts a strict Content Security Policy blocks by default. Getting CSP right in a Next.js application is not as simple as adding a header; it requires a nonce-based approach that most vibe-coded Next.js applications miss entirely, along with every application bootstrapped from a starter template without a security baseline.

This guide covers the complete CSP implementation for Next.js 15/16 App Router: generating a per-request nonce in middleware, writing a strict policy directive by directive, testing in report-only mode before you enforce, and collecting violation reports. It is a practical companion to the complete HTTP security headers guide for Next.js SaaS — CSP is the most complex header to configure correctly, so it deserves a standalone treatment.

Why Content Security Policy Is the Last Line of XSS Defense

Cross-site scripting attacks inject malicious JavaScript into your page and execute it in the victim's browser — stealing session cookies, logging keystrokes, redirecting to phishing pages, or silently exfiltrating data. Input validation and output encoding are your first defenses, but they fail when a third-party script you loaded is compromised, when a dependency vulnerability introduces a DOM XSS sink, or when a template renders user content without escaping. CSP is the last line: even when attacker-controlled script reaches the page, the browser refuses to execute it.

  • →Inline script injection: an attacker who finds an XSS vector injects a script tag into your page. Without CSP, the browser executes it. With a nonce-based CSP, the injected script has no nonce and is blocked.
  • →Reflected XSS from server responses: when a server reflects unsanitized user input in an HTML response, the attacker crafts a URL that injects JavaScript. CSP blocks execution regardless of how the script reaches the page.
  • →DOM XSS through dangerous sinks: APIs like innerHTML, document.write, and eval create DOM XSS sinks. CSP's Trusted Types extension restricts what can be passed to these sinks, eliminating a whole category of DOM XSS.
  • →Compromised third-party scripts: a CDN or analytics vendor whose JavaScript you load can be compromised. A script-src allowlist limits which origins can serve scripts, and nonce enforcement means only your intentional script loads execute.
  • →Data exfiltration after injection: even after a script injection, the connect-src and img-src directives can block the attacker's script from sending data to an external server. An injected script that cannot make outbound requests loses most of its value.

Why a Strict CSP Breaks a Next.js App Router Application Without a Nonce

If you add a strict Content Security Policy to a Next.js App Router application without a nonce, the app breaks immediately. The browser console shows CSP violations blocking Next.js's own inline scripts, hydration fails, and the page renders without interactivity. This happens because App Router relies on a set of inline scripts it injects during server rendering.

  • →The __NEXT_DATA__ script: Next.js injects a JSON payload in an inline script tag that the client runtime reads during hydration. It includes the route, props, and build ID. A script-src 'self' policy blocks this script because it has no src attribute and 'self' applies only to external script files.
  • →React server component payloads: App Router streams server component output as inline script tags that deliver RSC payloads to the client. These inline scripts are blocked by any policy that does not allow inline scripts or a matching nonce.
  • →Third-party scripts via next/script: the Script component with strategy='afterInteractive' or strategy='lazyOnload' injects script tags into the document. These need explicit allowlisting or the nonce prop.
  • →Using 'unsafe-inline' defeats the purpose: 'unsafe-inline' in your script-src directive allows all inline scripts including attacker-injected ones. It satisfies Next.js's requirements but provides almost no XSS protection. Modern browsers treat a policy with 'unsafe-inline' alongside a nonce as if 'unsafe-inline' were absent — the nonce takes precedence.
  • →The solution is a per-request nonce: a cryptographically random value generated for each HTTP request. Next.js reads the nonce and sets it on its injected script tags. The CSP allows only scripts carrying that nonce. An attacker who injects a script cannot know the nonce value — it changes on every request.

How to Generate a Per-Request Nonce in Next.js Middleware

Nonce generation belongs in Next.js middleware because middleware runs on every request before the page renders. This lets you generate a unique nonce, set the CSP header, and pass the nonce value to the layout via a request header where Next.js reads it. The middleware file lives at the root of your project, alongside the app directory.

  • →Generate the nonce with crypto.randomUUID(): call crypto.randomUUID() to get a UUID, then encode it as a base64 string. In the Next.js Edge Runtime where middleware runs, Buffer is not available. Use btoa() with a Uint8Array or use the UUID string directly as your nonce value — the security property is the randomness, not the encoding.
  • →Build the CSP string with the nonce interpolated: construct your full Content-Security-Policy header value as a template string. The script-src directive should include 'nonce-' followed by your nonce value: script-src 'self' 'nonce-abc123' 'strict-dynamic'.
  • →Set the Content-Security-Policy response header: on the NextResponse object returned by your middleware, call response.headers.set('Content-Security-Policy', cspValue). This delivers the policy to the browser with every HTML response.
  • →Pass the nonce to the layout via a request header: Next.js layout server components can read request headers using the headers() API, but they cannot read response headers. Pass the nonce forward by calling requestHeaders.set('x-nonce', nonce) before constructing your NextResponse. The layout then calls headers().get('x-nonce') to retrieve it.
  • →Configure the middleware matcher: add an export const config with a matcher array that excludes _next/static, _next/image, favicon.ico, and other static asset paths. CSP headers on static files add no security value and generate unnecessary overhead.

Reading the Nonce in Your Root Layout and Applying It to Scripts

Once middleware sets the nonce as the x-nonce request header, your root layout reads it and passes it to Next.js's Script component and any inline scripts you author. This is the bridge between the nonce your middleware generated and the nonce Next.js applies to its injected script tags during server rendering.

  • →Import and await headers() from next/headers: in your app/layout.tsx, add import { headers } from 'next/headers'. In Next.js 15 and later, headers() is an async function. Make your root layout's default export async and call const nonce = (await headers()).get('x-nonce') to retrieve the nonce string.
  • →Pass the nonce to every Script component: when using next/script, pass the nonce prop explicitly: <Script nonce={nonce} src='...' strategy='afterInteractive' />. Next.js reads the nonce prop and sets the nonce attribute on the resulting script tag, which the browser matches against the CSP header.
  • →Handle inline style tags with a nonce: if your layout renders inline style elements, pass the nonce attribute to the style element. JSX style props on HTML elements (style={{ color: 'red' }}) do not need a nonce — only style element tags do.
  • →Do not log or expose the nonce: the nonce must stay secret for the duration of the request. Never include it in a response body, an API endpoint, a log line, or a cookie. It is a one-time value whose security depends on the attacker not being able to predict or observe it before the response is sent.

Writing a Strict Content Security Policy: Directive by Directive

A complete CSP for a Next.js SaaS application contains about ten directives, each controlling a different category of resource. The goal is to be as restrictive as possible while allowing the legitimate resources your application needs. A policy that uses 'none' or 'self' by default and explicitly opens only what is required fails closed — an accidentally omitted resource generates a violation report, not a silent attack surface.

  • →default-src 'self': the fallback for all resource types not explicitly listed. Any resource type you do not configure a specific directive for falls back to 'self', meaning only the same origin.
  • →script-src 'self' 'nonce-{nonce}' 'strict-dynamic': 'self' allows scripts from your origin, the nonce allows Next.js's inline scripts and your authored scripts, and 'strict-dynamic' allows nonce-trusted scripts to dynamically load further scripts — which Next.js requires for its chunked script loading. Without 'strict-dynamic', script chunks Next.js inserts dynamically after hydration are blocked.
  • →style-src 'self' 'nonce-{nonce}': allows stylesheets from your origin and nonce'd inline style elements. If you use a CSS-in-JS library that injects style tags, configure it to accept and apply the nonce.
  • →img-src 'self' blob: data: https:: images from your origin, blob URLs used by canvas and object URLs, data URIs for small inline images, and any HTTPS origin for user-uploaded content. Replace 'https:' with specific CDN hostnames for a tighter policy.
  • →font-src 'self': fonts from your origin. Add fonts.googleapis.com and fonts.gstatic.com if you load Google Fonts, or your CDN hostname if fonts are hosted elsewhere.
  • →connect-src 'self': restricts fetch, XHR, WebSocket, and EventSource connections to your origin. Add your API domain and monitoring endpoints explicitly. This limits where an injected script can send exfiltrated data — a script that cannot make external requests cannot steal session tokens.
  • →object-src 'none': blocks all browser plugins — Flash, Java applets, and their successors. There is no modern use case for allowing these.
  • →base-uri 'self': prevents an attacker from injecting a base HTML tag that redirects all relative URLs to an attacker-controlled origin. 'self' limits base tags to your own origin.
  • →form-action 'self': restricts where forms may submit data. This prevents an attacker who finds an XSS vector from injecting a form that posts session tokens to an external endpoint.
  • →frame-ancestors 'none': prevents your application from being embedded in an iframe on another origin, blocking clickjacking attacks. Use 'self' only if your application intentionally renders itself inside an iframe it controls.
  • →upgrade-insecure-requests: instructs the browser to upgrade HTTP resource loads to HTTPS automatically, preventing mixed content and passive content loading over insecure connections.

Testing Your Content Security Policy in Report-Only Mode

Switching a production application directly to a strict enforced CSP without testing guarantees broken functionality — third-party scripts, analytics, inline styles from dependencies, and dynamically loaded chunks all generate violations before you have a chance to fix them. The correct approach is report-only mode first: the browser evaluates your policy and reports violations without blocking anything, giving you a clear picture of what needs fixing before you enforce.

  • →Use Content-Security-Policy-Report-Only: change the header name from Content-Security-Policy to Content-Security-Policy-Report-Only. Keep the same policy value. Users see no impact on functionality; the browser evaluates the policy and sends violation reports.
  • →Add a report-uri directive: append report-uri /api/csp-report to your policy string and create a Next.js route handler at app/api/csp-report/route.ts that accepts POST requests with the application/csp-report content type. Log the JSON violation body — it contains the blocked URI, the violated directive, the document URL, and the source file and line number.
  • →Watch the DevTools console during development: the browser logs CSP violations as console errors. Test every page of your application and note each violation. Each one represents a legitimate resource your policy would block in enforcement mode.
  • →Use Google's CSP Evaluator: paste your policy string into csp-evaluator.withgoogle.com to identify common weaknesses — 'unsafe-inline' without a nonce, dangerous host wildcards, missing object-src — and get a grade for your policy's strength.
  • →Common sources of violations: Google Analytics and Tag Manager inject inline scripts — pass the nonce prop on the Script component that loads them. Third-party chat widgets often inject inline scripts and need their CDN origin added to script-src. Stripe.js loads from js.stripe.com and needs that origin in script-src.
  • →Switch to enforcement after violations stop: after one to two weeks in report-only mode with no new violations, change the header back to Content-Security-Policy. Keep the report-uri directive to catch regressions when you add new third-party integrations.

CSP Mistakes That Vibe-Coded and AI-Generated Next.js Applications Make

Vibe-coding tools — Lovable, Bolt, Cursor, v0, Windsurf — generate functional Next.js applications but produce no Content Security Policy configuration. The resulting middleware.ts, next.config.js, and layout.tsx files contain no CSP. Founders who ship these applications are deploying without browser-level XSS protection that every security audit checks for in the first thirty seconds. Running DeployReady against any Next.js app surfaces the missing CSP header immediately — it is one of the checks in the HTTP security headers category. What DeployReady cannot catch is a CSP that is present but broken: a policy using 'unsafe-inline' that provides no actual protection.

  • →No CSP at all: the most common finding in vibe-coded applications. No Content-Security-Policy header means any XSS vulnerability — in the app, a dependency, or a compromised third-party script — is fully exploitable by any attacker who can inject a script tag.
  • →Using 'unsafe-inline' in script-src: a developer adds a CSP but includes 'unsafe-inline' to allow Next.js's inline scripts. This satisfies the syntax but provides almost no XSS protection. Use a per-request nonce instead.
  • →A static nonce generated at build time: some implementations generate the nonce once during the build and hardcode it. A static nonce provides no security — anyone who reads any page response knows the nonce and can use it in an injected inline script on subsequent requests.
  • →Missing the nonce prop on Script components: middleware sets the nonce in the CSP header but the layout does not pass it to next/script elements. Those components generate violations, the developer adds 'unsafe-inline' to suppress them, and the CSP protection is gone.
  • →CSP configured only as a static header in next.config.js: static header configuration does not support per-request nonce values. For apps with no inline scripts this works, but most Next.js applications need a nonce for hydration, which requires the middleware approach.

Frequently Asked Questions

Why does my Next.js application break when I add a Content Security Policy?

Next.js App Router injects inline scripts for hydration and server component payloads. A script-src policy that does not include 'unsafe-inline' or a matching nonce blocks these scripts, causing hydration failures and a non-interactive page. The fix is nonce-based CSP: generate a unique nonce per request in middleware, include 'nonce-{value}' in your script-src, and read the nonce in your root layout to pass it to next/script components. Never reach for 'unsafe-inline' as a workaround — it disables CSP's core XSS protection.

What is a CSP nonce and why must it change on every request?

A nonce (number used once) is a cryptographically random string added to your CSP's script-src as 'nonce-{value}'. Next.js sets this value as the nonce attribute on every inline script it injects. The browser executes only inline scripts whose nonce attribute matches the value in the CSP header. The nonce must change per request because it is visible in every HTML response — a static nonce is equivalent to no nonce, since any attacker can read it from one page response and use it in an injected script on a subsequent request.

Should I use 'unsafe-inline' in my Next.js script-src directive?

No. 'unsafe-inline' allows all inline scripts regardless of origin, defeating CSP's XSS protection. When a browser sees both 'unsafe-inline' and a nonce in the same script-src directive, modern browsers ignore 'unsafe-inline' and enforce only the nonce. The correct policy uses the nonce and 'strict-dynamic' without 'unsafe-inline'. If you need to support older browsers that do not understand nonces, you can include both — older browsers fall back to 'unsafe-inline', while modern browsers enforce the nonce and ignore the fallback.

How do I test a Content Security Policy without breaking my production site?

Use Content-Security-Policy-Report-Only with your full policy value. The browser evaluates the policy and sends violation reports to your report-uri endpoint but does not block any resources. Deploy this header first, monitor violation reports for one to two weeks across all pages and user flows, fix the violations — typically missing nonce props on Script components or missing CDN origins in script-src — then switch to the enforcing Content-Security-Policy header once violations stop.

Does a Content Security Policy prevent all XSS attacks?

No. CSP is a critical defense-in-depth layer, not a substitute for input validation and output encoding. A well-implemented CSP blocks injected script execution in the browser, but DOM-based XSS through APIs like eval, innerHTML, and document.write can bypass a policy that does not also enable Trusted Types. CSP does not prevent the XSS vulnerability itself — it prevents exploitation. You still need parameterized queries, context-aware output encoding, and careful handling of user-controlled data wherever it reaches the DOM.

How Belsoft Helps Secure Next.js Applications

CSP is one of the most reliably missed security controls in Next.js applications built with AI coding tools. DeployReady checks for a Content-Security-Policy header and flags its absence or the presence of 'unsafe-inline' in its security score. Run npx deployready against any Next.js app to get your current header posture in under a minute — that is the automated baseline.

A Belsoft security audit goes deeper: our engineers review your middleware implementation for a static nonce, check that every Script component receives the nonce prop, verify that connect-src and img-src actually restrict data exfiltration paths, test your CSP violation reporting pipeline, and walk you through switching from report-only to enforcement. For SaaS teams preparing for enterprise customers or a first security questionnaire, CSP enforcement is one of the controls enterprise security reviewers check by opening browser DevTools on your login page.

“A CSP with 'unsafe-inline' gives you the false comfort of a security header with none of the protection.”

Written by

Marco Silva

Security Engineer, Belsoft Solutions

Ready to partner?

Let's talk about your company.

30 minutes. No pitch. We talk through how you run today and where AI and automation would help.

Book a free audit
logo

Your AI & automation transformation partner: we audit, build, and train your team, then stay embedded as you grow.

Member ofNVIDIA Inception Program

Copyright Ⓒ 2026 BelSoft. All Rights Reserved.

BELSOFT, LDA · NIPC 517893258 · Lisbon, Portugal