Ognjen Regoje bio photo

Ognjen Regoje
But you can call me Oggy


I make things that run on the web (mostly).
More ABOUT me and my PROJECTS.

me@ognjen.io LinkedIn

Two tips for quick migration from analytics.js to gtag.js

#technical

Google has instructions on how to migrate from analytics.js to gtag.js with the steps being straight-forward.

While doing this, two things helped me:

1. Set up a GAID constant

So, the tracking code would look like this:

  <script async src="https://www.googletagmanager.com/gtag/js?id=UA-..."></script>
  <script>
    window.dataLayer = window.dataLayer || [];
    function gtag(){dataLayer.push(arguments);}
    gtag('js', new Date());

    gtag('config', '...');
    GAID = "...";
  </script>

This helps use it in code that manually triggers pageview tracking or ecomm.

For example, pageview tracking in code can now be triggered by:

gtag('config', GAID);

2. Use regular expressions to upgrade old events

First, replace this:

ga\(['"]send['"], ['"]event['"], ['"](.+)['"], (.+)\)

with this:

gtag('event', '$1', {event_category: '$1', event_label: $2})

And then

ga\(['"]send['"], ['"]event['"], ['"](.+)['"]\)

with this:

gtag('event', '$1', {event_category: '$1'})

It’s important to do it in order so that labels and categories can be picked up correctly.