How to use Analytics.js to fix your analytics code and achieve metrics nirvana

March 4, 2014 Aaron Severs

analytics-drawing

There are so many great analytics tools out there that it’s often hard to know what to use. What’s more, each one comes with its own flavor of JavaScript API that’s slightly different from all the rest, meaning each new one you choose to add, even if you’re not sure it’s right for you, is a ton of work to implement.

Analytics.js – one API to wrap them all

Thanks to our friends at Segment.io, there is now a free, open-source solution to this problem. Analytics.js is an open source JavaScript library that wraps the native APIs of over 50 popular analytics, marketing, and error tracking tools into a sensible, common interface. For anyone who has implemented Google Analytics + KISSmetrics + UserVoice + Hubspot + foo + bar all on one site, you know what this could mean for code cleanliness.

Also consider the huge business win – instead of carefully deciding on each analytics solution before prioritizing the implementation, you can instead try several solutions all at once, with no extra effort, then choose the best to keep after evaluating them all with real data.

Here’s how it works

There’s great documentation available here, but the implementation instructions mostly refer to Segment.io’s paid offering (which is worth a look if you want something even easier to use, and with a REST API). For my example, I’m going to assume you’re building a Rails app, but you can apply the below to any framework.

1. Initialize Analytics.js

Download Analytics.js from its repo on GitHub. There is a minified version included, but since most Rails apps use the asset pipeline, I use the unminified source and let Rails do the rest. Vendor this JS by placing it in /vendor/assets/javascripts.

You’ll now want to load Analytics.js on all pages. However, it isn’t necessary to block on this, so to speed things up, it is recommended that you load it asynchronously. I typically do this in a shared partial that I then include in all my layouts.

<!-- /app/views/shared/_analytics.html.erb -->
<script type="text/javascript">
  // Create a queue to push events, and stub all methods
  window.analytics || (window.analytics = []);
  window.analytics.methods = ['identify', 'track', 'trackLink', 'trackForm', 'trackClick', 'trackSubmit', 'page', 'pageview', 'ab', 'alias', 'ready', 'group', 'on', 'once', 'off'];
  window.analytics.factory = function (method) {
    return function () {
      var args = Array.prototype.slice.call(arguments);
      args.unshift(method);
      window.analytics.push(args);
      return window.analytics;
    };
  };
for (var i = 0; i < window.analytics.methods.length; i++) {
  var method = window.analytics.methods[i];
  window.analytics[method] = window.analytics.factory(method);
}

// Set up a way to async load Analytics.js after everything else
analytics.load = function(callback) {
  var script = document.createElement('script');
  script.async = true;
  script.type = 'text/javascript';
  // If using rails, use the asset_path helper
  // Don't forget to add analytics.js to config.assets.precompile!
  script.src = '<%= asset_path('analytics.js') %>';
  script.addEventListener('load', function (e) {
    if(typeof callback == 'function') {
      callback(e);
    }
  }, false);
  var firstScript = document.getElementsByTagName('script')[0];
  firstScript.parentNode.insertBefore(script, firstScript);
};

Now we initialize Analytics.js with all of our integrations. In this example, I’m using:

  • Google Analytics for visitor tracking and campaign tracking
  • Mixpanel for user behavior, cohort, and funnel analysis
  • Customer.io for marketing automation and drip campaigns
  • Sentry for JavaScript error tracking and alerts

You’ll notice I refer to Rails.application.config for my specific ids and keys. Your implementation may vary.

// Continues from above
analytics.load(function () {
  analytics.initialize({
    'Google Analytics': {
       trackingId: '<%= Rails.application.config.google_analytics_id %>'
     },
     'Mixpanel': {
       token: '<%= Rails.application.config.mixpanel_token %>',
       people: true
     },
     'Sentry': {
       config: '<%= Rails.application.config.sentry_js_dsn %>'
     },
     'Customer.io': {
       siteId: '<%= Rails.application.config.customer_io_site_id %>'
     }
  });
});

2. Use the API to Identify Your Current User

For integrations that allow you to identify users, such as Mixpanel People or Customer.io, Analytics.js has a simple API that you call once to do all the things!

// Continues from above

// if a current user is logged in, identify them to analytics.js
<% if @current_user %>
analytics.identify('<%= @current_user.id %>',{
  created: '<%= @current_user.created_at %>',
  email: '<%= @current_user.email %>',
  name: '<%= @current_user.name %>'
});
<% end %>

// track the page view
analytics.page();
</script>

3. Track Your Events

Now you can start tracking events in your application code, using the analytics.track() method.

// In your application code somewhere
analytics.track('Ate a donut', {
  flavor: 'Chocolate',
  price: 2.50
});

This event will be tracked in all of your analytics tools, all at once. Want to try another tool next week? Just add its initialize method… and that’s it!

Welcome to metrics nirvana!

(Thanks to Segment.io’s generally great documentation for help with this post.)

About the Author

Biography

Previous
DZone 2014 Cloud Platform Report: PaaS is More Popular than IaaS
DZone 2014 Cloud Platform Report: PaaS is More Popular than IaaS

This week, DZone published their 2014 Cloud Platform Report which reveals that Platform-as-a-Service (PaaS)...

Next
Setting up a FreeBSD Server on Hetzner, Part 1: Base Install and ssh
Setting up a FreeBSD Server on Hetzner, Part 1: Base Install and ssh

This blog post covers the procedure to configure a FreeBSD virtual machine located in a Hetzner (a German I...