Hide

User ID - Web Tracking (analytics.js)

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

Overview

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.

Implementation

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');
    

Example

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 -->
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];
a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');

<?php
// 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');

</script>
<!-- End Google Analytics -->

Where:

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