2 ways to setup Google Analytics for multiple environments

When we're developing a website or app, one thing we want to avoid is filling our Google Analytics data with noise from our own activity. In this article, we're going to demonstrate two different options to address this.

# 1. Conditional loading

This method will load the google analytics script based on the browser's window.location.hostname property.

// this will be the production domain
// that you want to check against
const productionHostname = 'foobar.com'

// if its the production server
// we'll run google analytics
if (window.location.hostname === productionHostname) {
  /*
    Google Analytics script...
   */
}

# 2. Different UAs

Alternatively, we can define a custom user agent depending on the host like so:

const UAs = {
  'production-domain.com': 'UA-1',
  'staging-domain.com': 'UA-2',
  'development-domain.com': 'UA-3'
}
/*
  Google Analytics script...
 */
ga('create', UAs[window.location.hostname], 'auto')
ga('send', 'pageview')

This allows us to setup different analytics filters based on the UA.

If you have other approaches that you find useful, I'll be happy to add them here and give you the credit.

fetching pluses ...
More Articles

Subscribe to the newsletter

No spam. Unsubscribe any time.