google-analyticsgoogle-analytics-4

How to collect user ID's?


I am trying to collect user ID's for google analytics tracking, but am confused on discrepancy between articles I found.

This article (https://www.analyticsmania.com/post/google-analytics-4-user-id/) is saying to use this approach:

window.dataLayer = window.dataLayer || [];
window.dataLayer.push({
  'event' : 'login',
  'userId' : '1234567' //this number must be replaced with an actual User ID
})

While the official docs are saying to do this:

gtag('config', 'TAG_ID', {
  'user_id': 'USER_ID'
});

What is the correct approach to implementing this?


Solution

  • Both are correct, but refer to two different contexts.

    The first, that of the dataLayer, you use it to pass the information to the GTM and send the hit from there.

    The second, that of the gtag, is used if you do not have GTM and therefore have the codes directly on the page.