160

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?

Jeff Atwood
  • 60,897
  • 45
  • 146
  • 152
uriDium
  • 12,309
  • 19
  • 70
  • 131
  • 6
    What language/technologies are you developing in? Because you could do something where if the hostname = http://127.0.0.1/ or http://localhost/ (or whatever your local instance is) then don't show the analytics script block. Should be one line of server-side code... – davewasthere Aug 09 '09 at 18:31
  • 4
    I don't know why someone wants to move this to SuperUser - it's clearly a programming/development question. – Thomas Owens Aug 10 '09 at 20:03
  • I am using asp.net, vs2005 and it is a web project. – uriDium Aug 11 '09 at 11:39
  • You clould use as script-blocker e.g [umatrix](https://chrome.google.com/webstore/detail/umatrix/ogfcmafjalglgifnmanfmnieipoejdcf?hl=en) or [uBlock](https://addons.mozilla.org/en-US/firefox/addon/ublock-origin/). It'll block all ad scripts, including googles analytic script. – Simon May 01 '19 at 16:11

23 Answers23

216

I like the simple approach of using javascript. It works anywhere.

<script type="text/javascript">
if (document.location.hostname.search("myproductiondomainname.com") !== -1) {

//google analytics code goes here

}
</script>
keza
  • 2,471
  • 2
  • 14
  • 10
  • 30
    Thanks. I personaly use `if (document.location.hostname == "example.com") { /* ga code */ } else { _gaq = {push: function(arg) {console.log("ga:", arg)}}}` - this allows me to safely use some event trackers and custom _gaq calls anywhere in my code and in the same time allow me to debug GA calls on dev environment. – seriyPS Jul 14 '13 at 23:04
  • 1
    Another, _slightly_ more readable solution would be to use a regex literal: `if(/example\.com/.test(window.location.hostname)) { /* GA code */ }` – mjswensen Oct 30 '13 at 05:03
  • I like this approach much more because it allows you to view pages both in dev and production if you have a azure site (or a similar set up). IE when you go to http://xxxxx.azurewebsites.net/ it doesn't pick up the session. Thanks! Simple fix as well took me 5 minutes to put in to production. – Jhayes2118 Jun 24 '14 at 00:29
  • 11
    Fuller illustrate solutions provided above (assume ga is object name): `var ga; if (document.location.hostname == "example.com") { /* GA script here */ } else { console.log("Running non-production google analytics replacement now"); ga = function(arg) { console.log("ga:", arguments);};} ga('create', 'UA-xxxxx', 'auto'); ga('send', 'pageview');` – Bryan Aug 05 '14 at 15:23
  • since ga is called like a function. I do it like so: – Gal Bracha Dec 28 '15 at 16:49
  • I created another property in google analytics to track development events. I used hostname logic to set appropriate tracking Id. `(document.location.hostname==="my-production-domain.com")? gtag("config", "prod-tracking-id") : gtag("config", "dev-tracking-id");` Now dev events will go to different dashboard and I can debug analytics events even for dev testing without polluting production traffic data. – Bipul Jun 12 '18 at 04:38
  • I think this one is better: `document.location.hostname.startsWith("stackoverflow.com");` because it excludes `beta.stackoverflow.com` – Andi Giga Apr 10 '19 at 16:55
104

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.

Yahel
  • 35,856
  • 22
  • 98
  • 150
chaos
  • 115,791
  • 31
  • 292
  • 308
  • 17
    A [newly created] filter only applies on future data. – viam0Zah Aug 10 '09 at 11:03
  • 2
    That is perfect. I am doing this proactively. I have not yet actually added the javascript Google Analytics requires. I will put the filter in place and then deploy. – uriDium Aug 11 '09 at 11:40
  • 8
    just came across this question randomly... I'd just use a different UA-ID for my development environment. That's what i do right now. I think this would be a better approach than having to block IP addresses and stuff. – karry Oct 18 '12 at 18:31
  • 3
    Actually there is an even easier way. This technique will only work for future data as well though. When initializing the ga object just set an explicit cookie domain. Reference: https://developers.google.com/analytics/devguides/collection/analyticsjs/domains – Darren Apr 30 '14 at 16:56
  • 2
    Depending on your development environment, you can also exclude hostnames. I develop with asp.net so I excluded all hostnames that contains `localhost`. If you usually have a testing environment under a subdomain, just exclude that. – CularBytes Feb 14 '16 at 13:34
  • If I apply my ip-number as exclude and when I use the website, that is used in production phase, then my traffic data will not be recorded in production phase, is it true? – What'sUP Sep 21 '17 at 14:07
36

It's 2014 and I'm still unsatisfied with all existing solutions...

  • IP filters require a static IP address. What if I'm working from home or from a coffee shop?
  • Checking host name eliminates hits from a dev environment, but what if I'm debugging the live site?
  • Editing server configurations is annoying/advanced and multiple domains are complicated.
  • Opt-Out extensions either block hits on all websites or none at all depending on who you ask.

So, I created my own Browser Extension... https://chrome.google.com/webstore/detail/lknhpplgahpbindnnocglcjonpahfikn

  • It follows me wherever I go
  • It works on a dev environment and on live/public domains
  • It only affects me and the sites that I'm developing
  • It turns on/off with one click
  • It's easy to verify that it is truly not sending any data to analytics

It works by keeping a "developer cookie" set on your machine at all times just for the domains that you choose. You then simply check for this cookie in your script before sending any data to Analytics. You customize your own unique NAME and VALUE for the cookies in the extension's settings. This can easily be used by a team of people, so developers, content creators, proofreaders, and anyone else in your organization can all view pages without inflating the statistics.

Examples of how to put the code into your pages...

JavaScript

if (window.location.host==="mydomain.com" || window.location.host==="www.mydomain.com") {
   if (document.cookie.indexOf("COOKIENAME=COOKIEVALUE") === -1) {
      // Insert Analytics Code Here
   }
}

PHP

if ($_SERVER['HTTP_HOST']==="mydomain.com" || $_SERVER['HTTP_HOST']==="www.mydomain.com") {
   if (@$_COOKIE["COOKIENAME"] !== "COOKIEVALUE") {
      // Insert Analytics Code Here
   }
}

Verifying that the HOST name equals the domain of your live site ("mydomain.com") ensures that the analytics data will never be sent by ANY visitor while viewing from a test domain such as "localhost" or "beta.mydomain.com". In the examples above, "www.mydomain.com" and "mydomain.com" are the two valid domains where we DO want visits to be recorded.

The live site sends data to analytics as expected UNLESS a developer cookie is found with matching values. If it sees that unique cookie set on your device, then your visit will not count towards your totals in Google Analytics or whatever other analytics tool you prefer to use.

Feel free to share my solution and use my extension to keep those cookies set.

seebigs
  • 809
  • 8
  • 9
  • This is a great solution. Thanks! – Nate Jan 13 '15 at 15:27
  • 1
    Hey seebigs, could you take this a step further and instead of requiring developers to change their analytics code, just find a way to intercept and replace the ga object with a mock object instead? You can theoretically do that after the JS loads but before the analytics code runs.... There is https://chrome.google.com/webstore/detail/analytics-blocker/jmcpbefnpobogldglnlikgojpaddibgb/support but it appears to be broken and unsupported. – jmort253 Jul 27 '15 at 04:25
25

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.

Nando Vieira
  • 963
  • 10
  • 16
  • This is of limited use as it only applies if the development machine and the system under test are the same one. – JoshJordan Sep 09 '09 at 19:14
  • 1
    Think this is probably the most widely used solution, though instead of comparing to ´"development"´, you compare to ´"production"´ - meaning, as long as the site is run in a production environment, we render the GA script, otherwise not (such as staging servers, development or test servers). Obviously this doesn't handle the case of you debugging a live environment, but that's fine for most ppl. – miphe Jan 21 '15 at 09:26
  • 2
    You can also if ENV["RAILS_ENV"] == "production" – moeabdol Feb 22 '16 at 16:04
20

You can use this code

<script>
var host = window.location.hostname;
if(host != "localhost")
{
    // your google analytic code here
}
</script>
prawito hudoro
  • 363
  • 3
  • 9
17

The solution is to use Google Tag Manager (GTM) to handle your Google Analytics. This will allow you to only fire Google Analytics on your production domain without having to write any conditionals in your site's code. Here's how to do it:

In GTM, set a Trigger that only fires when the Page Hostname contains your production domain.

enter image description here

Then set a Tag for Universal Analytics and make its Trigger the one you just created.

enter image description here

Martyn Chamberlin
  • 1,167
  • 13
  • 17
17

We setup a 2nd google analytics tracking code for development and QA work -- actually comes in handy when you want to test your analytics integration, also ensures one doesn't have bleedover into production stats.

Wyatt Barnett
  • 15,444
  • 3
  • 31
  • 51
  • I've never thought of doing this, but the more I do, the more I like it :) – Ben Cull Apr 04 '14 at 05:49
  • Does this require a lot of overhead? My impression is that the dev team just publishes preview and staging directly to live production without making any code changes. – MXMLLN Feb 13 '15 at 14:25
  • 2
    @MXMLLN -- that depends on how well you are doing configuration management. In our case it was just another line in a config file we were already handling, ymmv. – Wyatt Barnett Feb 13 '15 at 15:51
  • @WyattBarnett -- Thanks, I'll see what they think. – MXMLLN Feb 13 '15 at 22:50
16

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.

astropanic
  • 10,140
  • 17
  • 64
  • 128
  • 3
    this, sir, is the simplest solution I have ever seen to this problem! +1 from me – Nir Levy Aug 10 '09 at 19:56
  • I don't recommend this approach because you're going to develop (possibly release) code that might conflict with GA. And you'll get 404s trying to dl the script, possibly blocking. – webXL Jun 01 '12 at 23:35
  • @webXL, my solution is exactly for not downloading the script at all, it is for the development machine, and not for production usage (deployment host), please point out what might conflict in this case, when GA is not used at all on development machine on the developed application... – astropanic Jun 03 '12 at 19:47
  • @astropanic, GA declares at least one global, so it is possible to overwrite it or be overwritten by it. By excluding it in development, you run that risk. Might be a small risk, but an avoidable risk nonetheless. Besides, don't the hostnames have to match up for GA to track? – webXL Jun 03 '12 at 20:27
  • You can also use [0.0.0.0 instead of 127.0.0.1](https://stackoverflow.com/questions/20778771/what-is-the-difference-between-0-0-0-0-127-0-0-1-and-localhost) – Goyllo Aug 09 '17 at 06:47
  • Yes, but 0.0.0.0 is not intended to be used as an particular address, it means "listen to all IPv4 interfaces on my machine" when you start a server. With 127.0.0.1 you're addressing a single IP address, your loopback interface in this case. – astropanic Aug 13 '17 at 10:05
8

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.

Avi
  • 1,281
  • 1
  • 18
  • 28
6

There are a few Chrome extensions that do this for you, like https://chrome.google.com/webstore/detail/fadgflmigmogfionelcpalhohefbnehm

Very convenient if your IP address is not static.

Uri
  • 20,857
  • 6
  • 38
  • 61
  • 1
    I use the following and it works GREAT for browser-based development (currently looking to address this with my node development). https://www.igorware.com/extensions/block-yourself-from-analytics – rainabba Jun 06 '17 at 00:23
6

Add this line before your Google Analytics async code runs to disable tracking for that web property ID:

window['ga-disable-UA-XXXXXX-Y'] = true;

UA-XXXXXX-Y corresponds to the web property ID on which you would like to disable tracking.

From: https://developers.google.com/analytics/devguides/collection/gajs/

AJP
  • 21,889
  • 17
  • 76
  • 108
  • I'm working on a site with a lot of pages which each have their own copy of the GA JS code. I'll eventually be making this dynamic in a footer but in the meantime, could I just add this high up the page in the header and it'll disable all calls to GA? – codecowboy Jan 22 '15 at 11:46
  • Yes as long as you provide the same web property ID that is used further down the page. – AJP Jan 27 '15 at 12:38
4

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

Joseph Lust
  • 17,180
  • 7
  • 70
  • 72
3

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.

Adrian
  • 99
  • 9
2

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.

Dan Diplo
  • 24,377
  • 4
  • 61
  • 86
2

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
  }
Nguyễn Văn Phong
  • 11,572
  • 15
  • 21
  • 43
Vinodh
  • 47
  • 7
1

Just as an additional option for this, I have a development server with lots of different sites and developers. This meant that I wasn't particularly happy with the 3 main options

  • hosts file- problematic with lots of developers and open to human error
  • if/else development block on every site etc
  • configuration on GA website - some clients have their own GA accounts; would have to be completed on every site with the potential to be forgotten/overlooked

Rather than implementing the various options in the other answers here I approached the problem in the following way. In the global httpd.conf (rather than a site specific one) I used the apache module mod_substitute to simulate the effect the hosts file fix in another answer has, but for every development site, and every developer automatically.

Enable the module

CentOS: Open /etc/conf/httpd.conf and add the following line

LoadModule substitute_module modules/mod_substitute.so

Ubuntu/Debian: Run the following command

sudo a2enmod substitute

Once you've got the module enabled add the following lines to your httpd global config file

CentOS: /etc/conf/httpd.conf

Ubuntu/Debian: /etc/apache2/httpd.conf

# Break Google Analytics
AddOutputFilterByType SUBSTITUTE text/html 
Substitute "s|.google-analytics.com|.127.0.0.1|n"

Then restart apache

CentOS: service httpd restart

Ubuntu/Debian: /etc/init.d/apache2 restart

What this does is replace all text matching .google-analytics.com with .127.0.0.1 when apache serves the page so your page renders with analytics code similar to the below example

var _gaq = _gaq || [];
_gaq.push(['_setAccount', '']);
_gaq.push(['_trackPageview']);

(function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.127.0.0.1/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
Ben Swinburne
  • 22,620
  • 8
  • 55
  • 94
1

Like people are mentioning you can either host the google-analytics.com domain locally or setup a function to see if you are working in your development network.

Keep in mind if http://www.google-analytics.com/ga.js does not load and your using onclick javascript functions to help track clicks on page elements.

IE: onclick="javascript:pageTracker._trackPageview('/made/up/folder/reference');

Your going to have JavaScript errors that will stop jQuery or other robust JavaScript functions from functioning.

gegere
  • 69
  • 5
1

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!

furnaceX
  • 397
  • 7
  • 12
1

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

Daniel Congrove
  • 2,821
  • 2
  • 24
  • 51
0

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>
user94154
  • 15,244
  • 19
  • 74
  • 113
0

I have a PHP variable set for my local development that gives me a terminal for providing data/feedback etc when I'm working on stuff.

I use XAMPP so that has an env variable for tmp which is the following:

$isLocal = (getenv("tmp") == '\xampp\tmp') ? true : false;

This doesn't exist on my production server because xampp is not being used

if($isLocal){
  // do something, eg. load my terminal
}

... Specific to this question:

<?php if(!$isLocal){ ?>
  <!-- Insert Google Analytics Script Here -->
<?php } // end google analytics local check ?>
shanehoban
  • 878
  • 9
  • 26
  • That solution can really mess up your events and conversion tracking codes in JS because you won't have a "ga" object to call. That way that the whole JS could crash and cause a lot of other issues. – omgitsdrobinoha Oct 07 '16 at 10:06
0

Today, whilst on a different computer than my own, I noticed μBlock Origin for Chrome was blocking Google AdSense by default. After some Googling, I found this article. It notes also μBlock Origin Firefox, μ Adblock for Firefox and Ad Muncher for Windows block AdSense by default. Most other options are listed as being configurable to block AdSense.

This seems to work and is useful because my IP is often dynamic, so the Chrome extension can follow me around as long as I am logged in to Chrome.

0

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,
                    });
                  `,
      }}
    />
  </>
}
ruX
  • 6,233
  • 2
  • 35
  • 29