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:

  1. Attempt to read the __utma cookie value.  (Read about the GA cookies in depth here)
  2. Make sure the cookie has data in it (not undefined).
  3. Split the cookie values into an array based on the dot delimiter.
  4. 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.
  5. Assign this User ID as a visitor scope custom variable in GA or as a custom dimension in Universal Analytics.
  6. 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:

  1. You’re only firing one GA Profile ID on the site.
  2. 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:

  1. Create a data layer macro to hold the userId value.
  2. 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.
  3. 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+.

{ 3 comments }

As a developer, client-side errors can be a real pain.  Developers usually do a good job logging server-side application errors, but often times ignore client-side errors.  As the web evolves, we’re seeing more and more single page applications that are heavily reliant on client-side service calls using technologies like AJAX.  This makes sites heavily dependent on JavaScript.

Google Tag Manager just released a new listener tag type, the ‘JavaScript Error Listener’.  The JavaScript Error Listener will allow you to capture client-side errors that would otherwise be invisible to the server and log them to Google Analytics or another service of your own choosing.  For my example, I’ll be logging JavaScript errors to Google Analytics as an event with the error itself as the event label.  Bear in mind that the maximum size for an event label is 500 Bytes which will let us store 500 characters.

The first thing we need to do is add the JavaScript Error Listener to our tag container:

Screen Shot 2014-03-13 at 8.56.27 PM

Now that we have the JavaScript Error Listener in place with a firing rule of ‘All Pages’, I’m going to publish a debug version of the container so I can inspect the gtm.PageError object that will be pushed to the data layer when a JavaScript error occurs.  To do this, I’ve created a simple test page with a JavaScript error that results when the link is clicked because no function with that name exists.  Once I opened the test page:

  1. I opened the Chrome developer tools
  2. Clicked the link on the test page to cause the JavaScript error
  3. Typed ‘dataLayer’ in the console to inspect the dataLayer and expanded the last item (most recently added) to see the contents of the gtm.pageError event.

Screen Shot 2014-03-13 at 9.08.34 PM

Now I can see that the ‘gtm.errorMessage’ field is populated with some useful information about the uncaught exception.  To log this to Google Analytics as an event, I’ll need to add a new tag in GTM with a firing rule of {{event}} equals gtm.pageError and create a new macro for the gtm.errorMessage object.

Here’s the rule to fire the GA event when an error occurs:

Screen Shot 2014-03-13 at 9.21.06 PM

The macro to pull in the JavaScript error message:

Screen Shot 2014-03-13 at 9.21.52 PM

and finally the GA event tag itself:

Screen Shot 2014-03-13 at 9.22.45 PM

Now when a JavaScript error occurs on your site, you’ll be able to see them in your Google Analytics event reports:

Screen Shot 2014-03-13 at 9.28.11 PM

To take this a step further, I’d suggest setting up custom alerts to send an email when JavaScript errors occur on your site.

Questions or comments?  Get in touch with me on Google+ or leave a comment below.

{ 2 comments }

Justin Cutroni, Analytics Evangelist at Google

Last night, I had the pleasure of attending our local Web Analytics Wednesday meeting (yes, I know, on a Tuesday) at ThoughtFaucet in Burlington, VT. As Vermonters working in the web analytics space, we’re fortunate to have Justin Cutroni, Analytics Evangelist for Google, right here in our backyard. The format for the meeting was open Q&A. We started off with a few general questions, but before long Justin was diving deep and sharing some nuggets that I’ll share with you:

  1. Universal Analytics is the future of Google Analytics.  Universal Analytics will be out of beta very, very soon.  Classic Google Analytics won’t go away, but all future enhancements will only be released to Universal Analytics.  Justin encouraged planning for the migration to Universal Analytics now – especially for larger sites with more time between releases.  Justin also recommends using Google Tag Manager to assist with this implementation.
  2. Remarketing is currently the only feature in classic Google Analytics that is not yet available in Universal Analytics.
  3. Remember those cross device measurement reports that Google announced at I/O back in May of last year?   Justin indicated we can expect them “very, very soon.” This will allow you to measure multi-device paths to conversion.  For instance, you’ll be able to track a user as they start building their cart on their mobile phone through to checkout on their laptop.  Keep in mind that in order for these reports to work, you’ll need to use Universal Analytics and provide  a ‘UID’ (User ID) to connect the dots between any given user’s desktop, phone and tablet.
  4. There will always be a free version of Google Analytics.  With the launch of Google Analytics Premium, this has been a common concern.  With so many of us relying on a free tool, it’s good to know that it’s here to stay.
  5. For the Google Analytics API, Justin said that his team’s goal is to make every report, metric and dimension available in the Web UI through the API.
  6. Industry benchmarks will be available again soon in a different more useful format.  Justin said they decided to remove them because they led to more confusion than helpful insights.
  7. Google Tag Manager (GTM) will soon undergo a big UI refresh to help management of tag containers with a large number of tags, rules, and macros.  GTM will also soon allow you to set a firing order for tags in a particular container.  This is a big deal as tags currently fire in random order unless you use this workaround.

Google Analytics Universal Analytics

Justin also delved into a number of other topics such as building a measurement plan, performing an analytics audit, as well as big data and the ‘internet of things’.  I won’t get into that here other than to say that it’s clear from hearing Justin talk that we can expect our roles as data analysts to change dramatically.  Rather than us analysts dissecting the data to build recommendations, we’ll be designing the systems that do it for us.  Exciting times!

Thanks again to Justin for taking time away from his family to answer our endless questions and to @Gahlord for hosting the event at ThoughtFaucet.

Have questions about this post?  Get in touch with me by leaving a comment or Google+.

{ 3 comments }

How to implement Google Tag Manager in the WordPress Thesis Theme

November 24, 2013

For those of you using the WordPress Thesis theme (as this site is), you may be wondering how to properly implement Google Tag Manager.  The built in Thesis option for scripts places scripts such as Google Analytics at the end of the page just before the closing </body> tag.  This is not an ideal location [...]

Read the full article →

About to make the jump to the DoubleClick version of the Google Analytics script? Read this first.

November 23, 2013

Update 2/18/2014: As it turns out the logic I used in my test below has an issue due to using setTimeout to test whether the user’s browser had loaded the GA script successfully.  Phil Pearce commented and suggested following Andre Scholten’s method which avoids the use of setTimeout.  I’m happy to report that follow up [...]

Read the full article →

Google Tag Manager for Single Page Applications

July 17, 2013

Single Page Applications are becoming more and more common as web developers adopt asynchronous technologies such as AJAX, Node.JS and Knockout. One of the challenges of adding a web analytics solution such as Google Analytics to a Single Page Application, is the browser location (site address) does not change as a user performs actions on [...]

Read the full article →

Sampling a percentage of your users with Google Tag Manager

March 31, 2013

One of the neat features of Google Tag Manager is the ability to fire a tag or some custom JavaScript to only a certain percentage of your users.  Why would you want to do this?   Let’s say you want to use a test app like Optimizely but don’t want to pay for one of the [...]

Read the full article →

My new dev machine

September 16, 2012

I just sold my recently loaded Late 2011 15″ Macbook Pro and traded up (sideways, really) to an Asus Zenbook UX32-VD.  Why the Asus?  It’s a 13.3″ screen rocking 1920×1080 resolution with dedicated 1GB NVidia 620M video card.  That, and it’s 3.3 pounds.  It puts the Ultra in Ultrabook. It’s easily upgraded by removing the [...]

Read the full article →

Measuring the VALUE of Social Media using Google Analytics

March 20, 2012

Google Analytics just announced a set of new social reports to help marketers identify the value of traffic from social media sites such as Facebook and Twitter. As marketers, when faced with “What’s the ROI for Social?”, we often answer with “it’s the intangibles” or “it can’t be measured”. Now, with the addition of the [...]

Read the full article →

Acquisition Express – AdWords Communication Extension

February 25, 2012

Late last year, Google AdWords added another Ad Extension called the ‘Communication Extension’ to their growing list of ad extensions. The Communication Extension allows you, the AdWords advertiser, to include a simple email registration form right underneath your ad! As you can see above, because I was signed in with my Google Account when I [...]

Read the full article →