Kyle Banks

Disabling Google Analytics in Development Using Only JavaScript

Written by @kylewbanks on Aug 29, 2013.

When developing for the web, many people use Google Analytics to track, you guessed it, analytical data about users. While the tool is great at what it does, one problem that consistently comes up is the need to keep development analytics from being tracked.

Usually you can use an environment variable on the server-side to only serve the Google Analytics code in production mode. Another option would be to setup a filter in Google Analytics to only track events from a specified domain (your production URL).

The server-side solution is the most elegant in my opinion because filters aren't applied to the Real-TIme analytics, which can be irritating at times. But what if you are simply serving static HTML files, or want to use a separate, development mode Google Analytics account, even in your staging servers that are set to production mode?

The solution is to use JavaScript and detect the hostname to determine if it's being served in production mode.

<script type="text/javascript">
     if (document.location.hostname.indexOf("kylewbanks.com") != -1) {
          /* Production Google Analytics Code */
     } else {
          /* (Optional) Development Google Analytics Code */
     }
</script>

In most cases, this logic is best suited for the server-side, or using filters in Google Analytics if you can get passed the fact that Real-Time analytics are not filtered. But, for cases where JavaScript is the best solution, enjoy.

Let me know if this post was helpful on Twitter @kylewbanks or down below, and follow me to keep up with future posts!