A single Cross-Site Scripting (XSS) flaw or a compromised third-party script on a checkout page can exfiltrate session tokens, capture form inputs, and redirect transactions within milliseconds. According to OWASP Top Ten guidance, Injection flaws (including XSS) remain a primary web application attack surface because browsers execute any valid script node placed into the DOM by default. Configuring Content-Security-Policy (CSP) alongside companion HTTP Security Headers places an enforceable policy boundary inside the browser itself: even if an attacker injects a <script> tag into HTML, the browser refuses to execute it when it violates the declared policy.
A common mistake during an initial CSP rollout is turning on an enforcing Content-Security-Policy header immediately in production. If a payment widget, support chat frame, or web font lacks an explicit allowance, core business flows can break silently for visitors.
The safer path starts with Content-Security-Policy-Report-Only. This header instructs browsers to evaluate the entire policy, record violations, and send structured JSON reports to your telemetry endpoint without blocking any asset:
Content-Security-Policy-Report-Only: default-src 'self'; script-src 'self' 'nonce-{RANDOM}'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; connect-src 'self' https://analytics.example.com; object-src 'none'; base-uri 'self'; frame-ancestors 'none'; report-uri /api/csp-report;
Run this observation window for 7 to 14 days so you capture low-frequency flows such as password resets, partner payment redirects, and common browser extensions. Once logs at /api/csp-report no longer surface false positives from your own application code, switch the header name to Content-Security-Policy.
Enforcing Strict CSP with Nonces on Next.js and Cloudflare Workers
Traditional domain allowlists are brittle because a single public CDN hosting legacy libraries can be abused as an XSS gadget. Instead, MDN recommends a Strict CSP model built on a per-request cryptographic nonce paired with 'strict-dynamic'. When a root script carries a valid nonce, 'strict-dynamic' permits it to load downstream dependencies without maintaining sprawling third-party allowlists, while blocking unauthenticated inline <script> tags.
In Next.js (App Router), Middleware generates a fresh random value via the Web Crypto API for every request, forwards it in x-nonce so Server Components can read it via headers(), and attaches the policy to the response:
import { NextResponse } from "next/server";
export function middleware(request: NextRequest) { const nonce = Buffer.from(crypto.randomUUID()).toString("base64"); const csp = [ "default-src 'self'", script-src 'self' 'nonce-${nonce}' 'strict-dynamic', "style-src 'self' 'unsafe-inline'", "img-src 'self' blob: data:", "object-src 'none'", "base-uri 'self'", "frame-ancestors 'none'", ].join("; ");
const requestHeaders = new Headers(request.headers); requestHeaders.set("x-nonce", nonce); requestHeaders.set("Content-Security-Policy", csp);
const response = NextResponse.next({ request: { headers: requestHeaders } }); response.headers.set("Content-Security-Policy", csp); return response; } ```
Avoid keeping 'unsafe-inline' or 'unsafe-eval' inside script-src, as either keyword undermines script-injection protection. For third-party analytics tools such as Google Tag Manager or event trackers, attach the nonce directly to the bootstrap loader instead of loosening directives with unsafe-inline. When deploying behind Cloudflare Workers, the edge layer can inject static security headers across all routes and optionally use HTMLRewriter to stamp a fresh nonce onto <script> elements before HTML reaches the browser, separating edge defense from application business logic.
CSP governs resource origins and script execution, yet it still relies on companion HTTP Security Headers to lock down transport encryption, prevent MIME sniffing, and restrict browser hardware APIs.
| Header | Recommended Value | Risk Mitigated | Operational Caveat |
|---|
Strict-Transport-Security | max-age=63072000; includeSubDomains; preload | Protocol downgrade to HTTP and MITM interception | Enable preload only after every subdomain serves valid HTTPS |
X-Content-Type-Options | nosniff | Browser MIME sniffing executing text files as scripts | Verify the server emits accurate Content-Type headers for CSS, JS, and images |
Referrer-Policy | strict-origin-when-cross-origin | Leaking sensitive URL query parameters via Referer | Preserves origin for internal analytics while stripping paths on external links |
Permissions-Policy | |
On Cloudflare Workers, you can apply this header set consistently to both static assets and dynamic HTML inside a single fetch() wrapper. Building these controls into edge configuration and automated test checks during web application development prevents ad-hoc patching after launch.
Scope, Caveats, and Engineering Limitations
The CSP directive semantics and threat categories referenced here come from official MDN Web Docs and OWASP Top Ten specifications; the Middleware structure and Report-Only rollout sequence reflect ToanKhonTech engineering practice rather than any claim of discovering vendor vulnerabilities.
Keep two practical technical boundaries in mind before rollout: - CSP is defense-in-depth, not a substitute for output encoding: If an application fails to encode untrusted input in templates or stores sensitive tokens in localStorage rather than HttpOnly and SameSite cookies, attackers can still abuse legitimate data flows or DOM clobbering without loading external scripts. - Tradeoff between dynamic nonces and Static Site Generation (SSG): Because a nonce must change on every request, HTML containing a nonce cannot be served from a shared static CDN cache unless the edge rewrites HTML per request (such as Cloudflare Workers HTMLRewriter) or the route renders dynamically (SSR). Purely static content sites with minimal inline scripts can use static sha256 script hashes instead to preserve full CDN edge caching.