Getting client ID with gtag.js

There is an undocumented way to get the clientid into GA:

gtag('config', 'UA-12345-1', {
  'custom_map': {
    'dimensionX': 'clientId'
  }
});

Obviously they wanted to provide a more convenient way to get the value (you provide literally the string 'clientId' which is then resolved into the proper value).

This was worked out by a guy named Yamata Ryoda and at length documented in an article by Simo Ahava. I admit I haven't tested it myself yet.


The accepted answer does not work anymore (at least for GA4). The correct, up to date way of doing this is:

gtag('get', 'YOUR_MEASUREMENT_ID', 'client_id', (client_id) => {
    // do something with client_id
})

See the documentation for get in the official Gtag.js docs.


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