Universal Analytics with Turbolinks and Gon

A quick quick guide to make Universal Analytics play nicely with Turbolinks.

<a href="https://github.com/rails/turbolinks", alt="Turoblinks - Github" rel="nofollow" target="_blank" >Turbolinks can boost your Rails 4 app performance but will cause unexpected behavior if you don't plan ahead. Client-side analytics libraries, like Google Analytics, will not function out of the box with Turbolinks and I will walk-through how to make Universal Analytics play nicely with Turbolinks.

For some quick background, while conducting research, I found a few issues with existing Google Analytics / Turbolinks solutions out there. These included:

  1. The analytics keys "UA-XXXXX" were being hard-coded in the javascript/coffescript files, rather than being set in a settings.yml file with other important keys. Loading from a settings file makes it easier to switch out keys, allowing me to test custom events, dimensions and other goodies on a staging server.
  2. Virtually every solution I found was built on Classic Analytics, which is being depreciated, rather than the newer Universal Analytics.
  3. None of the configurations I found handled custom events, dimensions, metrics, e-commerce and other important functionality. (Note: this will be covered in a separate post)

To handle these issues, I ultimately came up with the following turbolinks-friendly coffeescript implementation that uses the Gon gem to pass back-end Rails data to our javascript while using the newer analytics.js library (note: events will be covered in a separate post).

This is the most important part of the configuration:


@analyticsId: ->
  gon.google_analytics_id

This is where the key from our settings.yml file is being passed into the coffeescript file. I'm not going to go into details of how Gon works, but just understand that the variables you pass from the back-end to the client, need to be available before the javascript is loaded. We do this through a before_action in application_controller.rb and a Gon helper method the application head.


 # application_controller.rb
 before_action :set_gon_google_analytics_id
  

private

def set_gon_google_analtyics_id
  gon.google_analtyics_id = Rails.application.secrets.google_analytics_id
end

Finally, you need to make Gon accessible to your javascript files, so we instantiate it before our javascript loads in the head.

//application.html.haml
= include_gon
= javascript_include_tag "application"

A future post will walk through setting up events and social tracking with a Turbolinks-compatible setup. For reference, here are some other resources to check out: