Skip to content
Something.io

How to setup Cloudflare Web Analytics with Google Tag Manager

Google Tag Manager, Cloudflare, TIL1 min read

I decided to give Cloudflare Web Analytics a spin. Others have done a much better job of reviewing Cloudflare Web Analytics, so I want to refrain from doing a review. Despite the mixed reviews, I was still curious.

I want to share a quick tip on how I used Google Tag Manager to insert the Cloudflare JavaScript snippet. I'll go ahead and make the assumption you have basic experience with Tag Manager and the fundamental concepts. My first attempt was to simply insert the JavaScript snippet as a Custom HTML tag:

Naive - and wrong - Tag Manager Custom HTML implementation of Cloudflare Web Analytics

I checked that the tag was fired in Tag Managers preview mode and a in the browser's developer tools I could see a request to static.cloudflareinsights.com. I thought all was good and waited a day to see the analytics data. But no Cloudflare Web Analytics reported 0 visitors. I dug a bit deeper with the browser's developer tools, and learned that the data-cf-beacon attribute of the script-tag wasn't in the DOM.

After a few DuckDuckGo searches I found the answer in a thread on the Tag Manager help forum. The work around is to use JavaScript to create the script-tag and attributes:

Dynamical javascript to insert Cloudflare Web Analytics with Google Tag Manager

You can copy and paste the code snippet here:

1<!-- Cloudflare Web Analytics -->
2
3<script async>
4 (function() {
5 var el = document.createElement('script');
6 el.setAttribute('data-cf-beacon', '{"token": ""}'); //<<<---Insert token here
7 el.src='https://static.cloudflareinsights.com/beacon.min.js'
8 el.setAttribute('async', '')
9 document.body.appendChild(el);
10 })();
11
12</script>
13
14<!-- End Cloudflare Web Analytics -->

P.S. There is an entire discussion about the irony in using a Google product to load a privacy-first analytics scripts. Perhaps a theme for a future blog post?

Reach out on Twitter or LinkedIn if you have questions or comments.