HOW TO ADD GOOGLE ANALYTICS TO A RAILS 6 APP WITH TURBOLINKS

Rails Development

Sometimes I am just curious and would like to know if and how many people are actually visiting my app and what do they actually find interesting the most.

Google Analytics Recommended way of adding the google tag doesn't actually work

For this reason I like to add google analytics to my personal web apps. However, google analytics tells to add their script and gtag to the head section of the website - in my layout file. I tried this and no data was send to google analytics. Figuring out why it wasn't working, I found a nice tutorial that explained that actually turbolinks was kind of blocking the data transfer.

https://evrim.io/adding-google-analytics-to-a-rails-5-turbolinks-5-app/

<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-XXXXXXXXX-X"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'UA-XXXXXXXXX-X');
</script>

How to solve this?

We need to do the following steps:

Remove the gtag from the script in the head section of your layout file, views/layouts/application.html.erb

If you like you could also add the condition that only in production mode data would be send to google analytics.

<!-- Global site tag (gtag.js) - Google Analytics -->
<% if Rails.env.production? %>
  <script async src="https://www.googletagmanager.com/gtag/js?id=UA-XXXXXXXXX-X"></script>
  <script>
    window.dataLayer = window.dataLayer || [];
    function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());
</script>
<% end %>

Note, you need to substitute the id=UA-XXXXXX code with your tracking ID from google analytics.

optional: If you have other layouts, you need to add the same script as in step 2.

Create a new file in app/javascripts/packs/google_analytics.js
And add the gtag wrapped in a turbolinks:load statement

document.addEventListener('turbolinks:load', function() {
  gtag('config', 'UA-XXXXXXXXX-X')
});

Note, you need to substitute the id=UA-XXXXXX code with your tracking ID from google analytics.

Require the new javascript file in the application.js file

require("packs/google_analytics")

This worked for me. Since I am using Brave Browser, I needed to allow sending data to google analytics - removing the blocking through the Brave Shield.

I hope this will help if you had the same problem :)