CSP is a defence against cross-site scripting. If an attacker manages to inject a <script> tag into your page, a good policy stops the browser from running it, because it does not come from a source you allowed. MDN's CSP guide (opens in a new tab) describes this as its main purpose, with clickjacking and mixed-content protection as further uses.
How a policy looks
A policy is a list of directives separated by semicolons:
Content-Security-Policy: default-src 'self'; script-src 'self' https://cdn.example.com; connect-src 'self'| Directive | Controls |
|---|---|
default-src |
The fallback for any type not listed separately |
script-src |
Where scripts may load from, and whether inline scripts run |
connect-src |
Where the page may send requests with fetch, beacons, XHR and WebSockets |
img-src, style-src, font-src |
Images, styles and fonts |
frame-ancestors |
Which sites may embed your page in a frame |
The header is the recommended way to send a policy. A <meta http-equiv="Content-Security-Policy"> tag also works on static hosts, but it does not support every feature.
Nonces, hashes and strict policies
Allowlists of domains are hard to keep safe, so MDN recommends a strict policy based on nonces or hashes. A nonce is a random value the server generates for every response and puts on each script it trusts. A hash is a fingerprint of a script's exact contents. 'strict-dynamic' lets a trusted script load further scripts. Avoid 'unsafe-inline' and 'unsafe-eval', which remove most of the protection.
What an analytics script needs
When a policy forgets the analytics provider, the browser blocks it and the console shows Refused to load the script or Refused to connect. No visits arrive.
Reveata's script needs exactly two things (Content Security Policy):
script-src: the address the script loads from.connect-src: the address events are sent to, because they go withnavigator.sendBeaconorfetch.
It loads no images, frames, fonts or styles, and uses no eval.
| How you load Reveata | script-src |
connect-src |
|---|---|---|
| Standard snippet | the Reveata address | the Reveata address |
Managed proxy on stats.example.com |
https://stats.example.com |
https://stats.example.com |
| Your own proxy on your domain | 'self' |
'self' |
The optional queue snippet, which lets you call reveata() before the script loads, is inline. Allow it by moving it to a file you serve, by giving it your nonce, or with the exact sha256 hash listed in the docs.
Rolling out a policy safely
- Send it as
Content-Security-Policy-Report-Onlyfirst. The browser reports what it would block without blocking anything. - Fix every violation that belongs to a tool you use.
- Switch to the enforcing header.
- Recheck after adding any new tool or tag manager tag.