How to disable Google Analytics on localhost
Every now and then, I do major website updates locally. And each time, I need to remove the GTM code on the local website version and then put it back on the live version. But sometimes I forget to do so and get this in my GA4 report:

…or on my wife’s website:

Squarespace users might see a similar issue:

These are all internal sessions that you do not want in your Google Analytics reports. Although, you can (and should) use GA4 filters, but in this post I’m sharing a different, more radical approach how to completely disable Google Analytics on any non-live domain.
In your Google Tag Manager container, your GA4 tag is probably set up with either a hardcoded stream ID or a constant variable:

Now, we are going to change that. Instead of a constant variable that stores the ID, we will be using a lookup table variable:

In case you’re unfamiliar with how lookup table variables work:
- it takes the page hostname (the domain where the GTM code is fired)
- compares it against the
Inputvalue - if there’s a match, the
Outputvalue becomes the variable’s value - if there’s no match, it falls back to default value (
undefined, in this case)
In this way, our LT variable will return the correct ID when the GA4 tag fires on romangr.com, but when it fires on another domain (romangr.local, localhost, etc.), it will return undefined.
Finally, we’ll change the tag ID in our Google Analytics tag with the new LT – GA4 variable:

Now, if we debug the setup, our GA4 tag will fail on localhost (because of the undefined GA4 tag ID), and no data will be captured by Google Analytics:

At the same time, everything will be working on the live domain:

Final words
This effectively kills GA tracking for your dev environment — no hits will go through from localhost or a non-live domain. You could also use GA4 filters to accomplish the same thing, but that’s a little more tedious to configure.
One important caveat though: this approach will also block tracking for visits you may want to count, such as when your site is auto-translated by Google Translate:

To avoid this, review the hostnames in your GA reports and update your lookup table variable accordingly to include any domains you want to track.

Hi! I’m Roman, a Google Ads freelancer. This is my website where I share all kinds of things I find interesting related to Google Ads, Google Tag Manager, and Google Analytics. I am also available for hire, so if you need help with any of these, feel free to get in touch.