Excluding Employee Traffic from Google Analytics, Pixels, and More

  • report
    Disclaimer
    Click for Disclaimer
    This Post is over a year old (first published about 5 years ago). As such, please keep in mind that some of the information may no longer be accurate, best practice, or a reflection of how I would approach the same thing today.
  • infoFull Post Details
    info_outlineClick for Full Post Details
    Date Posted:
    Apr. 01, 2019
    Last Updated:
    Apr. 05, 2019
  • classTags
    classClick for Tags

A question that I keep seeing pop up on digital marketing forums, and have had to tackle myself in the past, is how to exclude “internal traffic” from showing up in Google Analytics (e.g. when your own employees are browsing your own website). This post will cover a few different solutions, some of which can work for many different platforms other than just Google Analytics, such as preventing pixel fires coming from employees. There is a lot of misinformation when it comes to marketing technology, so please approach this topic with a critical eye and keep in mind that technology is also subject to change.

This is a very long and comprehensive guide to this issue, so you might want to jump to the section that interests you using the table of contents below:

Quick Reminder: Why does this even matter?

If someone else told you to implement this, you might be wondering why it is even worth the time and effort to set up. Especially if your site gets a bunch of traffic already, what difference does it make if a few extra page views show up from internal traffic? Or employees occasionally see your own ads?

Why internal filtering is important for Google Analytics and other analytics or performance metrics platforms:

Although internal traffic might have a small impact on metrics like total page views, it is important to recognize it can greatly affect aggregate metrics like “avg session duration”, “time on page”, “pageviews per session”, and many more.

Here is a practical example. Let’s say that your company is working on developing a new landing page and wants to evaluate results. So far, 50 actual users have visited the page and each of them has only spent 10 seconds looking at the page before moving on to a different part of the site. There is a team of 2 employees at your company that worked on building the landing page and continue to tweak it, so each of their “time on page” is 30 minutes. If you look at the average time on page for that landing page in GA, you would see 79 seconds as the average time on page, which doesn’t look that bad, despite the majority of users only spending a measly 10 seconds on the page! This can make it very hard to evaluate performance based on site changes, especially since in order to make site changes, more employees have to be interacting with the site.

Why internal exclusions are important for digital advertising (showing ads to employees):

The issue with showing ads to employees is mostly one that is tied to scale; if you are at a small business, this is much less of a concern. However, if you are a large business, displaying ads to employees can actually have a surprising impact on both budget and performance metrics.

  • Ad Spend: For display advertising, since impressions can be very inexpensive, it can be easy to forget how spend can add up. For example, lets say your average CPM for a remarketing campaign is $5. That’s just $0.005 per impression. This is an extreme example, but if you have 200 employees at your workplace, your campaign is frequency capped at 60 impressions an hour, and your employees have visited your website but are not being excluded from targeting, assuming an 8 hour work day, you could potentially be wasting $480/day on internal impressions (((200 * 60 * 8)/1000)*5). That could be upwards of 14 grand a month in wasted budget! For PPC advertising, costs can skyrocket if your employees are seeing and clicking your own ads, especially if you are in an industry where clicks are more expensive, such as law firms.
  • Digital marketing metrics: Most people immediately worry about wasted spend when considering impressions wasted on employees, but the impact on metrics is important to consider as well. Employees are not likely to click on your own ads (and for good reason; one would hope they already are familiar with the place they work every day!) which will drive down your CTR for display campaigns. For paid search campaigns, such as AdWords, the negative effect on CTR is worse, since CTR and expected CTR is a component of quality score and ad rank, both of which can affect your final CPC and ad positions!
  • If your own employees are trying to find your company website (to log into a internal portal, read documentation, etc.), every time they search your company name on Google, if you have a brand campaign without employee exclusions, one of two things is likely to happen:
    • A) They see your ad, click on it, and you have now just paid for your own employee to visit your own site. Or…
    • B) They see your ad, they know it costs you money if they click on it, so they ignore it to scroll further down the page and click on the regular search result for your site. But, now Google has seen that user ignore your ad, which means your CTR will decrease and potentially your expected CTR metrics as well!

Introduction to IP Address Exclusion and  Cookie Based Exclusion

The two main overall methods to block or exclude internal traffic is IP based filtering and cookie based exclusions. Here is a brief generic description of both:

  • IP address exclusion: Your “public” IP address is a special address, kind of like your postal address, that is provided by your internet service provider (e.g. Comcast, Frontier, etc.) and is unique to your network (the internet connection that is shared across devices at your work), but not unique per device on the same network. It is automatically sent by your computer as part of every web requests, such as loading a web page. Google Analytics does not collect IP addresses (at least not in a way you can view as a user), but allows you to exclude traffic based on it.
  • Cookie based exclusion: A cookie is a very small digital file that can contain arbitrary text, and websites can “set” cookies on your computer just by you visiting them. The power of cookies is that they flow in both directions, from the server to your computer, and then back again from your computer to the server. This is how websites know that you are a logged in user, and why if you clear your cookies, you suddenly need to log back into all your password protected websites. Using the power of cookies, it is possible to block internal traffic for a variety of purposes and across networks.

Comparison of IP Address vs Cookie Based Exclusion

First, here is a quick comparison of the two main methods that can be used to differentiate employee traffic from non-employee traffic – IP based exclusion vs cookie based exclusion:

IP Based Exclusion Cookie Based Exclusion
No action required from employees to deploy

Employees have to either visit a special page or your business needs to already have some sort of internal site in use

Can be used to block:

  • GA recording traffic
  • Showing ads to your own employees*

Can’t be used to block:

  • Most pixel fires**
  • FB pixel**

* = Depends on ad platform, more on this later.

**  = Not without special setup, see section on advanced IP exclusion.

Can be used to block:

  • GA recording traffic
  • Most pixel fires
  • FB pixel
  • showing ads to your own employees *

* = Depends on ad platform, more on this later.

 

Works across devices (as long as they are using the same network). If 200 employees are all sharing the same network, they can be blocked by excluding a single IP address.

Each device needs to have its own cookie set. Per device, each browser also needs its own cookie set (e.g. Chrome vs Firefox)

Each network (E.g. building A vs building B) would need an IP address filter set up for it. IP addresses can change, so lists would need to be kept up to date.

Can’t be used to block traffic if employees take laptops home, to conferences, travel, use VPNs or proxies, etc.

Can’t be (easily) used with dynamic IPs

 

Cookies persist, no matter how many times a device switches networks, even if it is a mobile device.

Employees can manually clear cookies, which would require them to be re-registered with the blocking cookie.

One time setup is easy, if you just want to exclude traffic from Google Analytics or block paying to show ads to your own employees.

However, requires more upkeep if IP addresses change, employees use VPNs or Proxies, etc.

One time setup is more complicated, but should stay working for a long time. Furthermore, a more advanced setup will allow you to block internal traffic for more than just GA.

You cannot (at least not easily) temporarily or permanently turn off exclusions for a single employee that uses a shared IP address you are blocking.

Example: You have 200 employees you want to avoid showing your own ads to, but the CEO of the company likes seeing his own ads. This kind of setup is not really possible with IP based exclusions.

 

You can very easily disable exclusions for certain employees, or in a rush, simply use an incognito browser.

 

Testing exclusions is hard, or impossible

 

Testing exclusions is easy

No changes necessary to website

 

Changes have to be either made directly to website, or through tag manager like Google Tag Manager (GTM)

Why not use geographic based exclusion?

If you live in the digital marketing world, you might be familiar with location targeting and location exclusions available in most digital advertising platforms (AdWords, Facebook, DSPs / RTB systems). As such, you might also be wondering why I don’t simply advise that everyone exclude the location of their office building from targeting and Google Analytics monitoring. The short answer is that, depending on the scenario, I might actually advise that you use both, or multiple combinations of exclusions and targeting (see summary at bottom of this post). The longer answer is a little complicated.

You see, the term “location” has become a very loose term in the digital marketing space, and depending on the technology stack you are using (Google Analytics, Facebook, etc.) it can mean very different things. On many platforms, location is actually determined by… IP address! In fact, Google Analytics currently uses IP-to-geography technology for its location metrics, as mentioned on their official help page. The problem with this, as they mention, is that mapping IP addresses to physical locations is “approximate”, and from personal experience, not very reliable. IP-to-Geo works by looking up an IP address to a table (think Excel or Google Sheets) of known physical locations associate with that IP. These tables are usually bought and sold (examples: MaxMind, Neustar, etc.), and are usually created by other companies brokering data that they acquired through other companies that… well you get the picture. The end result is that IP-to-geo technology is notoriously variable in nature, and Google Analytics might report a location for a user that is 10-100 miles off from the location reported by AdWords / Google Ads for the same exact user!

If location is being determined by IP address, this also means that VPNs will introduce very inaccurate reports, as the location of the VPN provider will be recorded, not the user.

The good news is that although Google Analytics uses IP-to-geo, most ad platforms, including Google Ads, rely on newer and more reliable technology (**when it is available) to determine user location, like GPS, logged-in user PII, and even SSID (router names) scanning. So excluding your office building from targeting in your Google Ads campaign is actually not a bad idea. The only caveat here is the same as IP blocking; you can’t easily turn it off for a single employee, so if your boss really wants to see their own ads, location exclusion is not going to work well for you, and you are much better off using cookies.

How to Implement IP Address Exclusions

As mentioned above, IP addresses can be used to exclude internal traffic from showing up in Google Analytics, as well as some other purposes. Here are instructions for each goal:

How to exclude employee visits, traffic, and events from showing up in Google Analytics by excluding IP addresses:

To exclude traffic in GA based on IP address, the steps are pretty simple. You can follow my steps below, or visit the official guide from Google.

  1. First, gather the IP addresses that you will need to block. As a reminder, if you are trying to implement this for a large company, there might be more than one IP address being used at a single geographic location; each building might have its own IP address, or even each floor of a building. It all depends on how your IT department has set up networking. Make sure you are recording the “public” IP address, which is the one that is shared across employees. To find it, you can simply Google “what is my ip” on the network you want to get the IP of, or visit a site like this one.
  2. Once you have the IP addresses you want to exclude traffic from, you can go ahead and setup a filter in the admin area of Google Analytics to exclude traffic from them. However, you need to pick which view to apply the filter to. I highly recommend having at least one “view” in your account that is unfiltered, so you might need to create a brand new view if you only have 1 view in your account at the moment.
  3. Navigate to: Google Analytics -> Admin -> Property -> View (the view you want to add the IP filter on) -> Filters -> + Add Filter.
  4. Give your filter a name, leave filter type as “predefined”, select “exclude” as filter type, and then under “Select source or destination” select “traffic from the IP addresses”, and for “select expression” use “that are equal to”. Then paste in an IP address into the field below, and hit save!
  5. If you have multiple IP addresses that you want to block traffic from, you will have to create a filter for each one using the standard method above. However, you can use Regular Expressions (aka Regex) to create a single filter that can block dozens of IP addresses at once. See this page for details, and/or use my custom built tool to quickly generate a pattern for you!

How to use IP exclusions for digital advertising (AdWords, Display Ads, etc.)

There are so many advertising platforms out there, so my main recommendation here is to simply search the help guides/ documentation for the platform you are using, or reach out to an account rep and ask if IP exclusions are possible for your account. To help expedite this, here is a table of guides on IP excluding per platform, or a note if it is not possible:

AdWords / Google Ads Link
DoubleClick Bid Manager / Display & Video 360

Carrier and ISP Targeting

[IP exclusion might or might not be possible natively]

Facebook Ads

Not possible natively

Bing Paid Search

Link

AdRoll

Link

Advanced: Blocking remarketing tags/pixels from firing based on IP address:

If the ad platform you are using does not support IP based exclusions, and/or you want to be able to block remarketing/retargeting tags from even firing in the first place based on IP, that is actually possible.

Without Google Tag Manager:

First, here is a developer oriented solution that does not require Google Tag Manager, or any special JS libraries like jQuery. You can conditionally load marketing tags either server-side (PHP, NodeJS, etc.) or client-side (Javascript), with server-side being the recommended method.

Here is client side first, as a vanilla JS solution (un-minified source):

!function(){window.conditionallyLoadTags=function(t,n,o){n="function"==typeof n?n:function(){},o="function"==typeof o?o:function(){};var e,i,a=!1,c=!1;if("object"==typeof t&&null!==t&&("object"==typeof t.cookie&&(e=t.cookie.name,((i=document.cookie.match("(^|;) ?"+e+"=([^;]*)(;|$)"))?i[2]:null)==t.cookie.value.toString()&&(a=!0)),!a&&"object"==typeof t.ipAddresses)){c=!0;var f=t.ipAddresses;!function(url,method,callback,OPT_failCallback){method="string"==typeof method&&""!==method?method:"GET",callback="function"==typeof callback?callback:function(){},failCallback="function"==typeof OPT_failCallback?OPT_failCallback:function(){console.warn("httpFetchVanilla failed")};var t=new XMLHttpRequest;t.onreadystatechange=function(){4==t.readyState&&(200==t.status?callback(t.responseText):failCallback())},t.open(method,url,!0),t.send()}("https://api.ipify.org/?format=json","GET",function(t){try{var e=!1,i=JSON.parse(t).ip;Array.isArray(f)?-1!==f.indexOf(i)&&(e=!0):f.test(i)&&(e=!0),!0===e?o():n()}catch(t){n()}},function(){n()})}c||(!0===a?o():n())}}();

conditionallyLoadTags({
    'ipAddresses' : ['216.3.128.12','19.117.63.126']
},function(){
    console.log('You are not an employee. Firing tags.');
    window.dataLayer = window.dataLayer || [];
    function gtag(){dataLayer.push(arguments);}
    gtag('js', new Date());
    gtag('config','UA-12345678-01');
},function(){
    console.log('EMPLOYEE RECOGNIZED!!! Not firing tags.');
});

For a server side solution, it can vary greatly based on what technology you are using, so here is a generic solution that would work across most PHP based sites:

Using Google Tag Manager

Using IP addresses with Google Tag Manager (GTM) introduces some additional complexity, but allows for more reusable code, since once it is set up, you can easily assign an IP address variable as a blocking trigger for multiple marketing and collection tags.

I’ll defer to Simo Ahava’s guide on implementing this, as it does an adequate job and he is kind of the king of GTM stuff.

Once this is setup, you can set up all kinds of conditional tags that fire or don’t fire for internal employees. You can block FB pixels from firing, remarketing tags, conversion pixels, and more.

How to implement cookie based exclusions:

This is where I see a lot of guides fall short, despite cookies being a great way to differentiate employees vs non-employees, especially if you have internal webpages that only employees visit (e.g. employeeportal.example.com, example.com/internal/wiki-page, etc.).

Without GTM:

The summarized version of how this works, is that whenever an employee visits a page that only an employee could see (WordPress Admin section, internal wiki page, task management page) we use Javascript to set a cookie that basically says “Hey, server! I’m an employee!”. Then in our website server code, we check for the existence and value of that cookie – if we see it, we don’t return tracking code that we return for all other users.

I actually use this exact method on this website; I don’t like logging my own hits to GA, so whenever I am logged into WordPress and browsing my own site, I make sure a cookie is set marking myself as an internal user, which doesn’t expire for a full year. You can see this actual code on the Github repo for this site.

If you are looking for some generic code, you can drop this Javascript on any internal page where you want to set the “employee marking cookie”:

function setCookie(name, value, days){
	var d = new Date;
	d.setTime(d.getTime() + 24*60*60*1000*days);
	document.cookie = name + "=" + value + ";path=/;expires=" + d.toGMTString();
}
setCookie('isInternalEmployee','true',365);

And then for conditionally loading tags based on that cookie, you can either implement code server side like this:

<?php if($_COOKIE['isInternalEmployee']!=='true'): ?>
    <!-- Put all the tags you want to conditionally load here. GA example below: -->


    <!-- Global Site Tag (gtag.js) - Google Analytics -->
    <script async src="https://www.googletagmanager.com/gtag/js?id=GA_MEASUREMENT_ID"></script>
    <script>
    window.dataLayer = window.dataLayer || [];
    function gtag(){dataLayer.push(arguments);}
    gtag('js', new Date());
    gtag('config', 'GA_MEASUREMENT_ID');
    </script>
<?php endif; ?>

Or client side, with Javascript, like this (un-minified source):

!function(){window.conditionallyLoadTags=function(t,n,o){n="function"==typeof n?n:function(){},o="function"==typeof o?o:function(){};var e,i,a=!1,c=!1;if("object"==typeof t&&null!==t&&("object"==typeof t.cookie&&(e=t.cookie.name,((i=document.cookie.match("(^|;) ?"+e+"=([^;]*)(;|$)"))?i[2]:null)==t.cookie.value.toString()&&(a=!0)),!a&&"object"==typeof t.ipAddresses)){c=!0;var f=t.ipAddresses;!function(url,method,callback,OPT_failCallback){method="string"==typeof method&&""!==method?method:"GET",callback="function"==typeof callback?callback:function(){},failCallback="function"==typeof OPT_failCallback?OPT_failCallback:function(){console.warn("httpFetchVanilla failed")};var t=new XMLHttpRequest;t.onreadystatechange=function(){4==t.readyState&&(200==t.status?callback(t.responseText):failCallback())},t.open(method,url,!0),t.send()}("https://api.ipify.org/?format=json","GET",function(t){try{var e=!1,i=JSON.parse(t).ip;Array.isArray(f)?-1!==f.indexOf(i)&&(e=!0):f.test(i)&&(e=!0),!0===e?o():n()}catch(t){n()}},function(){n()})}c||(!0===a?o():n())}}();

conditionallyLoadTags({
    'cookie' : {
        'name' : 'isInternalEmployee',
        'value' : 'true'
    }
},function(){
    console.log('You are not an employee. Firing tags.');
    window.dataLayer = window.dataLayer || [];
    function gtag(){dataLayer.push(arguments);}
    gtag('js', new Date());
    gtag('config','UA-12345678-01');
},function(){
    console.log('EMPLOYEE RECOGNIZED!!! Not firing tags.');
});

dasf

Using Cookies with GTM to conditionally fire tags:

The nice thing about GTM, is you can set up all of the above without needing to actually touch server-side or front-end code – you can built it all entirely within GTM. Here is how I would approach that.

Add the tag that drops the employee cookie:

First, we are going to built a tag that sets the employee cookie. That way we can easily assign that tag and cookie to hundreds of internal employee pages, as long as they have GTM installed. We can reuse the code above, but wrap it in a script tag:

<script>
function setCookie(name, value, days){
	var d = new Date;
	d.setTime(d.getTime() + 24*60*60*1000*days);
	document.cookie = name + "=" + value + ";path=/;expires=" + d.toGMTString();
}
setCookie('isInternalEmployee','true',365);
</script>

and put it in a script tag, like this – go to “Tags -> New -> Choose Tag Type -> Custom HTML”:

GTM - Set Employee Cookie - isInternalEmployee - Trigger on All Internal Pages

Now, you need to tell GTM which pages your employees are visiting and on which it should drop this cookie. If you have already set up a trigger for internal pages, you can assign it, otherwise you will need to create one from scratch. You can use simple URL pattern rules to target pages like example.com/internal/wiki or dev.example.com, but if you have a more advanced internal system or CRM, more setup might be necessary. You assign the pages as a “Page View” trigger to the cookie-setting tag, which you can see assigned above as “Internal Employee Pages”.

Configure GTM to check for the value of that cookie and store as a variable

Now, we need a way to access this cookie inside of GTM and check if it is there or not. We can use a GTM “variable” to do this. Go to “Variables -> User-Defined Variables -> New -> Variable Configuration -> 1st Party Cookie”. Now use the same name of the cookie that we are setting above as the cookie to retrieve – if you haven’t changed anything, it should be “isInternalEmployee”, like this:

GTM - Read Employee Cookie Into isInternalEmployee Cookie

Now, lets set up a trigger based on the value of this cookie, so we can either exclude or target employees with any given tag. Go to “Triggers -> New -> Choose trigger type -> Page View”. Change “This trigger fires on” from “All Page Views” to “Some Page Views”, and then select the cookie we created as the condition to test against, and then “equals” or “contains” the string we set.

Google Tag Manager - Employee Pageview Trigger - To Be Used As Exception Trigger

OK, now we can use this trigger as a “blocking” trigger on any tag! Google Analytics, Google Ads Remarketing, Facebook, Custom HTML, you name it! On any tag, once you have defined what triggers it, in the same “Triggering” section, just hit the “Add Exception” button, then select the “Employee View” trigger that we created to have as an exception – this will prevent the tag from firing if someone has the employee cookie!

GTM - Exclude Internal Traffic from Hitting Google Analytics

Further note: Instead of excluding employees, you can also target them

There is probably not much use for this, but still something cool to think about: you can use the strategies above to target employees for campaigns instead of excluding them. What sort of campaign would need that? Well, for a large company, for example McDonald’s, maybe they want to promote an employee benefit, like paid managerial classes or an internal job opening. Using a cookie based approach, you could create a remarketing campaign targeting just your own employees for this goal. Or maybe you want to deploy special tracking just for employees; if you have a public-facing wiki, you might care more about how your employees use it than the general public, so you can know which topics need more training materials.

What about Local Storage (localStorage)?

Local storage (aka localStorage aka Web Storage) is a browser feature similar to that of cookies. It lets websites save and retrieve small amounts of text data to your browser, which is persisted even if you close and open your browser back up. Like cookies, localStorage is “scoped” to the originating site, so that example.com can’t access the localStorage set by joshuatz.com.

You could easily swap out most of my cookie code for code that would store the internal user flag in localStorage. See this page for an example.

The benefit to localStorage over cookies is that localStorage is kept even if a user clears their cookies. However, this is only true if a user individually clears cookies; using Chrome or Firefox’s “clear browsing data” to erase everything will also clear out localStorage (this is something that a lot of people miss when recommending localStorage over cookies for internal traffic blocking).

The immediate downsides to localStorage over cookies are simply that it is slightly more complicated and less supported (cookies have been around for longer and act pretty much exactly the same on any given browser). However, there is also a less obvious downside: certain browsers (e.g. Safari) will not persist localStorage values in an incognito browser window, even in the same tab. This seems unlikely to have a significant impact, but my point is really that there is not a great reason to pick localStorage over cookies, at least for the time being.

A further disclaimer here is that there continues to be pushback against the use of cookies and web tracking technology, both from consumers as well as developers. As such, browsers continue to change how they let sites interact with browser technologies, a recent example being Safari choosing to block third party cookies by default. It could be that in a year from now, my advice here will be less valid as first party cookies come under scrutiny. Or maybe localStorage read/writes get limited because of some security exploit, so cookies remain the winner. Who knows what the future holds.

Summary, Conclusion, and Notes:

As you might have already guessed, my preference is for cookie based exclusions over IP address or geography based exclusions. As someone who understands the “behind the scenes” technology, it seems clear to me that where cookies are reliable, technically sound, and configurable, things like IP address and geographic targeting can be “black boxes” of data that have passed through hundreds of brokers before reaching you, and you are not always getting what is promised. However,there really is no harm in combining many of these strategies together as you see fit. For example, maybe for a branded PPC campaign that has an incredibly high CPC, you use all three exclusions to prevent any employees from clicking on your own ads, but then on a general low-cost remarketing display campaign, you just set up a simple cookie exclusion in GTM, that way some employees can still see the remarketing ads if they want to.

If you disagree with anything here, feel free to chime in. I am happy to make adjustments to the article if I find your reasoning sound and based in facts. In general, these kinds of topics could use a lot more discussion in the digital marketing world 🙂

6 thoughts on “Excluding Employee Traffic from Google Analytics, Pixels, and More”

  1. Wilco says:

    Hi, how could I push these cookies through to use on multiple domains? I have multiple company sites with non-shared-analytics. So I thought I would create a internaltraffic.ourgroupcompany.com and trigger all of the different GTM accounts over there. That works, the cookies get registered on internaltraffic.ourgroupcompany.com. However once reaching one of the GTM account websites it doesn’t look up the cookie although it has been created through the GTM account of that website.
    is there someway I could accomplish this without needing my collegue going to 4 different urls? I have thought about creating a redirectloop going from internaltraffic.ourgroupcompany.com > internaltraffic.company1.com > internaltraffic.company2.com > etc. Or working with iframes. But I guess there should be an more easy solution

    1. joshuatz says:

      Hi Wilco,

      That is a great question. That makes sense that the GTM on the individual company site can’t see the cookie that was set on the shared group site; for security, cookies are scoped by host. This is a common issue, and the usual workaround is to either use iframes like you suggested, or even more common, use a dummy network request to set the cookie. Cookies can be set by other domains other than the one of the webpage you are on, in their response to a network requests, like a GET. Technically, this could be almost anything, but lots of sites use a 1×1 image pixel as the request, and have a script on the server return the “Set-Cookie” header in the response. One reason for this is that image requests are not subject to the same security (cross-origin) policies that other requests are.

      So in your scenario, you could
      A) embed each companies opt out page (internaltraffic.company1.com, internaltraffic.company2.com) as an iframe into the shared internaltraffic.ourgroupcompany.com. You could even set each iframe to be hidden with CSS. Or…
      B) Use an HTML img tag that calls a pixel from each of the individual companies servers. You would need to set up a corresponding script (PHP, NodeJS, whatever their server is using) to actually generate the response with the set-cookies header. Option A is considerably easier.

      I hope this was what you were looking for. Feel free to email me if you need a more detailed solution but don’t want to share details publicly.

      – Joshua

  2. Juan says:

    Hi Joshua, thanks a lot for all the effort to explain us how to implement this solution. Thus, I want to know if you can help me out with a problem I face after applying the cookie through Google Tag Manager. After a user lands with the url https://www.example.com/?block_internal_traffic=true , the search bar on our site doesn’t works; it seems the javascript code block the execution of other script.

    Would you point me to the direction to learn how to fix this? Thanks a lot! I know you should be very busy. Blessings.

    1. joshuatz says:

      Hi Juan,

      I’d be happy to give some pointers. None of the code I provided should have that effect on its own, but stopping GA from loading can cause issues if someone wrote Javascript that assumes that it is there. I took a look at your website, at least what I’m guessing it is based on your email address (don’t worry, only I can see that as an admin), and my assumption seems to hold true. There is some code that fires on the search bar “enter” action, and part of the code tries to use the “window.ga” global, which is normally provided by GA loading. Since GA is not there after blocking it for internal employees, the code fails, with “ReferenceError: ga is not defined”.

      There are a few easy solutions here. If you have control over the site’s code, replace if (ga) {...} with if (typeof(ga)!=='undefined'){...}. If you don’t have control over that code and can only deploy snippets from within GTM, try adding this as a custom HTML tag: <script>window.ga = typeof(window.ga)!=='undefined' ? window.ga : function(){};</script>. That will essentially create window.ga unless it already exists.

      Finally, I have bad news, which is that since it is not my code doing this and actually just your own site’s code erroring out when GA is not loaded… your site’s search bar is completely broken for users with popular ad blockers. Just another reason to fix this issue!

      Hope that helped. Feel free to follow up if you need additional help (either here in the comments or via email).

      – Joshua

  3. john bernal says:

    Hi Joshua, thanks for this fantastic work. What if the Google Analytics and the Facebook Pixel is harcoded in the server and it is not installed through Google Tag Manager? How we could block the internal traffic with GTM?

    1. joshuatz says:

      Hi John,

      Sorry about the delay in responding; I’m working through a backlog of comments right now. Answering this in case you, or anyone else, is still searching for the answer.

      If the GA or FB Pixel is hardcoded in the server’s response, then unfortunately, the best solution is to actually change the code that is running on the server itself. I talk about that in the “Without GTM” section of this post.

Leave a Reply

Your email address will not be published.