Content Security Policy (CSP) is an HTTP response header that lets a site declare which sources of scripts, styles, images, fonts, frames, and connections the browser should trust. Directives like script-src, style-src, img-src, and frame-ancestors give fine-grained control, and the browser blocks anything not on the allow-list.
Why it matters
CSP is one of the strongest defences against XSS: even when an attacker manages to inject a <script> tag, a strict policy prevents it from running. It also limits damage from compromised third-party scripts, blocks unwanted iframes (mitigating clickjacking), and gives you a violation-reporting endpoint so you can spot attacks and misconfigurations early.
How to use
- Start with
Content-Security-Policy-Report-Onlyand areport-toendpoint to gather data without breaking the site. - Avoid
'unsafe-inline'and'unsafe-eval'; use nonces or hashes for any inline scripts you cannot remove. - Lock
frame-ancestorsto your own origin (or'none') instead of relying onX-Frame-Options. - Set
upgrade-insecure-requestsso any leftover HTTP subresources auto-upgrade to HTTPS. - Pair CSP with Referrer-Policy and Permissions-Policy for layered defence.
- Audit third-party domains regularly; see the MDN CSP reference for every directive.