BrainsToBytes

Quick tips: Integrating Google Analytics with Rails 6/5 + Turbolinks + Webpacker

Just including the script tags Google Analytics provides you is not enough to enable analytics when a user is navigating your app with Turbolinks.

We need to enable our app to send analytics to google every time Turbolinks loads, and I wanted to share the solution I came up with for this problem. Before we start, let me share a disclaimer:

I don't know if this is the best way to solve this problem, but it's what I tried and it worked pretty well. I hope it will also fix your problem.

Ok, let's get started.

The first step is signing up for google analytics and getting your tag. If you don't have it yet, follow these instructions.

The second step is creating a partial (I usually put it on app/views/shared/_google_analytics.html.erb with the following content:

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

Remember to replace YY-XXXXXXXXX-Z with your own tag.

Now go to your layout(s) and render the partial inside the head tag:

  <head>
    ...

    <%= render 'shared/google_analytics' %>
    <%= stylesheet_pack_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
    <%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>
  </head>
  ...

Now you can go to your application.js file and add the following lines:

$(document).on("turbolinks:load", function() {
  gtag('config', 'YY-XXXXXXXXX-Z', {'page_location': event.data.url});
})

And again, replace YY-XXXXXXXXX-Z with your own tag.

That's all, you are done now. If you want to test it I recommend using something other than Firefox, as it blocks the google analytics script by default, but you can disable that feature easily.

I hope this will help, thank you for reading!

Author image
Budapest, Hungary
Hey there, I'm Juan. A programmer currently living in Budapest. I believe in well-engineered solutions, clean code and sharing knowledge. Thanks for reading, I hope you find my articles useful!