Migrating your on-page tracking from analytics.js to the new gtag.js — Part 1

Petros Perlepes
Growth Analytics
Published in
6 min readDec 20, 2017

The basics. Steady and simple changes.

Credit goes to Georg_Wietschorke

Recently Google has released for all subscribers a new Analytics tagging library for the web called gtag.js, in place of the 7-year old now analytics.js, which is now the default solution for adding Google Analytics to your site.

First of all what does that mean:

It means that slowly but surely all product updates will start rolling only for the latest tagging library. But, no need to worry just yet as no deprecation flag has been shown for the previous library and gtag.js terms still hold on the beta state. As we see it, it is too early to say that ‘action is required’ and that you should start planning this migration as soon as possible for all your properties.

Nevertheless, for the first part of this series of posts, we will briefly show you some of the most simple and easy-to-make changes you can do on your existing on-page tracking code, in order to make this migration as strainless as possible.

There is also an official guide by Google on this which you might also find really useful.

Starting up

If you just want the standard metrics that Google Analytics collects out-of-the-box and you do not use any custom ways to track user interactions on your site, you can use the default tracking snippet that Google provides in your new properties. If you belong in this category you can go ahead and skip the rest of the article and go on having a wonderful day!

Step 1: Basic snippet

The first thing you have to do and does not need any further explanation is replacing the old tracking snippet with the new one.
The only thing that you need to be a bit careful about is that in the old snippet, the default tracker initialisation along with the pageview hit was in two separate commands.

ga('create', 'GA_TRACKING_ID', 'auto'); // Tracker initialisation
ga('send', 'pageview'); // Pageview hit

but in the new library, you do them both with a single call

gtag('config', 'GA_TRACKING_ID');

For most of you, this does not pose a problem except for the case you do not wish to send an initial pageview directly after your snippet initialisation.
This could be solved as shown below:

gtag('config', 'GA_TRACKING_ID', { 'send_page_view': false });

Step 2: Events

The next step involves the most common scenario where you should send some custom user interactions to Google Analytics. You should already be familiar with the old case where sending events involved a single call to the library.
As an example, suppose we have already implemented a custom Google Analytics event for the case a user clicks the play button on one of our videos embedded on our site.

ga('send', 'event', 'Videos', 'play', 'Fall Campaign');// Or for the more imperative way
ga('send', {
hitType : 'event',
eventCategory : 'Videos',
eventAction : 'play',
eventLabel : 'Fall Campaign'
});

No worries, this is still the case for gtag.js only it looks more like the ‘imperative way’:

gtag('event', 'event_name', {
// Event parameters
parameter_1 : 'value_1',
parameter_2 : 'value_2',
// ...
});

We should note here that the event_name parameter is required and if not overridden in the parameters object, will be used as the event’s action.
So the previous event we defined in the analytics.js could be written as:

// Event action will be 'play' 
gtag('event', 'play', {
event_category : 'Videos',
event_label : 'Fall Campaign'
});
// In the case of an override, event action will be 'play video'
gtag('event', 'play', {
event_category : 'Videos',
event_label : 'Fall Campaign',
event_action : 'play video'
});

A new and really useful concept in this library is that of default event parameters and recommended events.

The default parameters feature allows you to specify events with the minimum amount of parameters possible and the library will supply some default values for the parameters you do not explicitly specify. For the simplest of cases, you can just provide a String that will be used as the action of this event hit. In practise, the code below will result in an event with action ‘login’, category ‘engagement’ and label ‘(not set)’, pretty useful for testing and prototyping in my opinion.

 gtag(‘event’, ‘login’);

The recommended events feature, which also sounds really appealing, provides a more streamlined and easy to understand schema for the most common interactions between a user and an application e.g. sign up, login, social share events etc. Also I am really happy to tell you that this is also true for integrations like Enhanced Ecommerce, making advanced implementations an easier task to tackle. Let’s see an example of how we would send an Enhanced Ecommerce purchase in analytics.js.

ga('require', 'ec');// The addProduct command would be called for as many
// unique products that took part in this transaction.

ga('ec:addProduct', {
//... Product attributes
});
ga('ec:setAction', 'purchase', {
//... Transaction information
});

ga('send', 'pageview'); // The hit to carry the EE purchase.

Below we will see the gtag.js version of the same event. As you will see, there is no ‘require’, no need to add products on separate commands and the carrier event is already built in. Less code definitely means less margin for error and easier on-boarding for someone starting out.

gtag('event', 'purchase', {
//... Transaction information
items: [{
//... Product attributes
},{
//... Next product attributes
}]
});

A complete list of these parameters and the recommended events can be found in the official page section.

Step 3: Custom definitions

To track custom and most of the times, business-specific attributes of a visitor or an interaction with the website, you have definitely used Google Analytic’s custom dimensions and metrics. To send these custom data with analytics.js you would either set the values to be included in every hit on a specific tracker or by adding it on any hit that applies. To reference custom definitions you have to use the unwieldy naming convention of:
definitionType + definitionIndex e.g. dimension3, metric1 and so on.

This convention required you to keep in mind at all times the correlation between the definition’s index and what it really meant for the implementation. Looking at my code a couple of hours later, I need to remind myself what every index stands for and if it is used in the way it is supposed to. That is for any place in the code that these definitions are referenced.

ga('send', 'event', 'Videos', 'play', {
metric3 : 23,
dimension12 : 'holiday collection',
dimension14 : 'consistent'
});

With gtag.js, this is no longer the case. In your ‘config’ command, you are now required to provide a mapping of the definitions you will include, to an understandable name referencing this specific dimension or metric through the rest of your code. This is defined as an attribute called ‘custom_map’ and is implemented as can be seen below.

gtag('config', 'GA_TRACKING_ID', {
custom_map: {
metric3 : 'durationInSeconds',
dimension12 : 'videoCategory',
dimension14 : 'appearenceRate'
});
// Sending custom definitions using keys defined in the custom_map
gtag('event', 'play', {
event_category : 'Videos',
durationInSeconds : 23,
videoCategory : 'holiday collection',
appearenceRate : 'consistent'
});

In every Google Analytics event we would like to send values for our custom definitions, we can now use an understandable attribute name and have a clear view of what can or is included in every hit, just by looking in the mapping object.

Conclusion of Part 1

Speaking from experience, the changes described in this first part, should cover most of your Google Analytics tracking setups. For the rest and more advanced topics, we will continue in the next post!

| Part 2 is coming soon!

For everything related to Google Analytics and the rest Google services, sophisticated implementations, data analysis and insights, check us out and stay vigilant for our next posts. If your case is advertising then definitely check out our product, adaplo.

--

--

Petros Perlepes
Growth Analytics

Front-end engineer@ Clerk; Loves software development books. Building foundations in software architecture.