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
In this case we have two different tag configurations for production as well as development setting, say
<script> console.log('Development') </script>
<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 Navigation
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.