← All writing

My CSP was quietly blocking Cloudflare Web Analytics

I was tuning this site with Lighthouse and couldn't get Best Practices past 92. Nothing on the page looked broken. The only clue was a Content Security Policy error in the browser console.

A CSP is a header your site sends that tells the browser where it's allowed to load scripts from and where it can send data. Mine was strict: scripts and data could only go to the site itself. That's what I wanted. The catch is that Cloudflare Web Analytics works by injecting a small beacon script from a Cloudflare domain, and that script sends its data to another Cloudflare domain. My CSP allowed neither, so the browser blocked the script and it never ran.

I didn't notice because I was seeing analytics. Cloudflare actually gives you two kinds. The first is traffic analytics, which Cloudflare counts on its own servers as requests come in: total requests, data transferred, status codes, cache stats, countries, and so on. That doesn't depend on anything running in the browser, so it kept working. The second is Web Analytics, which comes from that beacon running in each visitor's browser. That's where you get page load times, real-user Core Web Vitals like LCP, INP, and CLS, and visit counts that leave out bots. That's the part I was missing.

The fix was adding the two Cloudflare domains to the matching CSP rules and nothing else:

script-src ... https://static.cloudflareinsights.com
connect-src ... https://cloudflareinsights.com

After that deployed, the console was clean and Best Practices went from 92 to 100. Within a few hours the Web Analytics page started showing visits, page views, and page load times.

One gotcha if you check this yourself: Pages preview deployments don't inject the beacon, so you can only really confirm it on your production domain.

If you have a CSP and Cloudflare Web Analytics turned on, open the browser console on your live site. If you see a blocked request to cloudflareinsights.com, your Web Analytics probably isn't counting anything.