Is there a way to stop Google Analytics counting development work as hits?

Viewed 63958

I have added the JavaScript that I need to the bottom of my pages so that I can make use of Google Analytics. Only problem is that I am sure that it is counting all my development work as hits. Seeing as I probably see some of those pages a hundred times a day it will really skew my readings. Is there a way to turn it off from a particular IP address or is this something that should be built into my build process so it only gets added when I build for deployment?

24 Answers

Yeah, you go into Analytics Settings, edit your site, and +Add Filter to define a filter that excludes your IP address.

Past data is not regenerated with filters applied, so you'll only have the benefit of them moving forward.

If you're not using static IP, setting IP filters on GA can't help you.

Set an environment variable and conditionally display it. Take the following Ruby on Rails code, for instance:

<% unless RAILS_ENV == "development" %>
    <!-- your GA code -->
<% end %>

You can extend this behavior every language/framework you use on any operating system. On PHP, you can use the getenv function. Check it out the Wikipedia page on Environment Variables to know how to proceed on your system.

If You are behind NAT or You can't for other reason give Your IP to Google Analytics, then the simplest method is to set the google analytics domain to localhost (127.0.0.1), from now when You open Your browser, all request to Google Analytics will be directed to Your working station, without knowledge of Google Analytics.

To disable localhost hits, just create a filter to exclude localhost. Go to Admin -> Property -> View Settings to do so. Check the following screenshot for some help.

ga view exclude localhost

To disable production URL hits for yourself if you visit using a non-static IP, you can use a Chrome extension like Developer Cookie to skip running the Google Analytics code if it's you.

I personally don't do this since I use an Ad Blocker which already blocks Google Analytics on my browser.

Use a custom metric to filter all this traffic.

When you init GA in your app, set a custom flag to track developres:

// In your header, after the GA code is injected
if( <your_code_to_check_if_is_dev> ) {
  ga('set', 'is_developer', 1 );
}

Then add a filter in your GA Account to remove these results.

Admin > Account > All Filters > Add Filter > User Defined

enter image description here

I use Ad Blocker for Firefox, it can specifically block the Google analytics tracking script. Since firefox is my primary development browser it works great until i need to test my work in other browsers.

For Google Analytics 4 (GA4), you can create a rule to define IP addresses whose traffic should be marked as internal.

Define Internal Traffic

Path: Admin > Property > Data Streams > select your stream > More Tagging Settings > Define internal traffic

enter image description here

Define a rule to match one or more IPs that represent your internal traffic.

enter image description here

GA4 Data Filters

Path: Admin > Property > Data Settings > Data Filters

You will find the default filter "Internal Traffic" set to "Testing" mode.

Change to "Active" to enable the filter.

enter image description here

Probably not helpful to you, but I solved this problem by writing a custom ASP.NET server control that injects the required JavaScript. I then added the live URL to web.config and then only made the control visible when the host name matched the live URL in web.config.

If you have a react application and you have ejected the app(this could work for CRA as well). You can make use of the below code snippet in the index.html page.

<script type="text/javascript">
  if("%NODE_ENV%"==="production"){
  //your analytics code
  }

I know this post is super old, but none of the solutions met my needs. Not only did I want to remove dev work from GA (and FB), but I also wanted to have some folks within the company not be counted in GA and FB. So I wanted a relatively easy method for those folks to exclude themselves from analytics without a plugin, or ruling out a domain ip (as folks with laptops wander).

I created a webpage that users can go to and click a link to opt out of the GA and FB tracking. It places a cookie for the site. Then I check that cookie to determine if we should send data to GA and FB.

I originally set this up on a site for called Dahlia, which is a boutique maker of items for Greek Orthodox Weddings and Baptisms.

Here's the code:

I put the following code in the header for all web pages:

<script>
//put in your google analytics tracking id below:
var gaProperty = 'UA-XXXXXXXX-X';

// Disable tracking if the opt-out cookie exists.
var disableStr = 'ga-disable-' + gaProperty;
if (document.cookie.indexOf(disableStr + '=true') > -1) {
  window[disableStr] = true;
  window['ga-disable-UA-7870337-1'] = true;  //This disables the tracking on Weebly too.
} else {
   //put in your facebook tracking id below:
  fbq('init', 'YYYYYYYYYYYYYYY');
  fbq('track', 'PageView');
}
</script>

Be sure to add your GA and FB tracking IDs in the spaces provided. This was originally written for a Weebly (shopping CMS) site. So if you are not on Weebly you can remove the line that mentions weebly.

Then I created a new webpage called "do-not-track" with the following code in the header:

<script>
//put in your own google analytics tracking id below:
var gaProperty = 'UA-XXXXXXXX-X';
var disableStr = 'ga-disable-' + gaProperty;

// Opt-out function
function gaOptout() {
  document.cookie = disableStr + '=true; expires=Thu, 31 Dec 2099 23:59:59 UTC; path=/';
  window[disableStr] = true;
  gaOptoutCheck();
}

// Check Opt-out function
function gaOptoutCheck() {
    var name = "ga-disable-"+gaProperty+"=";
    var ca = document.cookie.split(';');
    var found = "false";
    for(var i=0; i<ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1);
        if (c.indexOf(name) == 0) found = "true";
    }
    if (found == "true") alert("Cookie is properly installed");
    else alert("COOKIE NOT FOUND");
}
</script>

And the following code in the body:

<a href="javascript:gaOptout()">Click here to opt-out of Google and Facebook Analytics</a>
<br><br>
Please visit this page on every computer, laptop, phone, tablet, etc. that you use; 
and for all browser you use on each of those devices.
<br><br>
If you ever remove cookies from browser, you will need to repeat this process for that browser.
<br><br><br>
<a href="javascript:gaOptoutCheck()">
Click to check if cookie is set</a>
<br><br>

Here is my full writeup for the Weebly site

Hope this helps somebody!

get the request host variable.

So wrap an if statement around the analytics javascript like this (Ruby-esque pseudocode):

<body>
<shtuff>dfsfsdf</shtuff>
if not (request.host == 'localhost')
  #analytics code here
elsif (request.host == the server's ip/domain)
  #analytics code here
else
  #do nothing
end
</body>

Unfortunatelly, it doesn't seem to be possible to exclude localhost from the reporting when using App + Web Properties type of setup:

Displaying Filters for web-only Properties only. Filters can't be applied to App + Web Properties.

For the nextjs web application, especially ones which are using static generation or SSR this would work:

In your document.tsx

export default class MyDocument extends Document {
  render() {
    return (
      <Html lang="en">
        . . . . . 
        <body>
          <Main />
          <NextScript />
          {process.env.NODE_ENV === 'production' ? injectAnalytics() : ''}
        </body>
      </Html>
    );
  }
}

where injectAnalytics is a function which returns your GA code, for instance:

function injectAnalytics(): React.ReactFragment {
  return <>
    {/* Global Site Tag (gtag.js) - Google Analytics */}
    <script
      async
      src={`https://www.googletagmanager.com/gtag/js?id=${GA_TRACKING_ID}`}
    />
    <script
      dangerouslySetInnerHTML={{
        __html: `
                    window.dataLayer = window.dataLayer || [];
                    function gtag(){dataLayer.push(arguments);}
                    window.gtag = gtag;
                    gtag('js', new Date());

                    gtag('config', '${GA_TRACKING_ID}', {
                      page_path: window.location.pathname,
                    });
                  `,
      }}
    />
  </>
}

I am using this code to disable google analytics in rails 6 in production.

When admin login I set is_developer cookie to disable google analytics for 1 year.

If admin logout, I do not delete is_developer cookie. So,google analytics will be disabled after admin logout.

You can comment all console.log after testing.

<% if Rails.env.production? %>
  <% ga_tracking_id = 'G-36......Y6' %>
  <!-- Global site tag (gtag.js) - Google Analytics -->
  <script async src="https://www.googletagmanager.com/gtag/js?id=<%= ga_tracking_id %>"></script>

  <% if user_signed_in? && current_user.admin? %>
    <script>
      if(document.cookie.indexOf('is_developer') > -1) {
        console.log('gtag:- is_developer cookie already set');
      } else {
        document.cookie = `is_developer=1; expires=${new Date(new Date().getTime()+1000*60*60*24*365).toGMTString()}; path=/`;
        console.log('gtag:- is_developer cookie set for 1 year');
      }
    </script>
  <% end %>

  <script>
    if(document.cookie.indexOf('is_developer') > -1) {
      console.log('gtag:- disabled for developer');
    } else {
      console.log('gtag:- enabled');
      window.dataLayer = window.dataLayer || [];
      function gtag(){dataLayer.push(arguments);}
      gtag('js', new Date());
      gtag('config', '<%= ga_tracking_id %>');
    }
  </script>
<% end %>

If you have any suggestions, comment below.

Related