how to get the Google analytics client ID

Although the author explicitly said he is using Javascript, others (like me) may be searching for a way to get this information from the server-side, like PHP.

For both: GA4 and UA, I found that you can easily check for the _ga cookie, which looks like:

_ga=GA1.3.475128143.1522318100

In the exemple above, the user id is "475128143.1522318100".

So, in PHP I can fetch it quickly as:

$gaUserId = preg_replace("/^.+\.(.+?\..+?)$/", "\\1", @$_COOKIE['_ga']);

You can also use Javascript to retrieve the cookie in a single line, without using ga() functions:

var gaUserId = document.cookie.match(/_ga=(.+?);/)[1].split('.').slice(-2).join(".")

This is working for me.


Google does have some documentation on getting the client id.

Looks like this:

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

I've used this before, too:

ga.getAll()[0].get('clientId');

EDIT: If you have more than one tracker on the page, it may be probable that at index 0 there is not the one you want, so an alternative function should be the following:

function() {
  try {
    var trackers = ga.getAll();
    var i, len;
    for (i = 0, len = trackers.length; i < len; i += 1) {
      if (trackers[i].get('trackingId') === "ID-PROPERTY") {
        return trackers[i].get('clientId');
      }
    }
  } catch(e) {}  
  return 'false';
}

where ID-PROPERTY is the id of your Property (i.e. UA-XXXXX-XX).