Google Analytics Setup for Rails 5.2

Signup for Google Analytics and get the javascript code that contains the UA-XXXXXXX for your site. Turbolinks makes the setup bit more involved. Copy the javascript code within the head section of the layout file.

  <head>
    <title>DeveloperTask</title>
    <%= csrf_meta_tags %>
    <%= csp_meta_tag %>

    <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track': 'reload' %>

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

        gtag('config', 'UA-134291848-1');
      </script>    
    <% end %>

    <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
  </head>

Note: Google analytics must be before the javascript include tag. Create a javascript file in app/assets/javascripts/google_analytics.js for triggering the analytics whenever turbolinks is loaded.

document.addEventListener('turbolinks:load', function(event) {
  if (typeof gtag === 'function') {
    gtag('config', 'UA-134291848-1', {
      'page_location': event.data.url
    })
  }
})

You will now be able to track all pages including the pages that are loaded using Turbolinks.

Reference

Google Analytics gtag setup for Rails 5.2


Related Articles