Content Security Policy (CSP) & HTTP Security Headers in 2026: Stop XSS Without Breaking Next.js or Analytics

Wazir Ahmed, CTO, DEESU and CEO, D.TENWazir AhmedCTO, DEESU and CEO, D.TEN10 min readWeb Development

Cross-Site Scripting (XSS) and client-side supply-chain skimming remain two of the highest-impact attack classes on the modern web. Even when your frontend uses React's automatic JSX escaping and parameterized backend queries, a single dangerouslySetInnerHTML sink, a poisoned analytics tag, a compromised npm transitive dependency, or a vulnerable markdown renderer can execute attacker-controlled JavaScript inside your users' authenticated browser sessions. Once malicious script runs in your origin, it can exfiltrate session tokens, hijack payment forms, or invoke privileged API mutations silently.

HTTP security response headers—anchored by a strict Content Security Policy (CSP)—act as the browser-enforced safety net when application-level sanitization fails. Yet in security audits across production SaaS apps and e-commerce storefronts, over 70% of deployed CSP headers are functionally bypassed within minutes because teams copy legacy templates containing 'unsafe-inline', 'unsafe-eval', or broad CDN wildcards (*.googleapis.com, cdn.jsdelivr.net) that host JSONP endpoints and AngularJS gadgets.

In this engineering guide, we dissect why allowlist-only CSPs fail, walk through implementing per-request nonce CSP with `'strict-dynamic'` in Next.js 15/16 Middleware and Nginx, show how to integrate Stripe, Google Analytics, and AdSense safely, and map out the complete modern HTTP header stack. Before editing production configs, you can prototype your directives and export ready-to-paste Next.js or Nginx snippets in our HTTP Security Headers & CSP Generator.

Strict Nonce-Based Content Security Policy and HTTP Security Headers Flow in Next.js and Nginx
Strict CSP Request Lifecycle: Middleware generates a unique 128-bit cryptographic nonce per HTTP request, binds it to the CSP response header and server-rendered script tags, and blocks any injected inline or unauthorized third-party script.

1. Anatomy of Modern XSS and Why `'unsafe-inline'` Defeats CSP

Historically, developers treated CSP as a domain allowlist: script-src 'self' https://www.googletagmanager.com https://js.stripe.com. In practice, domain allowlists break down on two fronts. First, modern frameworks hydrate pages with inline bootstrap scripts and third-party snippets, pushing impatient engineers to append 'unsafe-inline' just to make console errors disappear. The moment 'unsafe-inline' appears in script-src (without a nonce or hash overriding it), the browser permits every <script>alert(1)</script>, <img onerror=...>, and javascript: payload injected anywhere into the DOM—completely negating CSP's primary purpose.

Second, Google's own security research demonstrated that over 90% of real-world domain-allowlist CSPs are trivially bypassable even without 'unsafe-inline'. Any whitelisted host that serves user-uploaded files, open redirects, legacy JSONP callbacks, or old JavaScript libraries allows an attacker to load a valid <script src="https://trusted-cdn.example/jsonp?callback=stealTokens"> tag that satisfies the origin check while executing arbitrary logic.

2. Strict CSP: Per-Request Nonces and `'strict-dynamic'`

Instead of playing whack-a-mole with dozens of third-party subdomains, Google and the W3C recommend Strict CSP built around two primitives: a cryptographic nonce and the `'strict-dynamic'` keyword.

  • Cryptographic per-request nonce (`'nonce-<random>'`): For every single incoming HTML document request, your edge server or Next.js Middleware generates at least 128 bits of CSPRNG entropy encoded in Base64. That value is placed in both the Content-Security-Policy header and the nonce attribute of your trusted <script> tags. Because an attacker injecting HTML cannot predict the fresh nonce, injected scripts fail to execute.
  • `'strict-dynamic'` trust propagation: When 'strict-dynamic' is present, any script already trusted via a valid nonce is permitted to dynamically insert child <script> elements into the DOM (such as Next.js code-split chunks, Stripe Elements iframes, or Google Tag Manager sub-scripts). Simultaneously, modern browsers ignore legacy host allowlists and 'unsafe-inline', leaving them only as graceful fallbacks for ancient browsers.
  • Mandatory `object-src 'none'` and `base-uri 'none'`: Strict CSP also locks down legacy plugin execution (object-src 'none') and prevents base-tag hijacking (base-uri 'none'), where an attacker injects <base href="https://evil.example/"> to redirect all relative script URLs to their own server.

3. Implementing Nonce-Based Strict CSP in Next.js 15/16 Middleware

Next.js 15 and 16 natively read the x-nonce request header during Server Component rendering and automatically attach that nonce to framework hydration scripts, <Script> components, and route prefetch bundles. The critical operational constraint to remember is caching: nonce-based pages must be dynamically rendered per request (never cached statically with a reused nonce across different users), because reusing a static nonce lets an attacker scrape the nonce once and reuse it in an injection payload.

import { NextRequest, NextResponse } from "next/server";

export function middleware(request: NextRequest) {
  const nonce = Buffer.from(crypto.randomUUID()).toString("base64");

  const cspDirectives = [
    "default-src 'self'",
    `script-src 'self' 'nonce-${nonce}' 'strict-dynamic' https:`,
    "style-src 'self' 'unsafe-inline'",
    "img-src 'self' blob: data: https://www.google-analytics.com",
    "font-src 'self' https://fonts.gstatic.com",
    "connect-src 'self' https://api.stripe.com https://*.google-analytics.com",
    "frame-src https://js.stripe.com https://hooks.stripe.com",
    "object-src 'none'",
    "base-uri 'none'",
    "form-action 'self'",
    "frame-ancestors 'none'",
    "upgrade-insecure-requests",
  ].join("; ");

  const requestHeaders = new Headers(request.headers);
  requestHeaders.set("x-nonce", nonce);
  requestHeaders.set("Content-Security-Policy", cspDirectives);

  const response = NextResponse.next({
    request: { headers: requestHeaders },
  });
  response.headers.set("Content-Security-Policy", cspDirectives);
  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" },
      ],
    },
  ],
};
Next.js 15/16 middleware.ts generating per-request strict CSP nonces

Notice two deliberate engineering details in that snippet. First, style-src often keeps 'unsafe-inline' during initial rollout if third-party UI libraries inject inline style attributes, while script-src remains strictly locked down—because script execution carries orders of magnitude greater risk than CSS injection. Second, if your application serves static marketing pages from a CDN where per-request middleware is undesirable, use SHA-256 script hashes ('sha256-...') instead of nonces so pages remain 100% cacheable at the edge.

4. Enforcing Security Headers and Dynamic Nonces in Nginx

When running containerized web apps, SPAs, or backend APIs behind Nginx, you can inject security headers centrally at the reverse proxy layer. For static HTML served directly by Nginx that still requires per-request nonces, Nginx's built-in $request_id (a 32-character hex random identifier generated per request) paired with sub_filter replaces placeholder nonces on the fly with negligible CPU overhead:

server {
    listen 443 ssl http2;
    server_name app.example.com;

    # Replace placeholder nonce in HTML responses dynamically per request
    sub_filter_once off;
    sub_filter 'CSP_NONCE_PLACEHOLDER' $request_id;

    # Strict Content Security Policy
    add_header Content-Security-Policy "default-src 'self'; script-src 'nonce-$request_id' 'strict-dynamic' https:; object-src 'none'; base-uri 'none'; frame-ancestors 'none'; connect-src 'self' https://api.stripe.com; upgrade-insecure-requests;" always;

    # Transport & Framing Protection
    add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header Referrer-Policy "strict-origin-when-cross-origin" always;
    add_header Cross-Origin-Opener-Policy "same-origin" always;
    add_header Permissions-Policy "camera=(), microphone=(), geolocation=(), payment=(self)" always;
}
Nginx reverse proxy configuration with strict CSP, HSTS Preload, and COOP/Permissions-Policy

5. Safely Whitelisting Google Analytics, Stripe, and AdSense

The most common reason teams abandon CSP is breaking revenue-critical third-party scripts: checkout widgets, analytics beacons, and ad networks. With 'strict-dynamic' active, integrating these providers stays remarkably clean because you only attach your per-request nonce to the top-level loader script tag:

  • Google Analytics 4 & Google Tag Manager: Attach nonce={nonce} to the initial GTM or gtag.js <Script> component. With 'strict-dynamic', dynamically loaded GTM child tags inherit trust automatically. Explicitly allow https://www.google-analytics.com and https://*.analytics.google.com in connect-src and img-src so measurement beacons succeed without opening connect-src to arbitrary domains.
  • Stripe.js & Stripe Elements: Load https://js.stripe.com/v3/ with your nonce, allow https://api.stripe.com in connect-src, and restrict frame-src to https://js.stripe.com https://hooks.stripe.com for 3D Secure authentication challenges. Never whitelist broad wildcards like *.stripe.com unnecessarily.
  • Google AdSense: Ad networks dynamically load creative iframes from dozens of ad-tech partners, making strict host allowlists impossible without 'strict-dynamic'. Load adsbygoogle.js with your nonce, permit https://googleads.g.doubleclick.net and https://tpc.googlesyndication.com in frame-src, and isolate ad placements away from authenticated billing or account settings routes entirely—your checkout pages should run an even tighter policy with zero ad origins.

6. Beyond CSP: The Complete 2026 HTTP Security Header Matrix

A resilient browser security posture layers multiple orthogonal headers so that each defends a distinct attack vector—from SSL stripping and clickjacking to Spectre side-channel leaks and rogue browser extension telemetry. Similarly, when auditing how tokens survive client-side sessions alongside these headers, inspecting claims and expiration flags in our JWT Debugger & Security Inspector pairs naturally with verifying HttpOnly cookie attributes and CSP connect-src boundaries.

HTTP HeaderRecommended Production ValueAttack Vector PreventedDeployment Caveat
Content-Security-Policydefault-src 'self'; script-src 'nonce-...' 'strict-dynamic'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'XSS execution, supply-chain skimming, data exfiltration, clickjackingTest via Report-Only first; nonces require dynamic rendering.
Strict-Transport-Securitymax-age=63072000; includeSubDomains; preloadSSL stripping, protocol downgrade, Man-in-the-Middle cookie theftStart with max-age=300 before committing to HSTS Preload list.
frame-ancestors (CSP)frame-ancestors 'none' (replaces legacy X-Frame-Options)Clickjacking, UI redressing, invisible iframe overlaysSupports multiple origins cleanly; supersedes X-Frame-Options.
X-Content-Type-OptionsnosniffMIME-type confusion attacks turning uploaded text/images into scriptsEnsure static assets always return accurate Content-Type headers.
Permissions-Policycamera=(), microphone=(), geolocation=(), payment=(self)Unauthorized hardware/sensor access by embedded third-party iframesExplicitly allow features needed by embedded video calls or wallets.
Cross-Origin-Opener-Policysame-origin (or same-origin-allow-popups for OAuth)Cross-origin window handle hijacking & XS-LeaksUse same-origin-allow-popups if using popup-based Google/Stripe OAuth.
Cross-Origin-Embedder-Policyrequire-corp or credentiallessSpectre side-channel memory leaks; unlocks SharedArrayBufferOnly enable if third-party images/scripts send CORP/CORS headers.
Essential HTTP Security Response Headers and the Specific Attack Classes They Mitigate

7. Zero-Breakage Rollout Checklist Using Report-Only Mode

Flipping a strict CSP directly into enforcement on a busy production site almost guarantees broken checkout buttons or silenced analytics. Follow this staged rollout checklist to harden production safely:

  • Deploy your candidate policy using the Content-Security-Policy-Report-Only header first so browsers log violations without blocking any live user actions.
  • Configure the modern Reporting-Endpoints header alongside report-to csp-endpoint (with a legacy report-uri fallback) pointing to Sentry, Datadog, or an ingestion worker.
  • Collect violation telemetry for 7 to 14 days across desktop, mobile Safari, and embedded webviews, filtering out noisy browser-extension injections (chrome-extension://, moz-extension://).
  • Verify that every first-party <script> tag and third-party loader (Stripe, GA4, Turnstile) receives a fresh per-request nonce and that no CDN layer accidentally caches the HTML document containing that nonce.
  • Promote the header from Content-Security-Policy-Report-Only to enforcing Content-Security-Policy, while retaining a secondary Report-Only header whenever testing future tightening.
  • Test HSTS with a short 5-minute max-age across all subdomains before escalating to 2 years (63072000) and submitting your root domain to hstspreload.org.

Frequently asked questions

That behavior is intentional by design in CSP Level 3. Domain allowlists have proven brittle and easily bypassed via JSONP endpoints or open redirects on trusted CDNs. When 'strict-dynamic' is active, modern browsers ignore host expressions and 'unsafe-inline', trusting only scripts carrying a matching cryptographic nonce or SHA-256 hash—plus any child scripts those trusted scripts load programmatically. Leaving https: alongside 'strict-dynamic' acts strictly as a backward-compatibility fallback for legacy browsers.

In all modern evergreen browsers, the CSP frame-ancestors directive takes strict precedence over X-Frame-Options and provides far greater flexibility—such as authorizing multiple specific partner origins instead of a single domain or disabling framing altogether. However, sending X-Frame-Options: DENY (or SAMEORIGIN) alongside frame-ancestors 'none' remains completely harmless, costs just a few response bytes, and continues satisfying legacy enterprise compliance scanners and older embedded mobile webviews that do not parse CSP Level 2 directives.

You should never embed a static nonce inside a CDN-cached SSG HTML file, because every visitor receives the identical nonce, making it trivial for an attacker to predict and bypass the policy. For purely static sites hosted on Cloudflare Pages, Vercel Edge, or S3/CloudFront, use SHA-256 script hashes ('sha256-...') calculated at build time—or inject per-request nonces dynamically at the CDN edge via a Cloudflare Worker or Lambda@Edge transform.

Yes, setting Cross-Origin-Opener-Policy: same-origin severs the window.opener reference between your application and cross-origin popups, which breaks popup-based Sign in with Google, Apple, or third-party payment authorization flows that rely on window.postMessage. If your application depends on cross-origin popups communicating back to the opener tab, configure Cross-Origin-Opener-Policy: same-origin-allow-popups instead—preserving popup OAuth flows while still isolating your browsing context from untrusted third-party sites opening your URL.

Browser extensions such as password managers, grammar checkers, ad blockers, and translation widgets routinely inject inline scripts into web pages, generating noisy benign CSP violation reports at scale. Filter incoming JSON telemetry at your ingestion endpoint by dropping events whose source-file or blocked-uri starts with chrome-extension://, moz-extension://, safari-extension://, or about:, and deduplicate identical (document-uri, violated-directive, blocked-uri) tuples so genuine application regressions stand out immediately.

Sources

ShareLinkedInX
Wazir Ahmed, CTO, DEESU and CEO, D.TEN

Written by

Wazir Ahmed

CTO, DEESU and CEO, D.TEN

Dr. Wazir Ahmed is the CTO of DEESU and leads D.TEN, its training and education division. A training manager, educational psychologist and researcher with a Ph.D. in educational psychology, he oversees learning systems, technology architecture, and training design.

More from Wazir

Need help with this?

Reply within 1 business day

Tell us what you're building.

Send the problem, not a polished brief. We'll tell you what it actually takes to ship it: stack, timeline and cost, before you commit to anything.