Content Security Policy (CSP) is a browser security mechanism that lets a website declare which sources of scripts, styles, frames and other content are allowed to load, limiting the impact of injection attacks.
How CSP works
A server sends the policy in the Content-Security-PolicyHTTP response header. The browser then refuses to load or execute anything the policy does not allow. Important directives include:
- default-src and script-src – allowed sources for content and JavaScript; inline scripts are blocked unless they carry a matching nonce or hash;
- ‘strict-dynamic’ – trusts scripts loaded by already trusted scripts, which makes nonce-based policies practical;
- frame-ancestors – which sites may embed the page in a frame;
- connect-src and form-action – where the page may send data;
- report-to – where violation reports are sent.
A Content-Security-Policy-Report-Only header lets developers test a policy without blocking anything. CSP is standardised by the W3C; Level 3 is the current version.
Why CSP matters
CSP is a defence-in-depth layer against cross-site scripting: even if an attacker manages to inject a script tag, the browser will not run it. The frame-ancestors directive prevents clickjacking, and restricting connection targets makes it harder for formjacking skimmers to send stolen card data to attacker domains. A policy is only as good as its rules, though: allowing ‘unsafe-inline’ or whole CDN domains often makes it trivially bypassable.
Best practices
- Prefer strict nonce- or hash-based policies over long domain allowlists.
- Avoid ‘unsafe-inline’ and ‘unsafe-eval’.
- Roll out in report-only mode first and monitor violation reports.
- Treat CSP as an addition to output encoding and input validation, not a replacement.





