Tracking Single Page Web Apps with Google Tag Manager & Analytics
There’s quite a bit of outdated information about how to integrate Google Tag Manager (GTM) and Google Analytics into a single page application. The goal here is to keep your application blissfully unaware of GTM, and, fortunately it’s pretty easy to do.
So first off, fire up GTM and select your container or create one.
Just drop the GTM code snippet into your page right after the opening <body> tag as instructed. If you don’t have this code snippet, find it on the Admin > Container > Install Google Tag Manager screen.
Back in GTM, click on the trigger area and select New Trigger.
Give the trigger whatever name you like and select History Change for the event. History change will fire whenever something like Backbone or React Router uses the history API. We’ll use this trigger later to fire Google Analytics.
From here you can select whether it should fire on all history changes or only some.
A great example of only firing on some history changes would be restricting the trigger to fire only on your application’s production server.
After you’re done, save the trigger.
First off, you’ll need to set up an analytics account and grab it’s UA ID. Hit the new tag button on the container overview (or click into tags and hit the new button).
Select Google Analytics as the tag product and universal analytics as the tag type.
Configure the tag with your analytics account’s UA code (usually it looks something like UA-XXXXXXXX-X) and track page views.
Now we get to the reason why we created the trigger. Under fire on select all pages and then click more.
Clicking more will pop open a dialog with all your custom triggers. Select the history change trigger we created in step 2 above and hit save.
There’s no need for a special library or ugly hacks like eval’ing the GTM code in a wrapper react component (something I saw preparing for this tutorial). Most importantly, your application can remain unaware of the GTM or analytics code.
Interested in working with us? See our open engineering roles here.
Stay in touch
Subscribe to our newsletter
2 MINUTES READ | February 4, 2020
2 MINUTES READ | December 9, 2016