Content Security Policy (CSP) is one of the most effective defense-in-depth mechanisms available in modern web browsers. When configured properly, CSP mitigates Cross-Site Scripting (XSS), restricts unauthorized data exfiltration, stops clickjacking, and enforces transport security across all subresources.
Yet, despite widespread browser support, CSP remains one of the most commonly misconfigured or avoided web headers in production. The reason is simple: an overly rigid policy can instantly break legitimate third-party analytics, embedded videos, fonts, or inline event listeners, resulting in broken pages and lost conversions.
In this guide, we demystify CSP syntax, explain how modern cryptographic nonces replace legacy domain allowlists, illustrate how to safely roll out policies using report-only mode, and provide production-ready configuration snippets for Cloudflare Pages, Nginx, and static hosting platforms.
What Is Content Security Policy?
A Content Security Policy is delivered as an HTTP response header (Content-Security-Policy) sent by your web server or edge CDN. It instructs the browser to evaluate every resource requested by the document—including JavaScript scripts, CSS stylesheets, images, fonts, frames, and network connections—against an explicit set of rules.
+-----------------------------------------------------------------------------+
| Browser Security Engine |
+-----------------------------------------------------------------------------+
| |
| Document loads with: |
| Content-Security-Policy: default-src 'self'; script-src 'self' ... |
| |
| [Resource Request] ---------> [Check CSP Directive] |
| | |
| +-------------------+-------------------+ |
| | | |
| Matches Directive? | |
| | | |
| [ YES ] [ NO ] |
| | | |
| Resource Executed Blocked by Browser |
| Violation Report Sent |
| |
+-----------------------------------------------------------------------------+
If an attacker injects a malicious <script> tag into your HTML via an unescaped comment or URL parameter, a strong CSP prevents that script from executing because it lacks an authorized cryptographic signature or origin origin match.
Core Directives Explained
CSP is structured as a series of directives separated by semicolons. Each directive governs a specific category of web assets.
| Directive | Governed Resources | Fallback Behavior |
|---|---|---|
default-src |
All resources not governed by a specific directive | Root fallback |
script-src |
JavaScript execution, inline scripts, web workers | Falls back to default-src |
style-src |
CSS stylesheets and inline <style> tags |
Falls back to default-src |
img-src |
Images, SVGs, favicons | Falls back to default-src |
font-src |
Web fonts loaded via @font-face |
Falls back to default-src |
connect-src |
Fetch requests, XMLHttpRequest, WebSockets, EventSource |
Falls back to default-src |
frame-src |
<iframe> elements and embedded frames |
Falls back to default-src |
frame-ancestors |
Which sites can embed your site in an <iframe> |
Does NOT fall back to default-src |
base-uri |
Restricts <base> tag target URLs |
Does NOT fall back to default-src |
form-action |
Restricts <form> submission endpoints |
Does NOT fall back to default-src |
Why default-src 'none' is the Gold Standard
The safest starting point for any high-security application is to deny everything by default and explicitly grant permission for required asset types:
Content-Security-Policy: default-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none';
By setting default-src 'none', any asset type you forget to specify is blocked automatically rather than left open.
From Legacy Domain Allowlists to Modern Nonces
Early iterations of CSP relied heavily on domain allowlists:
# ANTI-PATTERN: Brittle domain allowlist
Content-Security-Policy: script-src 'self' https://apis.google.com https://cdn.jsdelivr.net;
While allowlists sound reasonable, security researchers quickly proved that allowlisting entire CDNs (like cdn.jsdelivr.net or cdnjs.cloudflare.com) renders CSP ineffective. If an attacker can locate an outdated or vulnerable library on that shared CDN, they can bypass the policy entirely.
The Nonce Approach (CSP Level 3)
The modern, recommended solution is cryptographic nonces. A nonce (number used once) is a unique, cryptographically random, base64-encoded string generated by the server on every request:
<!-- HTML output from server -->
<script nonce="rAnd0m123bAsE64" src="/js/app.js"></script>
The server sends the matching nonce in the HTTP header:
Content-Security-Policy: script-src 'nonce-rAnd0m123bAsE64' 'strict-dynamic';
When the browser parses the document, only <script> tags carrying the exact nonce generated for that specific HTTP response are allowed to execute. Injected scripts from an attacker will lack the secret nonce and will be blocked instantly.
The strict-dynamic Directive
When strict-dynamic is included alongside a nonce, scripts that have been verified by the nonce are trusted to create and inject further child scripts dynamically (such as modern module loaders or analytics packages), eliminating the need to maintain extensive allowlists.
Static Site Considerations: Hashes for Build-Time Integrity
What if you host on a static CDN (like Cloudflare Pages or GitHub Pages) where there is no server runtime generating dynamic per-request nonces?
For static websites, the best approach is cryptographic hashes:
Content-Security-Policy: default-src 'self'; script-src 'self' 'sha256-abc123...'; style-src 'self' 'sha256-xyz789...';
When you write an inline script, calculate its SHA-256 hash using the command line:
echo -n 'console.log("Flovo blog initialized");' | openssl dgst -sha256 -binary | openssl base64
Output:
47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU=
Add that hash to your policy:
Content-Security-Policy: script-src 'self' 'sha256-47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU=';
If anyone tampers with even a single byte of that inline script, the SHA-256 hash will not match and the browser will reject execution.
Deploying Without Downtime: The 4-Step Rollout Strategy
Never deploy an untested, restrictive CSP directly into production. Follow this phased progression:
[ Step 1: Baseline Audit ]
|
v
[ Step 2: Content-Security-Policy-Report-Only ]
| (Collect violation logs for 7-14 days)
v
[ Step 3: Policy Tuning & Exception Whitelisting ]
|
v
[ Step 4: Enforce Active CSP Header ]
1. Baseline Audit
Run a local crawl of your website using Chrome DevTools (Console tab with Preserve log enabled) to identify all inline styles, third-party analytics scripts, Google Fonts, and external API calls.
2. Enable Report-Only Mode
Instead of sending Content-Security-Policy, send Content-Security-Policy-Report-Only. In this mode, the browser does not block any resources; it merely logs violations and dispatches JSON payloads to a reporting endpoint:
Content-Security-Policy-Report-Only: default-src 'self'; script-src 'self' https://analytics.example.com; report-uri /api/csp-report;
A sample report generated by Chrome looks like this:
{
"csp-report": {
"document-uri": "https://flovo.in/blog/",
"referrer": "",
"violated-directive": "script-src 'self'",
"effective-directive": "script-src",
"original-policy": "default-src 'self'; report-uri /api/csp-report",
"blocked-uri": "https://evil-tracking.com/tracker.js",
"status-code": 200
}
}
3. Review Violation Logs
Analyze the logs for 1 to 2 weeks. You will discover legitimate widgets that were missed during initial testing, such as Google Tag Manager dependencies or browser extension artifacts.
4. Switch to Enforcement
Once violation logs stabilize to zero legitimate warnings, update your edge configuration to send the active Content-Security-Policy header.
Production Configuration Snippets
Cloudflare Pages (_headers file)
In the root of your static output directory (e.g., public/_headers):
/*
Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; img-src 'self' data: https:; connect-src 'self'; frame-ancestors 'none'; base-uri 'self'; form-action 'self';
X-Frame-Options: DENY
X-Content-Type-Options: nosniff
Referrer-Policy: strict-origin-when-cross-origin
Nginx Configuration
server {
listen 443 ssl http2;
server_name blog.flovo.in;
add_header Content-Security-Policy "default-src 'self'; script-src 'self'; style-src 'self' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; img-src 'self' data:; connect-src 'self'; frame-ancestors 'none'; base-uri 'self';" always;
add_header X-Frame-Options "DENY" always;
add_header X-Content-Type-Options "nosniff" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
}
Common CSP Pitfalls and How to Avoid Them
1. unsafe-inline Style Restrictions
Many front-end frameworks (and themes like PaperMod) inject dynamic CSS rules for animations or dark mode toggles into <style> tags. If you completely disallow unsafe-inline in style-src without hashes, your site’s dark mode toggle may fail silently. Ensure you either hash the style block or include 'unsafe-inline' strictly for styles while keeping script-src locked down.
2. Missing connect-src for Client-Side Telemetry
If your site sends client-side error telemetry to services like Sentry, LogRocket, or PostHog via fetch() or navigator.sendBeacon(), those calls will fail unless the ingestion endpoints are explicitly permitted in connect-src.
3. frame-ancestors vs X-Frame-Options
frame-ancestors 'none' is the modern CSP replacement for X-Frame-Options: DENY. However, for maximum compatibility with legacy browsers (like older Safari versions), send both headers simultaneously.
Summary Checklist
- Set
default-src 'self'ordefault-src 'none'as your foundation. - For dynamic servers, utilize cryptographically random nonces with
'strict-dynamic'. - For static sites, calculate SHA-256 hashes for inline initialization scripts.
- Always validate policies using
Content-Security-Policy-Report-Onlyfor at least 7 days before enforcement. - Explicitly configure
frame-ancestors 'none',base-uri 'self', andform-action 'self'. - Automate header validation in your CI/CD test suite using curl or automated headless browser checks.