Security · Web · Cloudflare · Frontend

Content Security Policy (CSP) Guide: Tightening Your Site Without Breaking It

How to set up a Content Security Policy: safe first directives, nonces vs hashes, CSP on a static site, a gradual rollout with Report-Only and the breakages you will hit.

Sander Yazıcıoğlu Published: 4 min read Türkçe oku

Content Security Policy (CSP) Guide: Tightening Your Site Without Breaking It

Working on corporate and health-tourism websites, I kept seeing the same picture: an analytics tag, a chat widget, a map, a form service, plus a few scripts the marketing team added. Each one runs with the same power as your own code. A Content Security Policy (CSP) is how you tell the browser "only code from these sources may run on this page". Even if there is an XSS hole, it is a second line of defence that stops the injected script from executing.

The catch: a badly written CSP breaks the site instantly. So you build it in layers, not in one go.

A first step that breaks nothing

This is the CSP line in this site's _headers file:

Content-Security-Policy: base-uri 'self'; object-src 'none'; frame-ancestors 'none'; upgrade-insecure-requests

There is no script-src here, so scripts are not touched yet. But all four directives give real protection while breaking almost no sites:

DirectiveWhat it does
base-uri 'self'Stops an injected <base> tag from pointing every relative URL to another server
object-src 'none'Disables plugin content via <object> and <embed>
frame-ancestors 'none'Prevents the page from being framed by another site (clickjacking); the modern replacement for X-Frame-Options
upgrade-insecure-requestsAutomatically upgrades http:// requests on the page to https://

Starting with these four lines beats "we'll do CSP later" every time.

The real work: script-src

script-src provides the actual protection against XSS. There are three approaches:

1. Host allowlist: script-src 'self' https://www.googletagmanager.com. Easy to read but weak. If an allowed domain hosts user content or a JSONP endpoint, the policy can be bypassed.

2. Nonce: the server generates a random value on every response and writes it to both the header and every <script> tag.

<script nonce="r4nd0m">/* ... */</script>
Content-Security-Policy: script-src 'nonce-r4nd0m' 'strict-dynamic'; object-src 'none'; base-uri 'self'

'strict-dynamic' extends trust to scripts loaded by a nonced script, which is practical for chained loaders such as tag managers. The nonce must be different on every response; a fixed nonce protects nothing.

3. Hash: the SHA-256 digest of an inline script's content goes into the policy. It stays the same on every response as long as the content does not change.

import crypto from 'node:crypto';
const hash = crypto.createHash('sha256').update(inlineScript).digest('base64');
// policy: script-src 'self' 'sha256-<hash>'

CSP on a static site

On static hosting such as Cloudflare Pages every response is the same file; there is no server to generate a nonce. You have two options:

  • Hashes at build time: find inline scripts during the build and write their hashes into _headers. If your Vite output has few inline scripts, this is the simplest route.
  • Nonces at the edge: a Worker streams the HTML through HTMLRewriter, adds a fresh nonce to every <script> tag and writes the header with the same value. For Worker basics see the Cloudflare Pages and Workers post.

If you use Angular, it has supported ngCspNonce for inline styles since version 16, and version 19 added the experimental autoCsp option that hashes inline scripts. Using the framework's own path causes fewer surprises than rolling your own.

A gradual rollout with Report-Only

Instead of enforcing a new policy straight away, ship it in report mode first:

Content-Security-Policy-Report-Only: script-src 'self' 'sha256-...'; report-uri /csp-report

The browser blocks nothing but sends a JSON report on every violation. The blocked-uri and violated-directive fields tell you which sources are missing. After a few days of clean reports, rename the header to Content-Security-Policy. You can also send both headers at once: the current policy enforced, the stricter one on trial.

Part of the reports is noise: browser extensions inject their own scripts and produce violations from sources like chrome-extension. Filter those out before you set up alerts.

Common breakages

  • Inline event handlers: attributes like onclick="..." do not work with nonces. Move them to addEventListener.
  • WebSocket and API calls: forget connect-src and fetch and wss:// connections are cut off. In real-time apps this is usually the first thing to break.
  • Third-party iframes: maps, videos and comment widgets need frame-src.
  • Inline style attributes: style="..." written in HTML can be blocked by style-src. Changes JavaScript makes through element.style are not affected.
  • Development: Vite's dev server relies on inline code; add the policy to production responses only.
  • CSP via <meta>: frame-ancestors and the reporting directives do not work in a meta tag; use an HTTP header where you can.

Conclusion

Trying to get CSP perfect in one step ends either with a broken site or with never starting. Add the harmless directives first, trial script-src in Report-Only mode, clean up the reports and only then enforce it. Security headers are part of technical quality too; for the rest of the list see the technical SEO checklist.

All articles →