Cloudflare Web Analytics is an analytics service that focuses on simplicity and privacy. You can enable it for any project you host on Cloudflare and start collecting basic and private metrics from your sites.

I recently added it to a project and noticed it was not capturing any event. So, let's get our hands dirty and understand what is happening.

CORS error when sending the beacon

This service uses a minimal JS code to send a beacon with the visitor event. When checking the developer console, I noticed the event was blocked by the Cross-Origin Resource Sharing (CORS) policy.

If you did not hear about CORS before, it is a way for a web server to indicate the user browser from which domain it can receive requests. This blocking system is a security mechanism. It prevents a malware site from sending a request to any sensitive site (like your bank) without you noticing it.

From the MDN docs:

Cross-Origin Resource Sharing (CORS) is an HTTP-header based mechanism that allows a server to indicate any origins (domain, scheme, or port) other than its own from which a browser should permit loading resources

This policy is very convenient. However, it may cause issues when it is not configured correctly.

Cloudflare Web Analytics and custom domains

Looking for a solution, I found a related message from a Cloudflare developer in their forums:

Hi, looks like we have a bug on our end. Until this is fixed, after adding your custom domain on Pages, please disable and re-enable Web Analytics so that your new custom domain

And this was my current issue. In the end, these are the steps I followed:

  1. Disable Web Analytics
  2. Deploy a new version of the site
  3. Enable Web Analytics
  4. Redeploy again a new version

After this, I started getting events on my site.

When things do not work

As a developer, you usually get frustrated when a “click to enable” button does not work. Companies try to simplify their products as much as possible, and the easier they configure a feature, the faster you expect it to work.

Most of the time is a matter of patience. Deep breath and start searching for a solution 😄