CSP — Content Security Policy
HTTP header that restricts which sources a page can load — protection against XSS attacks.
What is CSP
CSP (Content Security Policy) is an HTTP response header that tells the browser which sources your page is allowed to load: scripts, styles, images, fonts, frames, etc. It is the most powerful browser-level defense against XSS (cross-site scripting) and data exfiltration.
Without CSP, an XSS vulnerability can load malicious JavaScript from any domain on the internet. With CSP, even if the vulnerability is exploited, the browser refuses to execute the code because it does not come from an approved source.
Core Directives
default-src— fallback for all resource typesscript-src— where JavaScript is allowed fromstyle-src— where CSS is allowed fromimg-src— imagesconnect-src— XHR, fetch, WebSocketfont-src— fontsframe-src— iframesreport-uri— where to send violation reports
Example CSP Header
Content-Security-Policy: default-src 'self'; script-src 'self' https://cdn.example.com; img-src 'self' data: https:; style-src 'self' 'unsafe-inline'; font-src 'self' https://fonts.gstatic.com; report-uri /csp-report
This means:
- By default, all assets must come from the same domain
- Scripts:
cdn.example.comis also allowed - Images: from anywhere over HTTPS and data URIs
- CSS: from the same domain and inline styles (not ideal)
- Fonts: from Google Fonts
- Violation reports sent to
/csp-report
Strict CSP — the Modern Approach
Today a "strict CSP" is recommended, which uses a nonce or hash to
approve specific inline scripts instead of an allowlist of domains:
Content-Security-Policy: script-src 'nonce-r4nd0m' 'strict-dynamic'; object-src 'none'; base-uri 'none';
Every inline <script> tag must carry nonce="r4nd0m" (freshly
generated per request). Attackers cannot guess the nonce, so injected scripts are blocked.
Gradual Roll-out
- Start with
Content-Security-Policy-Report-Only— reports only, nothing is blocked. - Collect reports and see what "would have broken".
- Fix legitimate sources that are missing.
- After 1–2 weeks, switch to the full
Content-Security-Policy.