Content Security Policy: Best Practices
A strict CSP limits where code and content can load from and blocks injection.
Principles
- Prefer nonces/hashes over 'unsafe-inline'.
- Avoid wildcards; scope sources precisely (schemes, hosts, paths).
- Separate third-party content (subdomains/sandbox) and disallow eval.
- Use frame-ancestors instead of X-Frame-Options.
- Log violations (report-to / report-uri) and iterate.
Rollout without breakage
- Ship in Report-Only first; fix violations; then enforce.
- Inventory third-party resources and gate them behind nonces/hashes.
- Pin expected connections with connect-src.
TL;DR
Start with a strict CSP, ship in Report-Only
, then enforce. Prefer nonces/hashes over 'unsafe-inline'
. Allow only what you need.
5‑minute checklist
- Baseline:
default-src 'self'
(or'none'
) and add sources explicitly. - Use nonces for inline scripts/styles; avoid wildcards.
- Pin third‑party domains; review and remove unused allowances.
- Enable
upgrade-insecure-requests
and block mixed content. - Roll out via
Content-Security-Policy-Report-Only
and monitor violations.