Search code examples
google-analyticsgoogle-tag-manager

How to update Google Analytics user id using GTM?


Using gtag.js I can change the user id in this way:

gtag('config', 'G-XXXXXX', {
  'user_id': '12345'
});

Using GTM instead, how can I change the user id used by Google Analytics?

What I currently did was to add a variable in GTM, and insert it as the value of the user property "user_id" in the TAG of analytics.

The problem is that in this way Analytics is initialized with the initial user_id value. In my case though, using it on a single page application, the user id can change after having already initialized GTM and so Analytics, and dataLayer.push({ 'user_id': 'xxx' }) has no effect on Analytics.


Solution

  • dataLayer.push({ 'user_id': 'xxx' }) by itself might not have an effect, but that is because you do not tell GTM to update it's internal state.

    GTM overwrites the "push" method of the datalayer array with some custom code that, among other things, scans the pushed objects for a key with the reserved name "event". Only if it finds that key, the data that has been pushed to the datalayer is actually evaluated, and the variables configured in the "variables" tab of the GTM interface assume a new value, if indeed a new value for them has been set in newly added datalayer object. The "event" key also allows you to create a trigger to fire tags with the updated values.

    So if you do

    dataLayer.push(
    { 
      'user_id': 'xxx',
      'event': 'updateUserId' 
    }); 
    

    your user_id variable in GTM will be assigned the new value, and you can create a "custom event trigger with the event name "updateUserId". You can e.g. send a request to Google Analytics with the new value (I have to say that the variable name "user_id" is a little unhappy for something that you obviously expect to change a lot).

    The value is also updated if after the push follows an automatic event, e.g. a valid click trigger or similar.