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.

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-Policyheader and thenonceattribute 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" },
],
},
],
};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;
}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 orgtag.js<Script>component. With'strict-dynamic', dynamically loaded GTM child tags inherit trust automatically. Explicitly allowhttps://www.google-analytics.comandhttps://*.analytics.google.cominconnect-srcandimg-srcso measurement beacons succeed without openingconnect-srcto arbitrary domains. - Stripe.js & Stripe Elements: Load
https://js.stripe.com/v3/with your nonce, allowhttps://api.stripe.cominconnect-src, and restrictframe-srctohttps://js.stripe.com https://hooks.stripe.comfor 3D Secure authentication challenges. Never whitelist broad wildcards like*.stripe.comunnecessarily. - Google AdSense: Ad networks dynamically load creative iframes from dozens of ad-tech partners, making strict host allowlists impossible without
'strict-dynamic'. Loadadsbygoogle.jswith your nonce, permithttps://googleads.g.doubleclick.netandhttps://tpc.googlesyndication.cominframe-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 Header | Recommended Production Value | Attack Vector Prevented | Deployment Caveat |
|---|---|---|---|
| Content-Security-Policy | default-src 'self'; script-src 'nonce-...' 'strict-dynamic'; object-src 'none'; base-uri 'none'; frame-ancestors 'none' | XSS execution, supply-chain skimming, data exfiltration, clickjacking | Test via Report-Only first; nonces require dynamic rendering. |
| Strict-Transport-Security | max-age=63072000; includeSubDomains; preload | SSL stripping, protocol downgrade, Man-in-the-Middle cookie theft | Start 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 overlays | Supports multiple origins cleanly; supersedes X-Frame-Options. |
| X-Content-Type-Options | nosniff | MIME-type confusion attacks turning uploaded text/images into scripts | Ensure static assets always return accurate Content-Type headers. |
| Permissions-Policy | camera=(), microphone=(), geolocation=(), payment=(self) | Unauthorized hardware/sensor access by embedded third-party iframes | Explicitly allow features needed by embedded video calls or wallets. |
| Cross-Origin-Opener-Policy | same-origin (or same-origin-allow-popups for OAuth) | Cross-origin window handle hijacking & XS-Leaks | Use same-origin-allow-popups if using popup-based Google/Stripe OAuth. |
| Cross-Origin-Embedder-Policy | require-corp or credentialless | Spectre side-channel memory leaks; unlocks SharedArrayBuffer | Only enable if third-party images/scripts send CORP/CORS headers. |
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-Onlyheader first so browsers log violations without blocking any live user actions. - Configure the modern
Reporting-Endpointsheader alongsidereport-to csp-endpoint(with a legacyreport-urifallback) 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-Onlyto enforcingContent-Security-Policy, while retaining a secondaryReport-Onlyheader whenever testing future tightening. - Test HSTS with a short 5-minute
max-ageacross all subdomains before escalating to 2 years (63072000) and submitting your root domain to hstspreload.org.
Frequently asked questions
'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.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.'sha256-...') calculated at build time—or inject per-request nonces dynamically at the CDN edge via a Cloudflare Worker or Lambda@Edge transform.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.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

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 WazirFree tools for this topic
Need help with this?



