I’m an active member of the LinkedIn Google Analytics group and a fellow group member, Ruth, recently asked how to set the unique Google Analytics user ID from the GA cookie as a custom variable. I responded with the JavaScript code that would do this in classic Google Analytics. Before long Ruth asked how to do this in Universal Analytics and finally in Google Tag Manager. I thought it would make sense to post it here as well.
First off, why would you want to do this? Setting a custom variable with the unique user ID from GA will allow you track individual user behavior in reports by building a custom segment against a particular user ID. You can also use this user ID to connect non-authenticated user behavior (before a user creates an account on your site) to an authenticated user (after they create an account). This can be immensely helpful in attribution.
How does this code work?
The code snippets below all perform the same basic steps:
- Attempt to read the __utma cookie value. (Read about the GA cookies in depth here)
- Make sure the cookie has data in it (not undefined).
- Split the cookie values into an array based on the dot delimiter.
- Extract the appropriate User ID from the array (2nd slot in classic GA, 3rd slot in Universal Analytics). Note that JavaScript arrays are zero-based so the ‘cookieValues[1]’ below is really accessing the 2nd item of the array.
- Assign this User ID as a visitor scope custom variable in GA or as a custom dimension in Universal Analytics.
- Fires an event with a category of ‘Custom Variables’ and action of ‘Set UserId’ with non-interaction set to true.
Before getting into the code itself, a few assumptions are in order:
- You’re only firing one GA Profile ID on the site.
- You don’t already have a custom variable (custom dimension in Universal) in the first variable slot. If you do, just modify the slot # to the first available slot.
This code needs to be implemented on your site after your Google Analytics code has had a chance to run. This ensures that the __utma cookie that contains this unique user ID has been set on the user’s browser. If you have your GA code running in the <head> section of your site, this code should be implemented near the closing </body> tag.
Here’s the script to set the GA user ID as a custom variable in the asynchronous version of classic GA:
Important Note: If you plan to upgrade to Universal Analytics in the near future, the functionality below will no longer work when you switch to Universal Analytics. If you have not already implemented this User ID tracking, I would suggest implementing Universal Analytics first and then implementing the Universal Analytics logic in the 2nd script section below.
<script type="text/javascript"> function readCookie(name) { name += '='; for (var ca = document.cookie.split(/;\s*/), i = ca.length - 1; i >= 0; i--) if (!ca[i].indexOf(name)) return ca[i].replace(name, ''); } var gaUserCookie = readCookie("__utma"); if (gaUserCookie != undefined) { var cookieValues = gaUserCookie.split('.'); if (cookieValues.length > 1) { var userId = cookieValues[1]; try { _gaq.push(['_setCustomVar',1,'gaUserId',userId,1]); _gaq.push(['_trackEvent', 'Custom Variables', 'Set UserId','',0,true]); } catch(e) {} } } </script>
If you do need to change the variable slot in the code above, change the blue value below to a number between 2 and 5 in the script above.
_gaq.push(['_setCustomVar',1,'gaUserId',userId,1]);
Universal Analytics:
In Universal Analytics, you are setting a custom dimension instead of a custom variable. You’ll need to add the custom dimension in the Universal Analytics profile setup prior to implementing the code below. If you already have a custom dimension in the first dimension slot (dimension1), you’ll need to change the ‘dimension1’ value in the code below to the appropriate ‘dimensionX’ value.
<script type="text/javascript"> function readCookie(name) { name += '='; for (var ca = document.cookie.split(/;\s*/), i = ca.length - 1; i >= 0; i--) if (!ca[i].indexOf(name)) return ca[i].replace(name, ''); } var gaUserCookie = readCookie("_ga"); if (gaUserCookie != undefined) { var cookieValues = gaUserCookie.split('.'); if (cookieValues.length > 2 ) { var userId = cookieValues[2]; try { ga('set', 'dimension1', userId); ga('send', 'event', 'Custom Variables', 'Set UserId', {'nonInteraction': 1}); } catch(e) {} } } </script>
In Google Tag Manager with Universal Analytics:
You can implement the script below as a ‘Custom HTML’ tag firing on all pages (or just your landing pages, if preferred). For the script below to work, you’ll also need to create an additional tag in GTM:
- Create a data layer macro to hold the userId value.
- Add an Analytics tag to set the custom dimension in Universal Analytics passing in the userId macro you created above. You can use a tag type of event to do this. You’ll need to populate the event category and event action. Be sure to set the non-interaction to ‘True’ to avoid artificially decreasing bounce rate.
- Set a firing rule for the tag of: {{event}} equals setUserId
<script type="text/javascript"> function readCookie(name) { name += '='; for (var ca = document.cookie.split(/;\s*/), i = ca.length - 1; i >= 0; i--) if (!ca[i].indexOf(name)) return ca[i].replace(name, ''); } var gaUserCookie = readCookie("_ga"); if (gaUserCookie != undefined) { var cookieValues = gaUserCookie.split('.'); if (cookieValues.length > 2 ) { var userId = cookieValues[2]; dataLayer.push({'event':'setUserId', 'userId': userId}); } } </script>
Have any implementation questions or comments? Get in touch with me by leaving a comment below or on Google+.
Comments on this entry are closed.
Pingback: Digital Analytics Week In Review - 21 March 2014 - Data Runs Deep()
Pingback: Google Tag Manager: attivare UserId anche senza login - MEC Italy - Digital Analytics Blog()