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

March 4, 2014 Aaron Severs


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, 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’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 || ( = []); = ['identify', 'track', 'trackLink', 'trackForm', 'trackClick', 'trackSubmit', 'page', 'pageview', 'ab', 'alias', 'ready', 'group', 'on', 'once', 'off']; = function (method) {
    return function () {
      var args =;
for (var i = 0; i <; i++) {
  var method =[i];[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') {
  }, 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
  • 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 () {
    '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 %>'
     '': {
       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, 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('<%= %>',{
  created: '<%= @current_user.created_at %>',
  email: '<%= %>',
  name: '<%= %>'
<% end %>

// track the page view;

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’s generally great documentation for help with this post.)

About the Author


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)...

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...

SpringOne at VMware Explore 2023

Learn More