ALL POSTS

Content Security Policy for Next.js and React

November 16, 2026 · 5 min read

headersnextjsjavascript
A browser-shaped gate filtering glowing geometric shapes.

Content Security Policy is a browser-enforced set of rules for the resources a page may load and execute. For a Next.js or React application, the challenge is choosing a policy that limits unwanted behavior without breaking hydration, styles, analytics, or legitimate integrations. A careful rollout starts with observation and a clear understanding of how your application renders.

This guide uses Next.js 16 App Router terminology. The request interception file is proxy.ts; older Next.js versions use middleware.ts. Apply the example to a staging application you control and adapt it to your actual resources. CSP complements output encoding and safe application code; it does not repair an authorization bug.

Inventory before writing a CSP header example

Walk through the site with browser developer tools open. Record script origins, image hosts, API and WebSocket connections, fonts, embedded frames, and any inline code your application or dependencies generate. Include login, payment redirects, error pages, and lazy-loaded components.

Assign an owner to each external dependency. “The marketing team might need it” is not a good reason to allow every HTTPS origin in script-src. A short inventory helps you remove an obsolete integration instead of creating a permanent exception for it.

Start with CSP report only

A report-only policy lets you observe violations without blocking the resources that trigger them:

Content-Security-Policy-Report-Only: default-src 'self'; object-src 'none'; base-uri 'self'; frame-ancestors 'none'

Expect reports from inline framework scripts until you configure nonces or a compatible alternative. Review the browser console first. If you operate a reporting endpoint, add a Reporting-Endpoints header and a corresponding report-to directive; retain compatible legacy reporting where your supported browsers require it.

Treat reports as untrusted input. Limit request size and rate, avoid storing sensitive URL query strings, and do not fetch URLs supplied in reports. A report collector should never become a general-purpose network proxy. The CSP specification defines report-only behavior and policy directives.

Choose between static delivery and per-request nonces

A CSP nonce is a fresh unpredictable value shared by an authorized script tag and the page’s policy. It is not a secret that remains private from the page; it prevents unrelated injected markup from knowing an accepted value in advance.

Next.js can use a nonce from the request’s CSP during rendering. That requires dynamic rendering and careful cache handling. Static HTML or an ISR response cannot simply be combined with a newly generated header nonce. Decide whether the affected routes should become dynamic, or whether a different CSP strategy better fits your static site. The Next.js CSP guide describes these constraints.

Do not cache nonce-bearing HTML for shared reuse. A policy that works on a local uncached request can fail when the CDN serves HTML generated with a different nonce. Verify the HTML and header as a pair.

A scoped Next.js 16 nonce example

This starter applies to an application section rather than every public asset. It forwards the policy to rendering and returns it in report-only mode for rollout:

// src/proxy.ts — adapt the matcher to your application routes.
import { NextRequest, NextResponse } from 'next/server';

export function proxy(request: NextRequest) {
  const bytes = crypto.getRandomValues(new Uint8Array(16));
  const nonce = btoa(String.fromCharCode(...bytes));
  const policy = [
    "default-src 'self'",
    `script-src 'self' 'nonce-${nonce}' 'strict-dynamic'`,
    `style-src 'self' 'nonce-${nonce}'`,
    "img-src 'self' data:",
    "font-src 'self'",
    "connect-src 'self'",
    "object-src 'none'",
    "base-uri 'self'",
    "frame-ancestors 'none'",
    "form-action 'self'",
  ].join('; ');

  const forwarded = new Headers(request.headers);
  forwarded.set('x-nonce', nonce);
  forwarded.set('Content-Security-Policy', policy);

  const response = NextResponse.next({ request: { headers: forwarded } });
  response.headers.set('Content-Security-Policy-Report-Only', policy);
  response.headers.set('Cache-Control', 'private, no-store');
  return response;
}

export const config = { matcher: ['/app/:path*'] };

This example intentionally does not allow your analytics, API subdomain, or payment frames yet. Add only the sources your inventory requires. Also ensure that redirects and error responses for protected pages receive the intended policy; a scoped matcher is a design decision, not automatic coverage.

For a route that otherwise might be prerendered, opt into request-time rendering in the appropriate server component:

// Example within the protected application section.
import { connection } from 'next/server';

export default async function Page() {
  await connection();
  return <main>Your application</main>;
}

Do not copy this into every static marketing page without considering the performance and hosting implications. Validate the current framework behavior against your installed version.

Handle scripts, styles, and analytics deliberately

Custom scripts need the same request nonce when they are intended to execute. Third-party script loaders deserve close review: strict-dynamic extends trust from an authorized script to scripts it loads, so approving a loader is a meaningful trust decision.

A style nonce authorizes matching style elements, not arbitrary inline style attributes. CSS-in-JS libraries and components that generate inline styles may require framework-specific nonce configuration or a different style policy. Do not respond to every violation by adding unsafe-inline globally. Determine whether the blocked behavior is needed and whether you can change the component.

Development tooling may require allowances that production does not. Keep development exceptions clearly separated, and perform the final verification with a production build. An application that runs under the development server is not evidence that your production CSP is correct.

Read violations as debugging evidence

For each violation, capture the directive, resource type, initiating page, and a redacted URL. Reproduce it in a clean browser profile to distinguish application behavior from extension injection. Test both first navigation and client-side navigation, because they can load different resources.

Group repeated violations instead of treating every report as a new incident. A single missing image host can create thousands of messages. Keep an explicit exception list with an owner and reason, and remove entries for integrations that no longer exist.

Move from reporting to enforcement

When supported user journeys pass and unexplained violations are resolved, change the response header to Content-Security-Policy for the tested scope. Avoid accidentally retaining a contradictory second policy at your reverse proxy. Multiple policies combine restrictively; a permissive new header does not simply cancel an older restrictive one.

Roll out incrementally, monitor errors and conversion paths, and retain a known-good rollback. Test the policy again after framework upgrades, tag-manager changes, or new payment integrations. Keep the rest of your security headers aligned with the application’s framing and privacy requirements.

Check your own site — your first scan is free. Scanwise combines passive intelligence with non-destructive external checks and AI-assisted remediation suggestions. It can observe exposed policies, but cannot guarantee every authenticated browser journey works. Test the changes in your own environment; starter credits require a verified account and are subject to anti-abuse limits.

Check your own site

Run the same external recon on your own domain. First scan is free.

RUN AI SCAN — FIRST SCAN FREE