CSP headers restrict which sources can load script, style, and other resources. Start in report-only mode to find violations, then enforce. Tune directives to allow legitimate CDNs and inline scripts. Use nonce or hash for inline scripts.
What CSP does
- Directives:
default-src,script-src,style-src,img-src, etc. Each limits where the browser can load that type of resource. Restricts XSS and unauthorized script/style injection. - Sources: Allow specific origins (e.g.
https://cdn.example.com),'self','none', or'unsafe-inline'/'unsafe-eval'(weaken security; avoid when possible). - Reporting:
report-uriorreport-tosend violation reports to your endpoint. Use in report-only mode to see what would be blocked before enforcing.
Report-only then enforce
- Report-only: Send
Content-Security-Policy-Report-Onlyfirst. No blocking; you get reports of violations. Fix legitimate third-party or inline usage (e.g. allowlist CDNs, add nonces). - Enforce: Once violations are acceptable (fixed or allowed), switch to
Content-Security-Policy. Browser will block violations. Keep report-uri to catch regressions. - Inline scripts: Prefer nonce or hash instead of
'unsafe-inline'. Nonce: server generates a random value per request; script tag hasnonce="…". Hash: allow a specific inline script by its hash. Reduces XSS surface.
Tuning
- CDNs: Add your CDN domains to
script-src,style-src,img-srcas needed. Use subdomains or specific paths if the CDN supports it. - Frameworks: Some frameworks inject inline script or style. Use nonce support (e.g. in meta tags or server-rendered scripts) or hashes. Document allowed sources for your team.
- Strictness: Tighter CSP (fewer wildcards, no unsafe-inline) is safer but can break legacy or third-party widgets. Balance security and compatibility; improve over time.
Summary
CSP headers restrict which sources can load script, style, and other resources. Start in report-only mode; tune directives for CDNs and inline scripts (nonce/hash); then enforce. Reduces XSS and injection risk.




