What is a Content Security Policy, and is it worth setting up?
A Content Security Policy (CSP) is an HTTP header that tells the browser which sources of scripts, styles, images and other resources your page may load. It's one of the strongest defenses against cross-site scripting (XSS).
How it helps
If an attacker manages to inject a <script> into your page, a well-configured CSP can stop the browser from running it, because the script doesn't come from an allowed source or lacks the right nonce.
Common directives
default-src: fallback for resource types not otherwise listedscript-src: where scripts may come fromstyle-src,img-src,connect-src,font-src,frame-srcframe-ancestors: who may embed your page in a frame (clickjacking protection)upgrade-insecure-requests: load HTTP resources over HTTPS
Strict CSP approach
Instead of long allow-lists of domains, a "strict" policy uses nonces (a random value per response added to each allowed script) or hashes of allowed inline scripts, often with strict-dynamic. This tends to be more robust than domain lists, which can be bypassed if an allowed domain hosts user-controlled content.
Rolling it out
- Start with
Content-Security-Policy-Report-Onlyto see what would break without blocking anything. - Collect violation reports and fix or allow legitimate resources.
- Switch to enforcing mode.
- Avoid
unsafe-inlineandunsafe-evalfor scripts if you can.
Challenges
Third-party scripts like analytics, ads and widgets complicate policies.
Do you run a CSP in production? Was the report-only phase helpful, or overwhelming?
Comments · 3
The report-only mode mentioned in the rollout steps is the friendly way in. You can see what the policy would block in the browser console without breaking anything, then tighten it as you fix each violation.
Start in report-only mode. You get console reports of what would have been blocked without breaking anything. We tightened it in stages over a few weeks.
Worth it, yes. Avoid
unsafe-inlinewhere you can, and use nonces for scripts you need inline.