Sure, here is the HTML code for the requested blog post:
Preventing Google Tag Manager from firing tags on localhost is a common requirement for developers and QA engineers. This can be achieved through a few elegant solutions.
Method 1: Using a Custom JS Variable
This method involves creating a custom JS variable that returns a different GA4 measurement ID based on the hostname.
function getMeasurementId() { const hostname = window.location.hostname; // Set different measurement IDs for different environments if (hostname.includes("localhost") || hostname.includes("127.0.0.1")) { return "TEST_MEASUREMENT_ID"; // Measurement ID for localhost/testing environment } else { return "PROD_MEASUREMENT_ID"; // Measurement ID for production environment } }
In the GA4 configuration tag, reference this custom JS variable as the measurement ID.
Method 2: Using Developer Traffic Filter
Another option is to use the developer traffic filter provided by Google Analytics. This requires adding a custom parameter to every event that should be excluded from production data.
In the GA4 configuration tag, enable the developer traffic filter and specify the custom parameter.
Method 3: Using Built-in Variables
Google Tag Manager provides built-in variables that can be used to check the hostname or environment. For example, the {{hostname}} variable returns the hostname of the current page.
This variable can be used in a conditional statement to control whether a tag should fire or not.
function shouldFireTag() { const hostname = window.location.hostname; // Return true if the hostname is not localhost or 127.0.0.1 return !hostname.includes("localhost") && !hostname.includes("127.0.0.1"); }
In the tag configuration, set the firing condition to the above function.
Conclusion
You can prevent Google Tag Manager from firing tags on localhost using any of the methods mentioned above. Choose the method that best fits your specific requirements and preferences.