javascriptgoogle-analyticsanalyticsanalytics.jsgtag.js

Getting client ID with gtag.js


Google released gtag.js a couple of months ago as the new way of tracking with Google Analytics, eventually replacing analytics.js as far as I understood. gtag.js is the default when setting up a new Google Analytics account, so the code snippet went from this:

<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

  ga('create', 'UA-12345678-1', 'auto');
  ga('send', 'pageview');
</script>

to this:

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

  gtag('config', 'UA-123456789-1');
</script>

What I need to do, is to get the client ID with gtag.js. With the old script, I could do as follows.

ga(function(tracker) {
  let clientId = tracker.get('clientId');
});

By the looks of it, gtag.js loads the same analytics.js script through Google Tag Manager, because the ga variable is indeed available. However, there is some difference because the tracker parameter is undefined when the callback is invoked, because gtag.js does not use trackers, so this approach clear won't work.

I looked through the documentation for gtag.js, but I was not able to find any information on how to obtain the client ID. The documentation for analytics.js states not to access the cookie directly to obtain the client ID, which makes sense. But is there any way to get it through the JavaScript API with gtag.js, or do I have to resort to reading the cookie for now?


Solution

  • Whlie tracker id property is unavailable it's still a proper ga tracker at least at the time being. so the following would work to get a clientId:

    ga.getAll().forEach( (tracker) => {
      var id = tracker.get('clientId'); console.log(id)
    })
    

    After accessing the ga tracker with ga.getAll() you can set up the 'customTask' that would assign clientId to custom dimension of your choice. Look at Simo's guide here