Use Google Analytics with Meteor

advertisements

What is the best way to include Google Analytics tracking code on your Meteor app, conditionally only for production environment only?

I am familiar with this guide, however it only works for a specific template. I would like to track across all pages and templates.

EDIT: Currently, I am doing URL matching to check if I am on production level, and then include the tracking code from Google. Not sure if this is best practice though.

// main.js
var production_url = /^my.production.url$/
if (production_url.test(window.location.host)) {
    (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
    (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
    m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
    })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

    ga('create', 'TRACKING_CODE', 'production.url');
    ga('send', 'pageview');
}

The code above is put directly in the main.js file and not under any Template instance.


Even though this question is old it might be worth mentioning that we created an analytics package, okgrow:analytics for Meteor, where we set the trackingID's of the platforms being integrated in the settings.json file.

By using different trackingID's for different environments you'll be able to specify the right trackingID for production. Simply leave the trackingID blank in the settings.json file on development/testing and it will still work (will show tracking events in debug).

Hope that helps!