Overview
The Content-Security-Policy header makes the browser block scripts and resources from sources the page did not allow. It is defense in depth against XSS, not a replacement for output escaping. Ship one on any site that renders user content or third-party scripts, starting with Content-Security-Policy-Report-Only to find breakage before enforcing.
Rules
- Prefer a strict policy: a random nonce per response (or hashes for static pages) on
script-src, plusobject-src 'none'andbase-uri 'none'.'strict-dynamic'lets nonce-trusted scripts load others. Avoid host allowlists,'unsafe-inline', and'unsafe-eval'. - A nonce must be unpredictable and new for every response; a fixed value protects nothing, and nonce pages cannot be statically cached.
- Send it as a header.
<meta>supports only some directives (frame-ancestorsis ignored). frame-ancestorscontrols who may embed your page (replacingX-Frame-Options);frame-srccontrols what your page may embed.- Report with
report-toplus aReporting-Endpointsheader.report-tobecame Baseline in March 2026; keep legacyreport-urialongside it for older browsers (browsers that supportreport-toignorereport-uri).
Content-Security-Policy: script-src 'nonce-{RANDOM}' 'strict-dynamic'; object-src 'none'; base-uri 'none'; report-to csp-endpoint
Related
- cors: controls cross-origin reads, not loading.
- nextjs: nonce wiring in Next.js.
- astro: CSP in Astro.
- cloudflare-security-headers: setting headers at the edge.
- owasp-top-10: XSS context.