authenticationgoogle-analytics

Google Analytics Setup User ID


So I've set up Google Analytics and everything is well and working. Now I want to track user ID. We have a system where when users are logged in they are assigned a unique identifier number. For example, we'll call this unique identifier number "identifierNumber" however when I add a new view and enable UserID in Google Analytics my user's number goes to zero. This is how I have it set up in my code between the head. I want to mention that if I go to my original view without user Id it still shows users and realtime. As soon as I switch views to the user ID view no data shows. I've let the code sit and refresh as well. Thank you.

<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-#########-1"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'UA-#########-1');
  ga('set', 'userId', '${identifierNumber}'); // Set the user ID using signed-in user_id.
</script>

Solution

  • You are mixing gtag code and Universal Analytics code (ga).

    To implement the User ID with gtag.js, update the config for your property to set the User ID:

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

    https://developers.google.com/analytics/devguides/collection/gtagjs/cookies-user-id#set_user_id