49

When you are creating a new instance of analytics.js by running

ga('create', 'UA-XXXXXXX-Y', {'cookieDomain': 'none'});

GA creates a unique client Id. I want to fetch this id and use it for my own purposes, but I can find only setter for this parameter but can't find any getter method to get it.

GA send it later in a parameter called &cid=123123.232323

Does anyone knows how do I get it?

user2979757
  • 783
  • 2
  • 8
  • 12
  • possible duplicate of [What is the client ID when sending tracking data to google analytics via the measurement protocol?](http://stackoverflow.com/questions/14227331/what-is-the-client-id-when-sending-tracking-data-to-google-analytics-via-the-mea) – Stephan Weinhold May 06 '15 at 09:39

5 Answers5

103

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).

Michele Pisani
  • 13,567
  • 3
  • 25
  • 42
Blexy
  • 9,573
  • 6
  • 42
  • 55
  • So I'm assuming we need to add some kind of analytics JS library to our web project? Can we then send this value to the back end for Java integration in this Java code? https://cloud.google.com/appengine/docs/google-analytics – fIwJlxSzApHEZIl Nov 12 '14 at 20:22
  • 3
    Hi @Blexy, any idea why the GA documentation function doesn't work? Using getAll does thankfully. Just curious why the other method doesn't return anything though. – Doug Fir Apr 10 '15 at 13:42
  • 3
    @DougFirr seems like you are using **synchronous** syntax when calling _getAll_ and analytics library has not being initialized and processed the queue yet. So there is no tracker at index 0 at that time. Try using **async** syntax like `ga(function(tracker) { /* Your getter code */});` – Artem Platonov Jul 30 '15 at 15:34
  • 2
    I'm interested for **synchronous code**. Is `ga.getAll()[0].get('clientId');` documented and assured to be valid in a few months/years or something that could be modified soon? – Basj Aug 29 '17 at 15:32
  • Any reasons why it is not working for me ?! I used this script exactly. – B4b4j1 Dec 13 '18 at 15:47
35

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.

BNazaruk
  • 6,300
  • 3
  • 19
  • 33
Alexandre T.
  • 3,581
  • 1
  • 18
  • 11
  • 2
    downvoted, sorry! google analytics documentation specifically says _not_ to access their cookie via browser API as their cookie may change. instead, use the provided-for APIs to get the client ID. – Benjamin Hoffman Aug 23 '18 at 20:26
  • @BenjaminHoffman Can you please share the reference for this? – raja pateriya Aug 16 '19 at 11:51
  • it's all over their documentation. but here is just one instance. https://developers.google.com/analytics/devguides/collection/analyticsjs/cookies-user-id#getting_the_client_id_from_the_cookie – Benjamin Hoffman Aug 25 '19 at 02:41
  • @BenjaminHoffman Their documentation only shows the Javascript version. – Brandon Aug 28 '19 at 16:52
  • 9
    @BenjaminHoffman sometimes this isn't a practical option and a solution similar to the one shown in the answer above is useful – nh43de Dec 11 '19 at 21:29
  • From Google documentation: "You should not directly access the cookie analytics.js sets, as the cookie format might change in the future. Instead, developers should use the readyCallback to wait until analytics.js is loaded, and then get the clientId value stored on the tracker." - https://developers.google.com/analytics/devguides/collection/analyticsjs/cookies-user-id#getClientId – SIRHAMY Jul 23 '22 at 16:15
6

First create the Google Analytics ga object to create a tracker object, by passing it a "Ready callback" function, then use the tracker to call other methods.

The ga() command queue provides an interface for doing almost everything you need to do with the analytics.js library.

"function(tracker)" is a callback function to be invoked when the analytics library is fully loaded and ready to be interacted with. The function is invoked with the default tracker object as it first argument. If no default tracker has been created, the first argument is/will return undefined.

Note: when the callback function is invoked, all ga object methods are available for use. Including the one you want tracker.get('clientId')

Replace the UA-XXXXX-Y in the code below with your UA code from Google Analytics.

// Queues a tracker object for creation.
ga('create', 'UA-XXXXX-Y', 'auto');

// Once the tracker has been created, log the
// client ID to the console.
ga(function(tracker) {
  console.log(tracker.get('clientId'));
  /* Your other code here */
});

Alternatively for lines 1 & 2, use the code below to create a named tracker.

// Queues a named tracker object for creation.
ga('create', 'UA-XXXXX-Y', 'auto', 'myTracker');

Official Google documentation: Cookies and User Identification

SIRHAMY
  • 157
  • 1
  • 9
Craig Gjerdingen
  • 1,844
  • 1
  • 21
  • 21
  • I think your first code block has one too many }'s (there's one on the same line as the "other code here" comment and one on the next line). – penitent_tangent Apr 07 '17 at 01:04
0

If you are using Google Tag Manager, you can use User-Defined Variable -> Variable type: "1st-Party Cookie" -> Cookie Name = _ga. Let's call it "GA Cookie". It will store value like this GA.1.1.123.123.

To cut the "GA.1.1", make another User-Defined Variable -> Variable Type: "Custom JavaScript" and write a simple JS function:

function() {
    var pattern = "GA1.1.";
    var id = {{GA Cookie}}.substr(pattern.length);
    return id;
}

It is not always "GA1.1", but still it has 5 signs. You can use different variable like var length = 5, but as for me, it looks like a kind of magic number.

0
ga((tracker) => {
  console.log(tracker.get('trackingId'));
});
Demven Weir
  • 807
  • 7
  • 6