Excluding Internal Traffic in Google Tag Manager

Excluding Internal Traffic in Google Tag Manager

You've got your Google Tag Manager (GTM) up and running. Now you need to exclude internal traffic from Google Analytics. This post goes through the process of how traffic exclusion could be done on GTM.
An article on LunaMetrics (http://www.lunametrics.com/blog/2014/03/11/goodbye-to-exclude-filters-google-analytics/) describes how the exclusion could be done on the old version of GTM. It was a good starting point for me though.

So what traffic do you want to exclude?

  • If you have a static IP address, you could exclude the traffic by checking the IP address as described in the LunaMetrics article

  • But with the use of various devices for testing and internal users accessing the website from various locations (homes, coffee shops, via mobile networks), keeping track of those IP addresses becomes a nightmare

  • Cookie-based exclusion

  • User-agent exclusion

    • If it's a large corporate entity with managed software, the user agent string of browsers could be changed to include a specific string to identify internal traffic
  • Hostname exclusion

    • In development, hostnames such as emmti.com.local or localhost are used. Even IP addresses (such as 127.0.0.1) are used to access development websites.

In this post, I'm using a cookie-based approach to exclude traffic. But the code examples given below also help in excluding traffic to particular host names. It can be extended further to exclude traffic from certain IP addresses and particular User agent strings.

Let's get to implementing the GTM exclusions.

Code on the Client Website

According to the Tag Manager instructions, the GTM Tag should be placed just after the opening tag to work perfectly.
The code below is an example of how this is implemented in an MVC application.

I've created a partial view GTM.cshtml which includes the following code:

<!-- Google Tag Manager -->
<noscript>
  <iframe src="//www.googletagmanager.com/ns.html?id=GTM-XXXXXX"
height="0" width="0" style="display:none;visibility:hidden">
  </iframe>
</noscript>
<script>
dataLayer = [{'trackThisPage': '@HelperFunctions.TrackThisPage()'}];
(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'//www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-XXXXXX');
</script>
<!-- End Google Tag Manager -->

The GTM.cshtml is rendered in the base layout using @{ Html.RenderPartial("GTM"); } just below the opening body tag. In the above code, I've added a dataLayer variable to assist with excluding any internal traffic. The helper function (in HelperFunctions.cshtml) returns either true or false depending on certain conditions I have set.

@functions {
    public static string TrackThisPage()
    {
        if (Request.QueryString["ignoreGTM"] != null && Request.QueryString["ignoreGTM"] == "false")
        {
            return "true";
        }
        else if ((Request.Cookies["ignorePageViews"] != null && Request.Cookies["ignorePageViews"].Value == "true") ||
            (Request.QueryString["ignoreGTM"] != null && Request.QueryString["ignoreGTM"] == "true") ||
            Request.Path.EndsWith("ignore", StringComparison.InvariantCultureIgnoreCase) ||
            Request.Url.Host.Contains(".local"))
        {
            return "false";
        }

        return "true";
    }
}

In the function TrackThisPage(), I have checked if the current request is sent to an URL ending with ignore or if the hostname contains ".local" or if a cookie is set with ignorePageViews variable. It also checks if ignoreGTM parameter is present and if it's true or false in order to determine if this page is to be tracked.

The function could be extended to include other checks such as IP subnets which are stored as an application configuration value.

I've also got a page localhost/ignore which creates a cookie whenever a user visits it. It's important here that internal staff are asked to visit this page first before browsing the site from any device. This is a one-time step that needs to be done the first time when using a new browser instance or whenever the browsing history has been cleared.

The following code shows a simple implementation where a cookie is set for a period of 10 years.

@{
    Response.Cookies["ignorePageViews"].Value = "true";
    Response.Cookies["ignorePageViews"].Expires = DateTime.Now.AddYears(10);
    <i>Cookie set to ignore page views.</i>
}

Whenever any page on the website is requested the following HTML will be returned if the page is not to be tracked.

<!-- Google Tag Manager -->
<noscript><iframe src="//www.googletagmanager.com/ns.html?id=GTM-XXXXXX"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<script>dataLayer = [{'trackThisPage': 'false'}];
(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'//www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-XXXXXX');</script>
<!-- End Google Tag Manager -->

If the page is to be tracked, the following HTML will be returned. Note the difference in the fourth line of code.

<!-- Google Tag Manager -->
<noscript><iframe src="//www.googletagmanager.com/ns.html?id=GTM-XXXXXX"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<script>dataLayer = [{'trackThisPage': 'true'}];
(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'//www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-XXXXXX');</script>
<!-- End Google Tag Manager -->

Code implementation on the client website is as simple as that.

Google Tag Manager Setup

The next step in the process is making sure that the Google Analytics tag does not fire when the dataLayer variable trackThisPage is false.
In order to do this head over to the GTM dashboard at http://tagmanager.google.com/

First off a new variable needs to be created. This can be done by following the steps below:

  1. Go to the particular container tracking your website and select Variables from the left-hand side menu
  2. Under the User Defined Variables section click on New
  3. Change the following values as given in the screen grab below

    • Variable Name: Track this page
    • Choose Type: Data Layer Variable
    • Data Layer Variable Name: trackThisPage
    • Data Layer Version: Version 2 (make no changes)
  4. Save the variable

Creating a new variable

Creating a new variable

Once the variable is created, it needs to be associated with a Trigger to work.

  1. Select Triggers from the left-hand side menu
  2. Click on New
  3. Change the following values as given in the screen grab below

    • Trigger Name: Don't track internal
    • Choose Event: Page View
    • Trigger Type: Page View
    • Fire On: Some Page Views
      • Conditions: Track this page equals false
  4. Save Trigger

Trigger not to track internal

Trigger not to track internal

Once the trigger is created, it should be associated with a new or existing tag. The instructions below are for creating a new tag.

  1. Select Tags from the left-hand side menu
  2. Click on New
  3. Change the following values as given in the screen grab below

    • Tag Name: External Only Traffic
    • Choose Product: Google Analytics
    • Choose a Tag Type: Universal Analytics
    • Configure Tag:
      • Tracking ID: Enter your unique tracking ID here
      • Track Type: Pageview
    • Fire On: All Pages
      • Add an exclusion: Choose "Don't track internal"
  4. Save the Tag

External only traffic Tag

External only traffic Tag

Test exclusions

Test your implementation by either sending ?ignoreGTM=false or ?ignoreGTM=true as a query string parameter to your pages.
When ?ignoreGTM=true, the Google Analytics tag should not fire. When ?ignoreGTM=false, the Analytics tag should fire and record your page view.

You can easily verify this by using the Tag Assistant (by Google) extension in Chrome. The Tag Manager preview & debug mode will also allow you to verify if this works as intended before your container is pushed live.

That's it for this post. Let me know how you go about implementing exclusions on your client websites.


This article was originally written on Google's Blogger platform and ported to Hashnode on 17 Sep 2022.