How to get clientId with custom dimensions in google analytics

1.1k views Asked by At

I replace my current default "universal google analytics" code to custom JavaScript to get the clientId but I got string value while using (Like: clientId).

GA code:

ga('create', 'UA-xxxxxx-x', 'auto'); ga(function(tracker){ var clientId = tracker.get('clientId'); }); ga('set', 'dimension1', clientId); ga('send', 'pageview');

2

There are 2 answers

3
Дмитро Булах On BEST ANSWER

This would hardly work since you're assigning cilentID value to the function scoped variable that can not be seen outside the readyCallback function. Consider the following code:

  ga('create', 'UA-XXXXX', 'auto');
  ga(function(tracker) {
    var cid = tracker.get('clientId');
    tracker.set('dimension1', cid); // ID is to be set right after the traker is available
  });
  ga('send', 'pageview');
0
Michael Frost Billing On

UPDATE: clientId is available through the API as ga:clientId

No need to set clientId (or userId) in a custom dimension anymore.

Note to anyone using the Universal Analytics User ID feature The values returned in ga:clientId is actually the userId Even more interessting. (As of time of writing) GA fails if you request clientId from a User ID view. So you should use a non-User ID view to get the User ID. :)