User ID - Web Tracking (analytics.js)

This guide describes how to implement User ID using analytics.js.


User ID enables the analysis of groups of sessions, across devices, using a unique, persistent, and non-personally identifiable ID string representing a user. To learn why you should implement the User ID, see Benefits of using the User ID feature.


To implement the User ID on the web:

  1. Provide your own unique, persistent, and non-personally identifiable string ID to represent each signed-in user. This ID is most often provided by an authentication system.
  2. Set the User ID on the tracker:
    ga('create', 'UA-XXXX-Y', { 'userId': 'USER_ID' });
    ga('send', 'pageview');


A typical authentication system should be able to provide a unique, non-personally identifiable and persistent ID, for a signed in user. This ID can be sent to Google Analytics when a user signs into your website.

For a website that implements such an authentication system and uses PHP, the standard analytics.js code snippet could be dynamically updated to set the userId when a suitable ID for the user is available, as in this example:

<!-- Google Analytics -->
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),

// New Google Analytics code to set User ID.
// $userId is a unique, persistent, and non-personally identifiable string ID.
if (isset($userId)) {
  $gacode = "ga('create', 'UA-XXXX-Y', { 'userId': '%s' });";
  echo sprintf($gacode, $userId);
} else {
  $gacode = "ga('create', 'UA-XXXX-Y');";
  echo sprintf($gacode);

ga('send', 'pageview');

<!-- End Google Analytics -->


  • $userId is a variable set by the server only if the user has successfully authenticated to your service.