Content-Security-Policy builder
What is a Csp Builder?
Content-Security-Policy (CSP) is an HTTP response header that tells the browser which sources of scripts, styles, images, fonts, frames and connections a page is allowed to use. A good policy is one of the most effective defences against cross-site scripting (XSS), because injected scripts from unapproved sources simply do not run.
How to use the builder
- Start with a restrictive
default-src 'self'. - Add the external sources your site really needs to each directive, such as your CDN in
script-srcor your API inconnect-src. - Copy the header and add it to your server, CDN or framework configuration.
Example policy
Content-Security-Policy: default-src 'self'; script-src 'self' https://cdn.example.com; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; connect-src 'self' https://api.example.com; frame-ancestors 'none'; base-uri 'self'; object-src 'none'
Key directives
- default-src: fallback for most other directives.
- script-src: where JavaScript may load from. Avoid
'unsafe-inline'and'unsafe-eval'; use nonces or hashes instead. - connect-src: targets of fetch, XHR and WebSocket.
- frame-ancestors: who may embed your page, replacing X-Frame-Options.
- object-src 'none' and base-uri 'self': cheap hardening every site should have.
Rolling it out safely
- Deploy first as
Content-Security-Policy-Report-Onlywith areport-toendpoint, and watch which resources would be blocked. - Fix or allow legitimate sources, then switch to enforcing mode.
- Analytics, ads and tag managers often load scripts from many domains; list them explicitly.
Frequently Asked Questions
What does Content-Security-Policy protect against?
Mainly cross-site scripting and data injection, by limiting where scripts and other resources can be loaded from.
Why is unsafe-inline discouraged?
It allows any inline script to run, including injected ones, which defeats much of CSP's protection. Use nonces or hashes instead.
How do I test a CSP without breaking my site?
Send it as Content-Security-Policy-Report-Only first. Browsers report violations but do not block anything.
Can CSP be set with a meta tag?
Yes, most directives can, but frame-ancestors and reporting only work in the HTTP header.