Stopping Google Analytics From Tracking Development

02/06/2019

I was recently working on my site and noticed I had skewed my Google Analytics while developing. I Googled around and found a nice trick. A simple window.location.hostname and checking if it’s localhost then skipping the Google Analytics script.

This was great but occasionally I use my private network’s IP address to test my site on my iPhone and iPad. The localhost trick doesn’t cover this scenario. I decided to spruce up this JavaScript a bit and have it ignore all private networks; 10.0.0.0/8, 172.16.0.0/12 and 192.168.0.0/16. IP packets addressed from them (private networks) cannot be routed through the public Internet.

Here is the refactored script:

<script>
    const host = window.location.hostname;
    const privateIpRegex = /localhost|(127\.)|(10\.)|(172\.1[6-9]\.)|(172\.2[0-9]\.)|(172\.3[0-1]\.)|(192\.168\.)/g;
    if(host.match(privateIpRegex) === null) {
        // you're on the internet, use google analytics 
        // script here
    }
</script>

This works because match returns null when no matches are found. Now when I browse my site on any private network Google Analytics is not recorded.

If regex isn’t your jam you can simplify and reverse the logic. I redirect all traffic to my apex domain so I don’t account for the www. traffic.

<script>
    const host = window.location.hostname;
    if(host === "mcgilldevtech.com") {
        // you're on the internet, use google analytics 
        // script here
    }
</script>

💥 Problem solved!