Google Analytics gtag with Rails 5 and Turbolinks

Get your Ruby on Rails 5 application working with Turbolinks and the new gtag.js for Google Analytics

July 6, 2018 - 1 min read

Google has rolled out a new way to send your data to Google Analytics, Adwords and more called gtag.js. This seems to be the new default when adding new properties to Google Analytics. The old guides for how to integrate Turbolinks with Google Analytics no longer work with the new gtag.js.

Turbolinks will speed up your Ruby on Rails (and other) applications by intercepting any page changes(clicking on links) and instead loading them with AJAX and replacing the body. This means that the browser doesn’t have to parse all the assets again like Javascript and CSS. If you have a lot of Javascript this can give you a huge performance boost.

In order to get Google Analytics working with Turbolinks however you have to hook into this AJAX load in order to send the page change to Google Analytics. In the past you used the ga function to do that but that doesn’t work with the gtag.js API.

What you do instead is put this at the very top of the head-part of your application layout file: