Glad You're Ready. Let's Get Started!

Let us know how we can contact you.

Thank you!

We'll respond shortly.

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


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

  1. Joshua says:

    Do you have this actually working somewhere? Doesn’t send any calls for me unless I place them in the load() function. Never calls any page() or track() calls otherwise. It seems to be build to allow queuing but it doesn’t appear to ever read that queue on init.

  2. Joshua says:

    Turns out the above code does not work for me as the open source version doesn’t seem to reload whatever was applied to the dummy object. A copy of the initial analytics object needs to be made then loaded to the real one once loaded. Gist:

  3. Aaron Severs says:

    You’re right. The open source version of analytics.js doesn’t play back the queued events after load, so there is some more code needed to go through the queue and replay the events, but I have not updated this post with the solution. I’ll add it later today!

  4. Karim Helal says:

    Great article, thanks for posting. Regarding Joshua’s comment, is the article now updated to reflect his issue or should we take his gist as the working example? Thanks!

  5. ashish says:

    How can get data from segment io using analystic js?

Post a Comment

Your Information (Name required. Email address will not be displayed with comment.)

* Copy This Password *

* Type Or Paste Password Here *

Share This