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.

    <%= 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=""></script>
        window.dataLayer = window.dataLayer || [];
        function gtag(){dataLayer.push(arguments);}
        gtag('js', new Date());

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

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

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', {

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


Google Analytics gtag setup for Rails 5.2

Related Articles

Ace the Technical Interview

  • Easily find the gaps in your knowledge
  • Get customized lessons based on where you are
  • Take consistent action everyday
  • Builtin accountability to keep you on track
  • You will solve bigger problems over time
  • Get the job of your dreams

Take the 30 Day Coding Skills Challenge

Gain confidence to attend the interview

No spam ever. Unsubscribe anytime.