Content Security Policy in Practice
Write a Content Security Policy, test it in report-only mode and tighten it with nonces or hashes without breaking your site.
Key takeaways
- CSP is delivered as an HTTP response header made of directives, each controlling one kind of resource.
- Report-only mode shows what a policy would block without breaking anything.
- Script rules based on nonces or hashes are much stronger than long lists of allowed domains.
- Adding
'unsafe-inline'to scripts removes most of the protection against injected code. - CSP is a second line of defense, so you still need correct output encoding in your application.
A Content Security Policy (CSP) is a set of rules your server sends to the browser describing what a page is allowed to load and run. If an attacker manages to inject a script into your HTML, a well-built policy tells the browser not to execute it.
The safe way to adopt one is to start in report-only mode, learn what your pages really use, then enforce a policy that allows your own scripts by nonce or hash. This guide walks through that process and the problems you're likely to meet.
What a policy looks like
A policy is a single header value. Directives are separated by semicolons, and each lists the permitted sources.
Content-Security-Policy: default-src 'self'; img-src 'self' https://images.example.com; object-src 'none'; base-uri 'none'; frame-ancestors 'none' default-src is the fallback for resource types you don't mention. The keyword 'self' means the same origin as the page: the same scheme, host and port. 'none' allows nothing. Keywords need single quotes, while host names are written without them.
| Directive | Controls |
|---|---|
script-src | JavaScript |
style-src | Stylesheets and inline styles |
img-src | Images |
connect-src | Fetch, XHR, WebSocket and similar connections |
font-src | Web fonts |
frame-src | What your page may embed in frames |
frame-ancestors | Who may embed your page |
form-action | Where forms may submit |
base-uri | What a <base> element may set |
object-src | Legacy plugin content |
Some directives, including frame-ancestors, base-uri and form-action, don't fall back to default-src. If you want them restricted, name them.
Start in report-only mode
Guessing at a policy and enforcing it usually breaks a payment widget, a font or your own menu. Send this header first:
Content-Security-Policy-Report-Only: default-src 'self'; report-uri /csp-report The browser applies nothing, but it logs each would-be violation to the developer console and, if you gave a reporting address, sends a JSON report there. The newer mechanism uses a report-to directive together with a Reporting-Endpoints header. Browser support for the two has differed, so many sites include both for now; check current compatibility tables.
Browse your whole site, including sign-in, checkout, search and administration pages. Then read the reports.
Expect noise. Browser extensions inject their own scripts and styles into pages, and those show up as violations that aren't your fault. Look for patterns tied to specific pages and resources you recognize. Your report endpoint is public, so limit request size and rate, and avoid storing more than you need, since reported URLs can contain personal data.
Inventory what your pages load
Sort the violations into three groups.
Things you control and want. Your own scripts, styles and images. These get 'self', a nonce or a hash.
Third parties you chose. Analytics, video embeds, payment forms, maps. Their documentation often lists the CSP sources they need. Each one you allow can run or load content in your page, so this is a good moment to remove tags nobody uses.
Things you don't recognize. Investigate before allowing. It may be an extension, a forgotten tag manager entry or a sign of a compromise.
Inline code is usually the biggest task. A script written directly in the HTML, or a handler such as onclick="save()", is blocked by a policy that restricts scripts. Move handlers into script files and attach them with addEventListener.
Allow scripts by nonce or hash
Older policies listed trusted domains. That approach is fragile: a large shared domain may host something an attacker can repurpose, and the list keeps growing.
A nonce is a random value generated fresh for every response. You put it in the header and on each script tag you intend to run:
Content-Security-Policy: script-src 'nonce-R4nd0mPerResponse' 'strict-dynamic'; object-src 'none'; base-uri 'none' <script nonce="R4nd0mPerResponse" src="/js/app.js"></script> An injected tag lacks the correct nonce, so it doesn't run. The value must be unpredictable and different each time. A nonce baked into a cached page defeats the purpose.
'strict-dynamic' lets a trusted script load further scripts it needs, and causes supporting browsers to ignore host allow lists in that directive.
A hash suits static pages. You compute a digest of the exact inline script, for example with SHA-256, and list it as 'sha256-...'. Change a single character and the hash must change too, so let your build tool calculate it. The console message for a blocked inline script often prints the expected hash.
Read a violation message
When the browser blocks something, the console tells you three useful things: the resource or inline item that was refused, the directive that refused it, and often a suggestion such as the hash that would permit an inline block. Reports sent to your endpoint carry similar fields, including the page's address, the blocked address and the violated directive.
Work from the directive. If script-src blocked a chat widget's loader, decide whether that widget is wanted before adding anything. If img-src blocked a tracking image you didn't know about, find which script requested it. If the blocked value is reported as inline, look for a style or script written into the HTML, and if it is reported as eval, some library is building code from strings through eval or new Function.
That last case deserves care. Allowing 'unsafe-eval' is sometimes forced by an older library, but many libraries offer a build that avoids it. Check their documentation first, and record why the exception exists so someone can remove it later.
Fix one category at a time and reload with the console open. Because a blocked loader never gets to request its follow-up resources, solving one violation can reveal the next.
Handle styles and other resources
Inline styles are common in templates and component libraries. You can allow style blocks by nonce or hash. Inline style attributes are harder, and many sites accept 'unsafe-inline' for styles while keeping scripts strict. That is a reasonable compromise, though injected styles can still alter a page's appearance and, in some cases, leak information.
For images, https: and data: are often needed. Allowing data: for scripts, by contrast, would reopen the hole you're closing.
Add connect-src entries for every API your front end calls, including WebSocket addresses. If a fetch request suddenly fails after enabling CSP, this is the first place to look. Keep in mind that CSP differs from CORS: CSP limits where your page may send requests, while CORS governs which origins may read a server's responses.
Enforce and keep tightening
When reports are quiet apart from noise, rename the header to Content-Security-Policy. You can send both headers at once: enforce a policy you trust, and trial a stricter one in report-only mode.
Set the header in your web server, CDN or application. A <meta http-equiv> tag also works for a limited policy, but it can't express report-only mode or frame-ancestors. If two enforced policies reach the browser, both apply, so the page gets the stricter combination. That explains some baffling blocks when a proxy and an application each add one.
A useful rollout order looks like this:
- Add the directives that rarely break anything:
object-src 'none',base-uri 'none'andframe-ancestors. - Run the script policy in report-only mode.
- Remove inline handlers and add nonces or hashes.
- Enforce, watch reports and fix stragglers.
- Review the policy whenever you add a third-party service.
upgrade-insecure-requests is another helpful directive for older sites. It tells the browser to fetch http:// resources over HTTPS, easing mixed content cleanup.
What CSP cannot do
CSP doesn't repair a vulnerability. The injected markup is still in your page, and without scripts an attacker may still add a misleading link or form. Fix the underlying flaw using the techniques in injection and XSS for builders.
It also can't tell whether an allowed third-party script has turned malicious. For scripts loaded from a fixed file elsewhere, Subresource Integrity (an integrity attribute holding the file's hash) makes the browser refuse altered copies.
A policy with 'unsafe-inline' and 'unsafe-eval' in script-src, or a bare *, looks reassuring in a header scanner while stopping very little. Judge your policy by what an injected script could still do.
Common questions
Will CSP slow my site down?
The header adds a few bytes and the checks are cheap. Per-response nonces can affect full-page caching, so static sites usually prefer hashes.
Why do I see violations I can't reproduce?
Extensions, security software and in-app browsers modify pages on visitors' devices. Filter reports by directive and source, and focus on those that recur across many clean sessions.
Where do I check the headers my site sends?
Open the network tab in your browser's developer tools, or request the page with curl -I https://example.com/. The wider list of security headers is worth reviewing at the same time.