Setting A Development And Production Environment in Google Tag Manager (GTM)

Google Tag Manager (GTM) is the tool of choice today for adding JS snippets in web apps. GTM covers most use cases we can think of, is free and with time you can certainly get a hang of it.

Often we want to separate the production environment from the development environment in GTM. This could be for several reasons like

  • Do not want data from the development environment to corrupt analytics of production environment.
  • Snippet runs in more verbose logging mode in while in development
  • Snippet is in testing and only after a successful run will move to production.
Creating Triggers in GTM

In case you are quite familiar with GTM, you know that adding a tag (A JS snippet is a kind of a tag in GTM) requires two things

  • Tag Configuration
  • Trigger

In this case we have two different tag configurations for production as well as development setting, say

<script>
console.log('Development')
</script>

and

<script>
console.log('Production')
</script>

We want to trigger the first in the development environment and the other in the production environment.

We are going to assume your development environment runs on a URL like localhost and production app is on a URL like mywebsite.com.

Now we just need to setup different triggers for these environments using the triggers in GTM.

Click on the Triggers tab in left nav

This should list down all your existing triggers.

Click on New button

Name the trigger 'Development All Pages'

Click on Trigger Configuration and choose 'Page View'

Change type to 'Some Page Views' and change condition to 'Page Hostname' 'contains' 'localhost'

These conditions are very useful, you could have also used the part of the URL after the host name like section1 in http://mywebsite.com/section1 to target a trigger using the Page URL value. This would ensure the snippet would only run on section1 pages.

Interestingly, you could use the 'Referrer' value to ensure a snippet only runs when a user lands from a certain referrer. For example, if you want to run a script only when people land from Facebook, you could use this with 'Referrer' 'contains' 'facebook.com'. Neat.

Repeat the same steps as above to create a new trigger named 'Production All Pages'

The condition in this tag should be 'Page Hostname' 'contains' 'mywebsite.com'

Use It In Creating a New Tag

And that's it, you now have two environments ready which can be used for different snippets to ensure they run in production or in development mode only. Hope you find this useful.