Google Analytics: How to Set Up a Simple Goal

Google Analytics provides a great feature for website owners to be able to track specific campaigns, also called a goal. It can be places on pages, forms, or anything you are wanting to track for to see if a campaign has an effective website conversion. It also tracks how the visitor arrived to the area…

The post Google Analytics: How to Set Up a Simple Goal appeared first on Diamond Website Conversion.

google-analytics-thumbnailGoogle Analytics provides a great feature for website owners to be able to track specific campaigns, also called a goal. It can be places on pages, forms, or anything you are wanting to track for to see if a campaign has an effective website conversion. It also tracks how the visitor arrived to the area you want to convert.

This works great after you’ve tried A/B Testing so you can verify the results from live traffic. In this article, you’ll learn how to set up a simple goal in Google Analytics.

Google Analytics: How to Set Up a Simple Goal

Please note, if you haven’t added your site to Google Analytics, then you can’t take advantage of the goal tool until you do. Aside from adding your site to Google Analytics, you will also need to apply the generated tracking code to your website.

The first step is in creating a simple goal is by clicking on your site in the Google Analytics dashboard. On the right hand side, scroll down to the area called Conversions. If you click on it, the area will expand and show you other links. Look for the area called overview as shown below.

googleanalytics-goals-screenshot-1

Now, you can either do this and be led to set up a simple goal or you can also click the Admin tab at the top. Image is below. In order to view the image larger and much better, you will have to right click on the image to open it in a new tab or window.

googleanalytics-goals-screenshot-2

On the last column under View, is an area called Goals. You’ll click that and be led to the page that has an area much like the image below.

googleanalytics-goals-screenshot-3

Click on the red button to create a goal. Once you have, you will need to name your goal and tell it hat type of tracking you want. In the case of this tutorial, and it being how to set up a simple goal, we’ll choose the first option called Destination. This is great for contact forms or lead generation forms. Once you have selected the option on how you want to track your goal, then click the blue button that says Next Step. See the example image below to see how you should proceed.

googleanalytics-goals-screenshot-4

In the next step, you tell it what page you are wanting to land on. You do not put the full URL. See the image below for how this step should go.

googleanalytics-goals-screenshot-5

Before hitting the blue button that says Create Goal, make sure to click the link that says Verify this Goal. This helps to make sure that your goal will work and checks it against your previous 7 days of stats on Google Analytics. In the case that you just joined and don’t have 7 days of stats, then proceed by clicking the button to create the goal. You can always check after a few days if the goal is actually working.

Once this has been set up, you won’t have to mess with it any more. You can just sit back and analyze how your goal is doing. Simple, right? There are other ways you can set up a goal in Google Analytics, like how long visitors are staying on your site (called Destination), by how many pages visits (Pages/Screens per Visit), or Event (like from watching a video.)

Have you taken advantage of setting up a goal in Google Analytics? Did you find it easy?

The post Google Analytics: How to Set Up a Simple Goal appeared first on Diamond Website Conversion.

8 Indispensable Google Tag Manager Variables

Variables are dynamic bits of information that can be used within Google Tag Manager Tags, Rules, and even between Variables. They look something like this: {{Variable Name}}. These can get the value of 1st Party Cookies, JavaScript Variables, Data Layer Variables, and the ‘Custom JavaScript’ macro lets you extend the functionality of Variables nearly limitlessly. For a great overview of everything on offer, check out Simo Ahava’s complete guide to all of the default Variables. Here’s a list of some of my personal favorites.

1. User Agent

The User Agent is a string of text that identifies the “software (a software agent) that is acting on behalf of a user”. In our case, this is the browser and device used to access our website. For example, here’s yours:

You can test the User Agent to detect what browser a user is accessing your site with. This can be helpful if you want to track certain browser-based information (outside of what GA already collects) or change or exclude portions of your tag for users on particular browsers.

Since the User Agent is stored in the navigator.userAgent property, all you have to do is create a JavaScript Variable Variable (yes, ‘Variable Variable’) like below:

Select the variable type 'JavaScript Variable' and enter 'navigator.userAgent' into the input

For example, if you wanted to run a test and exclude any users of Internet Explorer 8 or below, you could do the following:

var isIeEightOrBelow = {{User Agent}}.match(/MSIE [2-8]/i) > -1 ? true : false;
if (isIeEightOrBelow) {
  // some code
} else {
  // some other code, or nothing.
}

You could also block an entire tag by using the same match as a blocking rule:
Blocking IE8 with Tag ManagerWARNING: User agent tests are often unreliable. Never hinge site-critical functionality on a user agent test; use feature detection instead.

2. Week of the Year

Having the week of the year handy is more useful than you might first expect; one thing I like to do is store the week and year with a converting user, so that I can perform acquisition cohort analysis within Google Analytics. This snippet (courtesy of RobG on Stack Overflow) extends the built-in Date object to allow you to get the current week of the year.

function() {
  Date.prototype.getWeekNumber = function(){
    var d = new Date(+this);
    d.setHours(0,0,0);
    d.setDate(d.getDate()+4-(d.getDay()||7));
    return Math.ceil((((d-new Date(d.getFullYear(),0,1))/8.64e7)+1)/7);
  };
  return new Date().getWeekNumber();
}

This is a great way to segment data and learn how user behavior changes over time. This can also be helpful for analyzing the impact new products or features has on your business.

Update: With the new Cohort Analysis Report, you can do some of this style of reporting natively. That said, you can only look at a limited set of cohorts in the data, so this is still a good back-up.

3. Mobile User

This is a snippet courtesy of Michael Zaporozhets on Stack Overflow; it’s a function that will return True if the user is on a mobile device, according to their user agent.

function() {
  window.mobilecheck = function() {
  var check = false;
  (function(a){if(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0,4)))check = true})(navigator.userAgent||navigator.vendor||window.opera);
  return check; }
  return window.mobilecheck();
}

This can be a useful piece of information if you’d like to prevent certain tags from firing on mobile devices, or if you’d like to exclude mobile users from a Content Experiment. The above warning about using the User Agent still applies.

4. The Page Title

This is a simple set of Macros that can come in handy for a number of reasons; say, for example, your site returns content on the same path, but with a huge variety in what content it returns based on some byzantine query string structure. In that case, the Page Title might expose some useful information. Fortunately, this is easily accessible through the document.title property. Just configure the Macro like you see below:
Select 'JavaScript Variable' for your Macro type, then enter 'document.title' in the input

Of course, Google Analytics will already capture the Page Title for you, but should you need to combine that data with another data point for deeper context, this is handy to have.

5. The Meta Description

The meta description can also be a useful piece of information to have, either to pull data from or to push into Google Analytics. One example of how this can be used is to fire an event on every pageview that stores the meta description and the URL it was fired on; this can be helpful for tracking down duplicate or blank meta descriptions. Of course, you can also see this data inside the HTML Suggestions section of Google Webmaster Tools.

function() {
  var metas = document.getElementsByTagName('meta');
  for (var i = 0; i 

Update: Jim Gianoglio of LunaMetrics fame pointed out that this could be accomplished JavaScript-free by using the below JavaScript Variable macro:
Example JavaScript Macro with document.head.children.description.content entered as the value

The value entered above is document.head.children.description.content, which will return the Meta Description or Undefined. Google Tag Manager helpfully catches errors for missing properties.

6. The Environment

If your site is developed and runs in several different environments, such as a development environment, a staging environment, and a production environment, it can be useful to modify tag behavior based on which enviroment the tag is operating in. For example, I wouldn't want my Google Analytics tag sending data to my production Google Analytics account from activity taking place in my development area. This could dirty my data with extra transactions, events, and other site metrics. Even a few extra test transactions run for Quality Assurance can skew the data.

There are a few ways to handle this.

A.) Have your developers populate the environment in the Data Layer

You can have your development team add a Data Layer variable that specifies what environment the site is currently being loaded in, like this:

var dataLayer = window.dataLayer|| (window.dataLayer = []);
dataLayer.push({'environment':'staging'});

B.) Detect the environment based on the hostname

If your development and staging environments live at different hostnames, like 'mysitestaging.com', you can create a Custom JavaScript Macro that returns the environment based on what it sees in the hostname, like this:

function() {
  var hostname = {{Page Hostname}};
  if (hostname === 'mysite.com') return 'Production';
  if (hostname === 'mysitestaging.com') return 'Staging';
}

Update: Pavel Jašek pointed out to me on Twitter that lookup tables could be used in place of custom JavaScript; this is a much better way to go about it. Something like below would suffice:
An example lookup table with a list of potential hostnames and their corresponding environment strings

C.) Detect the environment by testing something else

If, for some reason, your testing enviroment is operating at the same hostname that your production environment is in, you'll have to be creative and determine another authoritative test to run in order to figure out which environment you're running in. Here's a handful of ideas:

  • Try and access a service available only in one environment, like an outside API
  • Check the hostname of resources loaded on the page, like images, CSS, or JavaScript
  • Search external stylesheets or JavaScript for comments – typically these will be minified out in Production

7. The Google Analytics UA Number

The UA number is the number associated with the Google Analytics property that a hit is being sent off to. Having this handy can be useful for either configuring things on the fly or testing data before takng certain actions. If your site only operates in one environment, this is a snap:

function() {
  return 'UA-XXXXX-XX';  // Enter in your UA number here
}

Update: The above is a valid, but more roundabout way to accomplish this – I’ve left it there for posterity, but I would recommend instead using a Constant macro for a single UA number, like below:
Example Constant macro with a Google Analytics UA number stored as the value
However, if you’d like to use a different property for each environment (you should), then you might do something like this:

function() {
  var environment = {{environment}};
  if ( environment === 'Production' ) {
    return 'UA-XXXXX-XX';
  }
  if ( environment === 'Staging' ) {
    return 'UA-YYYYY-YY'; 
  }
}

Update: Per the above update, a lookup table would be a better option here. Here’s what it might look like:
An example lookup table for a Google Analytics UA Number, keyed by environment
Pavel also recommended this article on lookup tables by Simo Ahava.

8. Google Analytics User ID

Whenever a user visits your site, Google Analytics assigns them a unique, random identifier. This value is stored inside the cookie that Google Analytics sets on the browser. I like to capture it and store it inside Google Analytics as a Custom Dimension or Custom Variable; it can come in handy when trying to track down specific user behavior across visits or transactions.

There are two ways to get to this data – either by extracting it from the Google Analytics cookies directly, or, with the Universal Analytics library, asking for it politely.

Option 1: Cookie Sniffing

FOR CLASSIC ANALYTICS:
// Only works if __utma cookie has been set
function() {
  var __utmaCookie = document.cookie.match(/__utma=(.*?)(?:;|$)/);
  if(__utmaCookie && __utmaCookie[1]) {
    var utmaVals = __utmaCookie[1].split('.');
    if(utmaVals[2]) {
      return utmaVals[1] + '.' + utmaVals[2];
    }
  }
}
FOR UNIVERSAL ANALYTICS:
// Only works if _ga cookie has been set
function () {
  var _gaCookie = document.cookie.match(/_ga=(.*?)(?:;|$)/);
  if(_gaCookie && _gaCookie[1]) {
    return  _gaCookie[1].match(/\d+\.\d+$/)[0];
  }
}

Option 2: Asking Politely (Tracker Properties; Universal Only)

FOR UNIVERSAL ANALYTICS WITHOUT A NAMED TRACKER (TYPICAL):
function() {

  // Fetch the GA Library
  var gaLib = window[ window.GoogleAnalyticsObject ];
  var trackers = gaLib.getAll();
  var uaNumber = {{UA Number}};

  for ( var i = 0; i 

FOR UNIVERSAL ANALYTICS WITH A NAMED TRACKER (UNUSUAL):

function() {

  var gaLib = window[window.GoogleAnalyticsObject];
  var tracker = gaLib.getByName({{Tracker Name}});

  if(tracker) {

    return tracker.get('clientId');

  }

}

Those are some of my favorite Custom Variables; what are yours? Share with me on Twitter at @notdanwilkerson.

Variables are dynamic bits of information that can be used within Google Tag Manager Tags, Rules, and even between Variables. They look something like this: {{Variable Name}}. These can get the value of 1st Party Cookies, JavaScript Variables, Data Layer Variables, and the 'Custom JavaScript' macro lets you extend the functionality of Variables nearly limitlessly. For a great overview of everything on offer, check out Simo Ahava's complete guide to all of the default Variables. Here's a list of some of my personal favorites.

1. User Agent

The User Agent is a string of text that identifies the "software (a software agent) that is acting on behalf of a user". In our case, this is the browser and device used to access our website. For example, here's yours:

You can test the User Agent to detect what browser a user is accessing your site with. This can be helpful if you want to track certain browser-based information (outside of what GA already collects) or change or exclude portions of your tag for users on particular browsers.

Since the User Agent is stored in the navigator.userAgent property, all you have to do is create a JavaScript Variable Variable (yes, 'Variable Variable') like below:

Select the variable type 'JavaScript Variable' and enter 'navigator.userAgent' into the input

For example, if you wanted to run a test and exclude any users of Internet Explorer 8 or below, you could do the following:

var isIeEightOrBelow = {{User Agent}}.match(/MSIE [2-8]/i) > -1 ? true : false;
if (isIeEightOrBelow) {
  // some code
} else {
  // some other code, or nothing.
}

You could also block an entire tag by using the same match as a blocking rule:
Blocking IE8 with Tag Manager WARNING: User agent tests are often unreliable. Never hinge site-critical functionality on a user agent test; use feature detection instead.

2. Week of the Year

Having the week of the year handy is more useful than you might first expect; one thing I like to do is store the week and year with a converting user, so that I can perform acquisition cohort analysis within Google Analytics. This snippet (courtesy of RobG on Stack Overflow) extends the built-in Date object to allow you to get the current week of the year.

function() {
  Date.prototype.getWeekNumber = function(){
    var d = new Date(+this);
    d.setHours(0,0,0);
    d.setDate(d.getDate()+4-(d.getDay()||7));
    return Math.ceil((((d-new Date(d.getFullYear(),0,1))/8.64e7)+1)/7);
  };
  return new Date().getWeekNumber();
}

This is a great way to segment data and learn how user behavior changes over time. This can also be helpful for analyzing the impact new products or features has on your business.

Update: With the new Cohort Analysis Report, you can do some of this style of reporting natively. That said, you can only look at a limited set of cohorts in the data, so this is still a good back-up.

3. Mobile User

This is a snippet courtesy of Michael Zaporozhets on Stack Overflow; it's a function that will return True if the user is on a mobile device, according to their user agent.

function() {
  window.mobilecheck = function() {
  var check = false;
  (function(a){if(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0,4)))check = true})(navigator.userAgent||navigator.vendor||window.opera);
  return check; }
  return window.mobilecheck();
}

This can be a useful piece of information if you'd like to prevent certain tags from firing on mobile devices, or if you'd like to exclude mobile users from a Content Experiment. The above warning about using the User Agent still applies.

4. The Page Title

This is a simple set of Macros that can come in handy for a number of reasons; say, for example, your site returns content on the same path, but with a huge variety in what content it returns based on some byzantine query string structure. In that case, the Page Title might expose some useful information. Fortunately, this is easily accessible through the document.title property. Just configure the Macro like you see below:
Select 'JavaScript Variable' for your Macro type, then enter 'document.title' in the input

Of course, Google Analytics will already capture the Page Title for you, but should you need to combine that data with another data point for deeper context, this is handy to have.

5. The Meta Description

The meta description can also be a useful piece of information to have, either to pull data from or to push into Google Analytics. One example of how this can be used is to fire an event on every pageview that stores the meta description and the URL it was fired on; this can be helpful for tracking down duplicate or blank meta descriptions. Of course, you can also see this data inside the HTML Suggestions section of Google Webmaster Tools.

function() {
  var metas = document.getElementsByTagName('meta');
  for (var i = 0; i < metas.length; i++) {
    if (metas[i].name === 'description') {
      return metas[i].content;
    }
  }
  return 'None found';
}

Update: Jim Gianoglio of LunaMetrics fame pointed out that this could be accomplished JavaScript-free by using the below JavaScript Variable macro:
Example JavaScript Macro with document.head.children.description.content entered as the value

The value entered above is document.head.children.description.content, which will return the Meta Description or Undefined. Google Tag Manager helpfully catches errors for missing properties.

6. The Environment

If your site is developed and runs in several different environments, such as a development environment, a staging environment, and a production environment, it can be useful to modify tag behavior based on which enviroment the tag is operating in. For example, I wouldn't want my Google Analytics tag sending data to my production Google Analytics account from activity taking place in my development area. This could dirty my data with extra transactions, events, and other site metrics. Even a few extra test transactions run for Quality Assurance can skew the data.

There are a few ways to handle this.

A.) Have your developers populate the environment in the Data Layer

You can have your development team add a Data Layer variable that specifies what environment the site is currently being loaded in, like this:

var dataLayer = window.dataLayer|| (window.dataLayer = []);
dataLayer.push({'environment':'staging'});

B.) Detect the environment based on the hostname

If your development and staging environments live at different hostnames, like 'mysitestaging.com', you can create a Custom JavaScript Macro that returns the environment based on what it sees in the hostname, like this:

function() {
  var hostname = {{Page Hostname}};
  if (hostname === 'mysite.com') return 'Production';
  if (hostname === 'mysitestaging.com') return 'Staging';
}

Update: Pavel Jašek pointed out to me on Twitter that lookup tables could be used in place of custom JavaScript; this is a much better way to go about it. Something like below would suffice:
An example lookup table with a list of potential hostnames and their corresponding environment strings

C.) Detect the environment by testing something else

If, for some reason, your testing enviroment is operating at the same hostname that your production environment is in, you'll have to be creative and determine another authoritative test to run in order to figure out which environment you're running in. Here's a handful of ideas:

  • Try and access a service available only in one environment, like an outside API
  • Check the hostname of resources loaded on the page, like images, CSS, or JavaScript
  • Search external stylesheets or JavaScript for comments - typically these will be minified out in Production

7. The Google Analytics UA Number

The UA number is the number associated with the Google Analytics property that a hit is being sent off to. Having this handy can be useful for either configuring things on the fly or testing data before takng certain actions. If your site only operates in one environment, this is a snap:

function() {
  return 'UA-XXXXX-XX';  // Enter in your UA number here
}

Update: The above is a valid, but more roundabout way to accomplish this - I've left it there for posterity, but I would recommend instead using a Constant macro for a single UA number, like below:
Example Constant macro with a Google Analytics UA number stored as the value However, if you'd like to use a different property for each environment (you should), then you might do something like this:

function() {
  var environment = {{environment}};
  if ( environment === 'Production' ) {
    return 'UA-XXXXX-XX';
  }
  if ( environment === 'Staging' ) {
    return 'UA-YYYYY-YY'; 
  }
}

Update: Per the above update, a lookup table would be a better option here. Here's what it might look like:
An example lookup table for a Google Analytics UA Number, keyed by environment Pavel also recommended this article on lookup tables by Simo Ahava.

8. Google Analytics User ID

Whenever a user visits your site, Google Analytics assigns them a unique, random identifier. This value is stored inside the cookie that Google Analytics sets on the browser. I like to capture it and store it inside Google Analytics as a Custom Dimension or Custom Variable; it can come in handy when trying to track down specific user behavior across visits or transactions.

There are two ways to get to this data - either by extracting it from the Google Analytics cookies directly, or, with the Universal Analytics library, asking for it politely.

Option 1: Cookie Sniffing

FOR CLASSIC ANALYTICS:
// Only works if __utma cookie has been set
function() {
  var __utmaCookie = document.cookie.match(/__utma=(.*?)(?:;|$)/);
  if(__utmaCookie && __utmaCookie[1]) {
    var utmaVals = __utmaCookie[1].split('.');
    if(utmaVals[2]) {
      return utmaVals[1] + '.' + utmaVals[2];
    }
  }
}
FOR UNIVERSAL ANALYTICS:
// Only works if _ga cookie has been set
function () {
  var _gaCookie = document.cookie.match(/_ga=(.*?)(?:;|$)/);
  if(_gaCookie && _gaCookie[1]) {
    return  _gaCookie[1].match(/\d+\.\d+$/)[0];
  }
}

Option 2: Asking Politely (Tracker Properties; Universal Only)

FOR UNIVERSAL ANALYTICS WITHOUT A NAMED TRACKER (TYPICAL):
function() {

  // Fetch the GA Library
  var gaLib = window[ window.GoogleAnalyticsObject ];
  var trackers = gaLib.getAll();
  var uaNumber = {{UA Number}};

  for ( var i = 0; i < trackers.length; i++ ) {
    if ( trackers[i].get('trackingId') === uaNumber ) {
      return trackers[i].get('clientId');
    }
  }
}

FOR UNIVERSAL ANALYTICS WITH A NAMED TRACKER (UNUSUAL):

function() {

  var gaLib = window[window.GoogleAnalyticsObject];
  var tracker = gaLib.getByName({{Tracker Name}});

  if(tracker) {

    return tracker.get('clientId');

  }

}

Those are some of my favorite Custom Variables; what are yours? Share with me on Twitter at @notdanwilkerson.

Average Session Duration – What is it and Why Bloggers Should Care

In Google Analytics, one of the statistics measures is average session duration. In simple terms, this is the amount of the time that a person spends on your website. This article will help you understand average session duration and if you’re a blogger, perhaps persuade you to take a better look into this piece of…

The post Average Session Duration – What is it and Why Bloggers Should Care appeared first on Diamond Website Conversion.

averagesessionduration-thumbnailIn Google Analytics, one of the statistics measures is average session duration. In simple terms, this is the amount of the time that a person spends on your website. This article will help you understand average session duration and if you’re a blogger, perhaps persuade you to take a better look into this piece of information.

As an extra goodie, there will be a few brief tips to hopefully get those visitors to stay longer.

Average Session Duration – What is it and Why Bloggers Should Care

As mentioned before, the average session duration is the average time of all the time spent on your site by your visitors. This time is usually a great indicator of how interested people are with the content on your website, regardless if it is something you are selling or not.

The smaller the number that the average session duration is, means that you’ve got a lot of work to do in either jazzing up your content, or creating new articles that your visitors are truly interested in seeing. You also would need to try to entice those visitors to stay on your website longer.

For example, if your visitors are only on your website for less than a minute and a half, you probably need to be concerned. Of course, Google Analytics has other tools you can look at after looking at your average session duration statistic. Usually you will want to check out where the visitors are coming to your site and where they are leaving. If the entrance and exit of your website, especially a blog, is the front page, then you’ve got a problem with the front of your website.

Possible Problems that Could be the reason for a poor Average Session Duration stat

  • Poor Navigation – If you don’t give people a clear path in order to navigate your website, they probably won’t go any further than the front page, or if you’re lucky, one article.
  • The design is undesirable. – A lot of people are visual. If your people can’t identify with you and remember you, they might not be back. Some bloggers who choose minimalistic designs often sacrifice their branding.
  • There are no effective calls to action. – If you are giving people a reason to come back, they won’t. Ask them to subscribe to your newsletter. Encourage the to follow you on the social networks. Encourage them to use your contact form or click on your about page to learn more about you and what your website is about.
  • The articles have boring titles. – People aren’t enticed to click on and read articles that are unappealing. Be concise and try to think of what spurs you on to clicking and reading a blog post based on the title. You can learn a lot from visiting leaders in your niche to see what’s most effective.
  • The website is just confusing. – If people don’t know what your website is about, and why they should be there rather than some other site, then they won’t be back. Give them a reason. If you’re not sure, go back to your original site focus plan and tweak it.
  • No plan to keep visitors once they’ve clicked deeper into the website. – Once people are within your website, whether it’s a blog post, or your shopping cart, or landing page, you need to keep them there. Entice them with linking to other articles within your site, in your post’s content. You could also benefit from either showing some most recent posts or related posts, or both.

Average duration session is definitely an important factor in website conversion. The goal is to keep them there as long as possible because that WILL get the subscriber, the social share, the commentator, and above all, THE SALE!

Do you pay attention to your average session duration stat for your website?

The post Average Session Duration – What is it and Why Bloggers Should Care appeared first on Diamond Website Conversion.

Getting a Handle on Site Speed

One of my greatest challenges has been to convince clients that they have a slow loading site AND that a slow loading website reduces the number of sales or leads they can expect to get. I’ve shown them the pretty waterfall charts that show that their site loads in 6.7 seconds – only to have…

The post Getting a Handle on Site Speed appeared first on Diamond Website Conversion.

One of my greatest challenges has been to convince clients that they have a slow loading site AND that a slow loading website reduces the number of sales or leads they can expect to get.

I’ve shown them the pretty waterfall charts that show that their site loads in 6.7 seconds – only to have their eyes glaze over.

I touch on it when we’re reviewing their Google Analytics and pointed out that page load times are now part of Google’s search algorythm – and still no response.

Then I discovered a secret weapon….the video of a site loading from webpagetest.org. There is nothing like seeing a blank screen while those seconds tick off to convince clients that site speed is important.

Site speed test from Webpagetest.org.  Notice how at 1.4 seconds 0% loaded and at 1.7 seconds 67% is loaded

Site speed test from Webpagetest.org. Notice how at 1.4 seconds 0% loaded and at 1.7 seconds 67% is loaded

 

Why Page Load Times Matter

According to the research firm Aberdeen Group Inc., a 1-second delay in web page load time translates into a 7% loss in conversions. This means that for each 10,000 in monthly sales, you stand to lose $700 or $8,400 per year.

We all want websites with cool features that attract attention and hold interest. But if that technology causes delays or fails to work properly, visitors won’t wait around….they’re off to something else.

Tag Man in partnership with glasses e-retailer Glasses Direct ran a test to study page speed and conversion behavior.

As expected, the study found that page-load speeds impacted conversion rates. The conversion rate peaked at about two seconds, dropping by 6.7% for each additional second.

Conversions peak at 1-2 second load times.  Source Tagman case study of Glasses Direct

Conversions peak at 1-2 second load times. Source Tagman case study of Glasses Direct

Two studies by Akamai and Gomez are frequently cited in reports on site speed. Both reports are several years old now, but what are the odds that visitor expectations have gone down?

The Akamai Study published in September 2009 interviewed 1048 online shoppers and reported the following:

  • 47% of the people expect a web page to load in two seconds or less
  • 40% will abandon a web page if it takes longer than three seconds to load
  • 52% of online shoppers claim that quick page loads are important for their loyalty to a site
  • 64% of shoppers who are dissatisfied with their site visit will go somewhere else to shop next time.

Remember this was 2009….with all the advances we’ve seen in technology and the emphasis on reducing page load times – do you believe that a site that takes over 2 seconds to load won’t impact visitor behavior?

Two interesting additional points came out of the The Gomez Report published in 2010 which interviewed 1500 consumers about their opinions:

  • 58% of mobile device users expect sites to download as quickly as they would on their home computers
  • 61% of mobile users said that poor performance would make them less likely to visit the mobile website again.

If you’re like most website owners, mobile traffic to your site is rising. It’s common to see 25% or more of your website visitors coming from mobile devices. Are you meeting your customer’s expectations for quick page load times on mobile devices? Probably not.

Responsive Design and Site Speed

In a month-long study of 12 e-retail responsive design sites conducted by Keynote, ¹ reported that the average load times by device were:

  • Desktop PCs 3.14 seconds (high-speed connections)
  • Tablets 2.8 seconds (high-speed connections)
  • Smart Phones 18.24 seconds (combination 3G and 4G connections)

The companies interviewed spent a lot of time, money, and effort in designing, building and tweaking their sites for mobile visitors.

As Mike Clem, vice-president of e-commerce at Sweetwater commented, templates with a “one-size-fits-all” approach carry a lot of additional, unnecessary code and this slows performance, because all that code has to load before the visitor can see the page on their desktop, tablet, or smartphone.²

What to do next?

Start by getting a clear idea of your site’s page load times. Get a combination of data from Webmaster Tools, Google Analtyics and services like YSlow, WebPageTest, and Pingdom. Look for commonalities to figure out what’s slowing down your site and pick off the biggest offenders first. A good developer can be of tremendous help here.

Next tackle the core of the problem. You’ll never cure poor site speed by tinkering around the edges of your website. For a WordPress site, this would include the following:

  • A clean theme with clean code – get rid of that unnecessary code. If you can afford a custom theme written specifically for your site, great – if you can’t, make sure that the template you use doesn’t carry a lot of excess baggage.
  • Switch off all the plugins you don’t need or use. Watch the page load times on the plugins you use and switch out of load-time hogs if you can.
  • Optimize images and graphics – Size your images before you load them into wordpress – if you can get away with lower resolutions without loss of quality, you’ll save some seconds.
  • Fast web hosting configured specifically for WordPress along with a caching strategy

Site speed is an ongoing challenge. As you make changes to your site, update plugins and themes and add additional features – be sure to test the impact on your site speed.

____________________________________________________________________________________________

¹ Siwicki, Bill. “The Ugly Truth about Responsive Design (and how to fix it).”  Internet Retailer June 2014: 42-54. Print.

² Siwicki, Bill. “The Ugly Truth about Responsive Design (and how to fix it).”  Internet Retailer June 2014: 42-54. Print.

 

The post Getting a Handle on Site Speed appeared first on Diamond Website Conversion.

Using Offline and Online data to drive Google Analytics Remarketing

The Google Analytics platform has been changing from a web analytics tool to a user-centric digital measurement tool (we’ve been calling it Universal Analytics). This evolution includes a number of changes to the system and completely new features. But what can you do when you put all of these pieces together? I wanted to write […]

Using Offline and Online data to drive Google Analytics Remarketing is a post from: Analytics Talk by Justin Cutroni

The post Using Offline and Online data to drive Google Analytics Remarketing appeared first on Analytics Talk.

The Google Analytics platform has been changing from a web analytics tool to a user-centric digital measurement tool (we’ve been calling it Universal Analytics). This evolution includes a number of changes to the system and completely new features. But what can you do when you put all of these pieces together?

I wanted to write a quick post about how a business could use the entire platform to better market to users on the web based on non-website activities. We’ll explore how to use offline and online data to create remarketing lists in Google Analytics.

Before I start a hat-tip to my buddy Dan Stone – a product manager at Google Analytics who often talks about this type of usage.

Influencing Display Advertising using Email Behavior

Businesses interact with users via many different channels – search, display, social, email, etc. And they’re always looking to better understand how one channel impacts another channel. That’s why we have attribution modeling.

But sometime we want to take direct action, or even automated action, in a channel based on user behavior in a separate channel.

For example, I may want to change my search or display strategy for users on my email list. Perhaps I want them to see different display ads because I have a better relationship with them.

Here’s an example.

With Analytics we can collect data from email marketing tools, send it to Google Analytics and then use that information to change display campaigns.

We can send data from email marketing tools, to Google Analytics, then use the data to drive Remarketing.

We can send data from email marketing tools, to Google Analytics, then use the data to drive Remarketing.

The Implementation

With some of the new features in Google Analytics it is very possible to change a user’s display advertising experience based on behavior in other digital environments.

The first thing we need to do is bind the data in Google Analytics to the data in our own systems. This might be the data in a CRM or some other customer system. We’re going to use an old-school method that I describe in the post integrating Google Analytics with a CRM.

Here’s a summary…

When a user visits your site (or your app) Google Analytics sets a unique, anonymous identifier. This identifier is called the Client ID or cid for short.

What we need to do is extract the client ID value from the Google Analytics cookies and pass it to your CRM system. Once it’s in your systems you should be able to join your internal customer IDs with the GA ID. I should note – this is not some task you finish in an afternoon. You need some nerd help and it could take a while.

You can extract the GA identifier from the tracking cookie and send it to your own system.

You can extract the GA identifier from the tracking cookie and send it to your own system.

Make sure you check out these two posts for more information:
Integrating Google Analytics with a CRM
Understanding Cross Device Measurement and the User-ID

Now that we have the two data sets joined we can do something really cool – we can send user-specific data to Google Analytics from other systems. This means that when we send out an email, or some other user-specific actions happens in our system, we can send that behavioral data to Google Analytics. How?

To send data to GA from other systems we use the measurement protocol. This technology let’s us send data to Google Analytics from any system that can connect to the internet. It defines how to send data to GA. We’ll use the measurement protocol to send data about email activities.

When we send an email to a user we will also send a measurement protocol hit to Google Analytics.

When an email is sent from your system, you can send a hit to Google Analytics using the measurement protocol.

When an email is sent from your system, you can send a hit to Google Analytics using the measurement protocol.

Specifically, we’ll send an event piece of data. The event will indicate that an email was sent to this user and the type of email:

www.google-analytics.com/collect?v=1&tid=UA-XX-Y&cid [UniqueID]&t=event&ec=Email&ea=Send&el=BackToSchool2014

If we want to be really fancy then we can also send a second hit to Google Analytics when the user receives the email and another hit when the user opens the email. For example, if the user opens the email then we can trigger a pixel within the email that sends a hit to Google Analytics.

www.google-analytics.com/collect?v=1&tid=UA-XX-Y&cid=[UniqueID]&t=event&ec=Email&ea=Open&el=BackToSchool2014

I need to stress, you need to write a bunch of code that generates these hits. The implementation will really depend on your systems.

The data in the above hits indicates that this email was part of the BackToSchool2014 campaign (look for the event data ec for Event Category, el for Event Label, ea for Event Actions. If we looked in Google Analytics the data would look something like this:

Offline email actions can be captured with the measurement protocol as events.

Offline email actions can be captured with the measurement protocol as events.

All of these hits include a specific parameter named cid. This is the Client ID for the particular recipient of the email that I discussed earlier. When Google Analytics processes these hits they will be merged with the dame user data from the website – because they have the same cid value.

OK, now we have user data coming from two separate systems and Goole Analytics is merging it together.

Here’s where the fun comes in.

Because all of this data is in one place, we can segment users in Analytics based on behavior, then use that list of users for remarketing.

You can join the Google Analytics ID, called CID, with your own ID. But then you can collect off-site actions in GA and tie them to other GA data.

after all of our work, we’re using the GA data measuring sent emails to create a remarketing list.

For those that have not use Remarketing, this is one of my favorite features in Google Analytics. Remarketing let’s you segment user on your website then send that list of users to Google AdWords (or DoubleClick if you use Analytics Premium) for use as a remarketing list.

The remarketing segment would look like this:

Segmenting users that received and opened an email.

Segmenting users that received and opened an email.

This segment is all users that opened the back-to-school email. I could also add a condition that the user received the email, but that’s not really necessary.

Now we can use this list of users in AdWords. How? I may want to use the same creative for their ads. Or perhaps I offer them the same deal that was in the email.

This technique is not just for email – you can use the measurement protocol to send data from any system. That means behavioral information from other digital experiences can be used to drive remarketing lists.

Hopefully this example gives you some idea of how multiple Google Analytics features can be used together to drive real business results.

Using Offline and Online data to drive Google Analytics Remarketing is a post from: Analytics Talk by Justin Cutroni

The post Using Offline and Online data to drive Google Analytics Remarketing appeared first on Analytics Talk.

Understanding Google Webmaster Tools

As much as you might think Google is making it hard to get traffic, they really aren’t. They have tools like Google Webmaster tools and Google Analytics. The difference between the two are the fact that Google Analytics measures your traffic, and Google Webmaster Tools tells you how Google actually sees your website. This article…

The post Understanding Google Webmaster Tools appeared first on Diamond Website Conversion.

google-webmaster-tools-logo-thumbnailAs much as you might think Google is making it hard to get traffic, they really aren’t. They have tools like Google Webmaster tools and Google Analytics. The difference between the two are the fact that Google Analytics measures your traffic, and Google Webmaster Tools tells you how Google actually sees your website.

This article is written to help you understand Google Webmaster Tools better. In fact, this article is part of a series, so there will be other parts to check out so you can become more familiar with Google Webmaster Tools.

Understanding Google Webmaster Tools

As mentioned before, Google Webmaster Tools is designed for you to see how the search engine (Google) sees your website. Consider it kind of like the doctor promoting healthy search for websites. Some of the results are:

  • Sharing what type of markup data format the search engines are seeing in your site, like Schema.org
  • Suggesting how to improve user experience and performance
  • Allowing you to demote specific areas of your site from Sitelinks
  • Giving a details list of search queries done on your website
  • Giving a list of links to sites linking into your website
  • Listing internal links
  • Showing Index status
  • Giving a list of keywords that are organized by the most significant one first
  • Allowing you to remove URLs from your website
  • Displaying crawl errors, as well as what types of errors
  • Having the ability to block URLs from the search engines
  • Being alerted if there are any security issues

In order to be able to use Google Webmaster tools, you must sign up and submit your website. The process involves putting a verification code somewhere on your website or verifying it through your domain registrar. After you verify the site, you need to submit a sitemap, once that is a valid Sitemaps.org sitemap.

The Sitemap.org valid sitemap allows Google to easily crawl the site. The markup used that search engine crawl is XML. For website owners that use WordPress and have the WordPress SEO by Yoast plugin, finding the link to the sitemap is easy. For other content management systems, there is a somewhat equivalent method to find the sitemap. For static websites (ones not powered with a database and may be solely HTML), building a sitemap may be necessary.

Once the sitemap has been submitting, Google may take a little while to crawl the site. Some site are lucky to be crawled within the week, and others, two weeks. After your site has been crawled, you can view information on what Google is seeing.

search-queries-gwt-screenshotYou probably will want to make sure that there are no crawl errors like a page not found, or any server issues. You will also want to make sure to observe if you have any duplicate meta descriptions and duplicate title tags to improve your search results. You obviously don’t want the same article description for several posts, right? 😉

Another area you might want to check out is the search queries. It’s probably good to check out the first time in order to make sure that the keywords are relevant to what your website is about. If they aren’t, you might need to go back and improve your content.

One last area that you should check is to make sure your site isn’t flagged for spam, duplicate content, or has any security issues. If you’re accepting paid links, you probably should stop. Google has gone to great lengths to discourage website owners from accepting paid links. If you have any alerts, fix the issue. Once done with fixing anything that was flagged, you can reply to Google’s team and they will review to make sure your site is not violating any of their rules.

It’s important to understand that Google Webmaster Tools can be a powerful tool in making sure your website is listed as accurately as possible on the search engine results.

Do you use Google Webmaster Tools?

The post Understanding Google Webmaster Tools appeared first on Diamond Website Conversion.

What Do You Do After You First Apply Google Anayltics to Your Website?

When you get into creating and managing a website, at some point you’re going to hear about Google Analytics, especially being told you need to have it on your website. Regardless if you’re a blogger, a small business owner, or a big corporate business, you do need a tool to measure your site’s progress. Google…

The post What Do You Do After You First Apply Google Anayltics to Your Website? appeared first on Diamond Website Conversion.

google-analytics-thumbnailWhen you get into creating and managing a website, at some point you’re going to hear about Google Analytics, especially being told you need to have it on your website. Regardless if you’re a blogger, a small business owner, or a big corporate business, you do need a tool to measure your site’s progress. Google Analytics just happens to be a good one that is also free to use.

So…

What Do You Do After You First Apply Google Anayltics to Your Website?

The majority of users may look in on their stats once a day or once a week. Google Analytics provides quite a bit of statistics. You can even set campaigns to analyze traffic from your website and some of your social network handles.

It’s quite alright to take a frequent look at your stats, but if you’re just looking at them and wishing your traffic to improve, then you’re missing out on what Google Analytics can do for you. It takes analyzing what’s going on and planning a campaign to drive attention to those areas of your website that you want people to see.

The great thing about most stats programs, including Google Analytics is that they provide exactly what information you need to know about your visitors. You can even find out if you’re targeting the correct audience, and at what times they hit your website.

Once you’ve installed Google Analytics on your website, you should let it do it’s job in collecting information. After about 3 weeks to a month, you should have a nice tentative spread of your website’s traffic.

When installing Google analytics to your website for the first time, some of the most important stats you should look at are:

  • Pageviews
  • Percentage of new visitors
  • Percentage of returning visitors
  • Bounce rate
  • How you are acquiring your visitors (where are they coming from)
  • Keywords

While there are a TON of other stats, your first time through should be to gather this information and start to put together a first campaign.

Your keywords, acquisition, and your bounce rate with each campaign you plan will change in time depending on how you adjust your website conversion plan.

Keywords

Before you even look at your stats, you really should already have a list of keywords that you’ve been wanting to work on for your website. If your analytics in Google are not coinciding with your intended list, then you’ve got homework to do in creating content around those keywords. Don’t worry, some people have websites for a few years before realizing that they’ve been missing out on capitalizing on being more laser focused on their keyword strategy.

Acquisition

If your website is brand new, you might not have too much information on how you’ve been acquiring your visitors. You will have a small idea, and can use those stats to either focus on those places that are sending you traffic, or working on trying to get traffic from new sources. It might take making sure your website is properly listed on search engines, creating social network handles, and sharing your content.

Bounce Rate

Bounce rate gives you a percentage of how many of your website visitors are only viewing one of your pages, and then leaving. Your bounce rate should never be high. In fact, your strategy should be in converting those visitors to fill out your lead forms, buy your product, share and comment on your blog posts, or even subscribe to your newsletter.

If you can put a plan together that gives you a low bounce rate, great acquisition sources, and above all, making a return on investment, you’re on the right path to great website conversion. The great thing is that Google Analytics is free to use… so what are you waiting for? Go forth and find out how your website is performing!

Do you use Google Analytics in your website conversion strategy? Do you still struggle with deciphering those stats and putting a plan together? If not, what advice do you have for newbies just hooking their website’s up to Google Analytics?

The post What Do You Do After You First Apply Google Anayltics to Your Website? appeared first on Diamond Website Conversion.

The Essential Guide To Error Tracking Using Google Analytics

Oft overlooked, error tracking is one of the most valuable ways to use Google Analytics. This essential guide covers how to use Google Analytics to track:

(click a link to jump ahead)

Using:

  • Google Tag Manager
  • Universal Analytics
  • Classic Google Analytics

404 Errors

Tracking 404s is great for:

  • Finding broken links (internal and external)
  • Proactively catching broken functionality
  • Tidying up older site architecture

Use Events to capture the previous page of the visit and the complete location of where the 404 occured. These are available at document.referrer and document.location.href, respectively. These two pieces of information can let you track down exactly where the offending link happens to be; capture these instead of relying on the ‘Page’ or ‘Full Referrer’ dimension in Google Analytics. Those values can easily be altered by filters, campaign parameters, or by other features built into Google Analytics.

FOR GOOGLE TAG MANAGER:

If you’re using Google Tag Manager, checking the title element for the default ‘404’ text is a sturdy test to fire a tracking event. Something like {{title}} equals '404 Page' or {{title}} contains '404 Page', as recommended by Samantha Barnes in her excellent guide to capturing 404 metrics with Google Tag Manager. You can also reference other tags that are on the page – be creative and find a standard value to watch for.

If that’s not possible, you’ll need to get your developers to populate the dataLayer with an event that you can watch for in Tag Manager, like:

var dataLayer = dataLayer||[];
dataLayer.push({'event':'404 Error'});

Then, you add a rule that watches for the 404 Error event, like so:

Then you create a Google Analytics Event tag and populate the Event Action and Event Label with the full URL of the page and the referrer.

As a best practice, I recommend that you try and decouple the mechanism that fires the event into Google Analytics from the actual event. Doing this means you can use a single ‘generic event’ tag to handle the processing of all of your events, and instead just push data into the dataLayer for the event tag to reference. For example:

In the above, each macro simply returns a corresponding dataLayer variable for an event value. It watches for ‘event’:’eventFired’ in the dataLayer. To generate a 404 event, all that needs to happen is the following be pushed into the dataLayer:

var referrer = document.referrer;
if (referrer === '') {
  referrer = 'No Referrer';
}
dataLayer.push({
  'event': 'eventFired',
  'eventCategory': '404 Error',
  'eventAction': document.location.href,
  'eventLabel': referrer,
  'eventValue': 0,
  'eventNonInteraction': true
});

This pattern makes adding future events a snap – all you have to do is push the ‘eventFired’ event into the dataLayer with the corresponding data; no need to create a whole new Google Analytics event tag.

If you’re not using Google Tag Manager, you’ll have to manually fire these events into Google Analytics. You can either include the following code as part of the 404 page template, or add it wrapped in a test into the header of each page on your site, e.g.:

if (document.title === 'Oops! You've found a 404 Page') {
  // Appropriate event tracking code from below goes here
}

FOR UNIVERSAL ANALYTICS:

var referrer = document.referrer;
if (referrer === '') {
  referrer = 'No Referrer';
}
ga('send', 'event', '404 Error', document.location.href, referrer, 0, {'nonInteraction': true});

FOR CLASSIC GOOGLE ANALYTICS:

var referrer = document.referrer;
if (referrer === '') {
  referrer = 'No Referrer';
}
_gaq.push(['_trackEvent','404 Pages', document.location.href, referrer, 0, true]);

JavaScript Errors

JavaScript errors are errors that the browser throws while executing the code that you’ve delivered to it. There are many common causes for JavaScript errors – browser compatibility, coding mistakes, and namespace collisions, to name a few. Tracking JavaScript errors can help you ensure a consistent user experience across browsers, catch bugs that were missed during development, and gauge the impact an error is truly having on users so that a fix can be appropriately prioritized.

FOR GOOGLE TAG MANAGER:

It’s your lucky day. Google Tag Manager offers a JavaScript Error Listener right out of the box. Just select ‘JavaScript Error Listener’ from the ‘Event Listeners’; I recommend you add this to every page.

Then, you’ll need to add another tag that listens for ‘gtm.pageError’ and uses the associated values to populate an Event for Analytics. I recommend reusing the pattern above for events, like this:

dataLayer.push({
  'event':'eventFired',
  'eventCategory': 'JS Errors',
  'eventAction': {{gtm.errorMessage}},
  'eventLabel': URL: {{href}} | File: {{gtm.errorUrl}} | Line: {{gtm.errorLineNumber}},
  'eventValue': 0,
  'eventNonInteraction': true
});

Otherwise, you’ll have to create another tag specifically for turning errors into events, like this:

I make the Event Action the gtm.errorMessage value and the Event Label URL: {{href}} | File: {{gtm.errorUrl}} | Line: {{gtm.errorLineNumber}}. This makes an for an easy-to-read format that can be drilled into for deeper context.

FOR UNIVERSAL ANALYTICS & CLASSIC ANALYTICS:

To track errors in the browser, you’ll need to bind an event listener to the window.onerror event that will generate a hit to send to Google Analytics. Doing this in a 100% backwards-compatible, error-free way can be super tricky, but here’s a copy-and-paste-friendly snippet you could utilize that should work with most browsers and Google Analytics configurations. Feel free to copy and modify to your tastes:

if (typeof window.onerror === 'object' && window.onerror === null) {  // Checks if this seat is taken/exists
  window.onerror = function(message, file, lineNumber) {
    if (typeof ga === 'object') {  // Detects Universal Analytics
      ga('send','event','JS Error', message, 'URL: ' + document.location.href + '| File: ' + file + '| Line: ' + lineNumber, 0, {'nonInteraction': true});
    } else if (typeof _gaq === 'object') {  // Detects Classic Analytics
      _gaq.push(['_trackEvent','JS Error', message, 'URL: ' + document.location.href + '| File: ' + file + '| Line: ' + lineNumber, 0, true]);
    }
  }
}

Server-side Errors

Sending application error data into Google Analytics directly from your server let’s you connect backend performance with front-end behavior. It can also contextualize seemingly unconnected issues across your site.

FOR GOOGLE TAG MANAGER:

Although technically not server-side, you could expose some error information into the dataLayer and then pass it into Google Analytics. On your server, this might look something like:

var dataLayer = dataLayer||[];
<?php
foreach ( $err in $errors ) { ?>
  dataLayer.push({
    'event': 'eventFired',
    'eventCategory': 'Server Error',
    'eventAction': '<?php echo $err->errno . $err->errstr ?>',
    'eventLabel': 'URL: ' + {{href}} + '| File: <?php echo $err->errfile ?> | Line: <?php echo $err->errline ?>';
  });
<?php } ?>

And on the client, you’d see:

<script>
  var dataLayer = dataLayer||[];
  dataLayer.push({
    'event': 'eventFired',
    'eventCategory': 'Server Error',
    'eventAction': 'Fatal error: Undefined class constant "MYSQL_ATTR_USE_BUFFERED_QUERY"'
    'eventLabel': 'URL: http://example.com/test/ | File: /local/www/example.com/includes/database/mysql/database.inc | Line: 43',
    'eventValue': 0,
    'eventNonInteraction': true
  });
</script>

Sidenote:

You’ll notice me using the syntax var dataLayer = dataLayer||[]; and then using dataLayer.push({}) in order to populate the dataLayer in my code; I recommend this as best practice to avoid accidentally overwriting needed information in the dataLayer. Basically, this is read by the browser as ‘The dataLayer is equal to itself, or it’s an empty array’. If the dataLayer doesn’t exists, the next section of the ‘OR’ (||) statement is evaluated, namely ‘dataLayer is an empty array’. In this way, if it exists, it will preserve itself, and if it doesn’t, it will create a new array named dataLayer for us to use.

Not instantiating dataLayer in this way can lead to problems if your code gets messy. For example, if you’re loading the dataLayer at the top of the page, then server errors inside the <content> of the page, this could happen:

<!-- Other HTML -->
<script>
  var dataLayer = [{'PageType':'Local'}, {'timestamp': 2849200492}];
  console.log(dataLayer); // Logs '[ { "PageType": "Local" }, {'timestamp': 2849200492} ]'
</script>
<!-- Other HTML -->
<script>
  var dataLayer = [{'event': 'Server Error'}];
  console.log(dataLayer); // Logs '[ { "event": "Server Error" } ]'
</script>

Should you need to reference either the PageType or timestamp values later, they would return undefined. Using dataLayer = dataLayer||[]; and then dataLayer.push() instead of just instantiating the dataLayer prevents this from happening.

FOR UNIVERSAL ANALYTICS:

The Universal Analytics Measurement Protocol provides a relatively painless way to send hits to Google Analytics directly from your server. All it takes is a POST request, which can be pretty simple to put together. Here’s a quick and dirty example using NodeJS:

var http = require('http');

function fireMeasurementProtocolEvent(category, action, label, value, nonInteraction, cid) {

  var ni = !nonInteraction ? '1' : '0';

  var eventData = "?v=1&tid=UA-XXXXXXX-XX&t=event&cid=" + cid + "&ec=" + category + "&ea=" + action + "&el=" + label + "&ev=" + value + "&ni=" + ni;

  var payload = {

    'hostname': 'www.google-analytics.com',
    'path': '/collect' + eventData,
    'method': 'POST'

  };

  var req = http.request(payload);
  req.end();

};

FOR CLASSIC GOOGLE ANALYTICS:

The truly intrepid can manufacturer fake __utm.gif requests – all you need to do is generate a GET request to http://www.google-analytics.com/__utm.gif with the correct parameters appended to the request. Here’s a great reference from Google on how to do just that.

Modal & Dialog Errors

Finally, a great ‘error’ type that I like to catch is any kind of modal or error dialog presented to a user. Even mundane error messages can reveal more sinister patterns lurking underneath. Tracking and analyzing common site messages is essential for good site hygiene.

FOR GOOGLE TAG MANAGER:

Either create an event tag and a macro to grab the text of the modal, or using the generic tracking event outlined above:

var modal = document.getElementById('modal-message');
dataLayer.push({
  'event': 'eventFired',
  'eventCategory': 'Error Modal',
  'eventAction': modal.textContent,
  'eventLabel': '',
  'eventValue':0,
  'eventNonInteraction': true
});

FOR UNIVERSAL ANALYTICS:

var modal = document.getElementById('modal-message');
ga('send', 'event', 'Error Modal', modal.textContent, '', 0, {'nonInteraction': true});

FOR CLASSIC GOOGLE ANALYTICS:

var modal = document.getElementById('modal-message');
_gaq.push(['_trackEvent','Error Modal', modal.textContent, '', 0, true]);

Have any error-collecting techniques of your own that I missed? Tweet them to me at @notdanwilkerson.

Oft overlooked, error tracking is one of the most valuable ways to use Google Analytics. This essential guide covers how to use Google Analytics to track:

(click a link to jump ahead)

Using:

  • Google Tag Manager
  • Universal Analytics
  • Classic Google Analytics

404 Errors

Tracking 404s is great for:

  • Finding broken links (internal and external)
  • Proactively catching broken functionality
  • Tidying up older site architecture

Use Events to capture the previous page of the visit and the complete location of where the 404 occured. These are available at document.referrer and document.location.href, respectively. These two pieces of information can let you track down exactly where the offending link happens to be; capture these instead of relying on the 'Page' or 'Full Referrer' dimension in Google Analytics. Those values can easily be altered by filters, campaign parameters, or by other features built into Google Analytics.

FOR GOOGLE TAG MANAGER:

If you're using Google Tag Manager, checking the title element for the default '404' text is a sturdy test to fire a tracking event. Something like {{title}} equals '404 Page' or {{title}} contains '404 Page', as recommended by Samantha Barnes in her excellent guide to capturing 404 metrics with Google Tag Manager. You can also reference other tags that are on the page - be creative and find a standard value to watch for.

If that's not possible, you'll need to get your developers to populate the dataLayer with an event that you can watch for in Tag Manager, like:

var dataLayer = dataLayer||[];
dataLayer.push({'event':'404 Error'});

Then, you add a rule that watches for the 404 Error event, like so:

Then you create a Google Analytics Event tag and populate the Event Action and Event Label with the full URL of the page and the referrer.

As a best practice, I recommend that you try and decouple the mechanism that fires the event into Google Analytics from the actual event. Doing this means you can use a single 'generic event' tag to handle the processing of all of your events, and instead just push data into the dataLayer for the event tag to reference. For example:

In the above, each macro simply returns a corresponding dataLayer variable for an event value. It watches for 'event':'eventFired' in the dataLayer. To generate a 404 event, all that needs to happen is the following be pushed into the dataLayer:

var referrer = document.referrer;
if (referrer === '') {
  referrer = 'No Referrer';
}
dataLayer.push({
  'event': 'eventFired',
  'eventCategory': '404 Error',
  'eventAction': document.location.href,
  'eventLabel': referrer,
  'eventValue': 0,
  'eventNonInteraction': true
});

This pattern makes adding future events a snap - all you have to do is push the 'eventFired' event into the dataLayer with the corresponding data; no need to create a whole new Google Analytics event tag.

If you're not using Google Tag Manager, you'll have to manually fire these events into Google Analytics. You can either include the following code as part of the 404 page template, or add it wrapped in a test into the header of each page on your site, e.g.:

if (document.title === 'Oops! You've found a 404 Page') {
  // Appropriate event tracking code from below goes here
}

FOR UNIVERSAL ANALYTICS:

var referrer = document.referrer;
if (referrer === '') {
  referrer = 'No Referrer';
}
ga('send', 'event', '404 Error', document.location.href, referrer, 0, {'nonInteraction': true});

FOR CLASSIC GOOGLE ANALYTICS:

var referrer = document.referrer;
if (referrer === '') {
  referrer = 'No Referrer';
}
_gaq.push(['_trackEvent','404 Pages', document.location.href, referrer, 0, true]);

JavaScript Errors

JavaScript errors are errors that the browser throws while executing the code that you've delivered to it. There are many common causes for JavaScript errors - browser compatibility, coding mistakes, and namespace collisions, to name a few. Tracking JavaScript errors can help you ensure a consistent user experience across browsers, catch bugs that were missed during development, and gauge the impact an error is truly having on users so that a fix can be appropriately prioritized.

FOR GOOGLE TAG MANAGER:

It's your lucky day. Google Tag Manager offers a JavaScript Error Listener right out of the box. Just select 'JavaScript Error Listener' from the 'Event Listeners'; I recommend you add this to every page.

Then, you'll need to add another tag that listens for 'gtm.pageError' and uses the associated values to populate an Event for Analytics. I recommend reusing the pattern above for events, like this:

dataLayer.push({
  'event':'eventFired',
  'eventCategory': 'JS Errors',
  'eventAction': {{gtm.errorMessage}},
  'eventLabel': URL: {{href}} | File: {{gtm.errorUrl}} | Line: {{gtm.errorLineNumber}},
  'eventValue': 0,
  'eventNonInteraction': true
});

Otherwise, you'll have to create another tag specifically for turning errors into events, like this:

I make the Event Action the gtm.errorMessage value and the Event Label URL: {{href}} | File: {{gtm.errorUrl}} | Line: {{gtm.errorLineNumber}}. This makes an for an easy-to-read format that can be drilled into for deeper context.

FOR UNIVERSAL ANALYTICS & CLASSIC ANALYTICS:

To track errors in the browser, you'll need to bind an event listener to the window.onerror event that will generate a hit to send to Google Analytics. Doing this in a 100% backwards-compatible, error-free way can be super tricky, but here's a copy-and-paste-friendly snippet you could utilize that should work with most browsers and Google Analytics configurations. Feel free to copy and modify to your tastes:

if (typeof window.onerror === 'object' && window.onerror === null) {  // Checks if this seat is taken/exists
  window.onerror = function(message, file, lineNumber) {
    if (typeof ga === 'object') {  // Detects Universal Analytics
      ga('send','event','JS Error', message, 'URL: ' + document.location.href + '| File: ' + file + '| Line: ' + lineNumber, 0, {'nonInteraction': true});
    } else if (typeof _gaq === 'object') {  // Detects Classic Analytics
      _gaq.push(['_trackEvent','JS Error', message, 'URL: ' + document.location.href + '| File: ' + file + '| Line: ' + lineNumber, 0, true]);
    }
  }
}

Server-side Errors

Sending application error data into Google Analytics directly from your server let's you connect backend performance with front-end behavior. It can also contextualize seemingly unconnected issues across your site.

FOR GOOGLE TAG MANAGER:

Although technically not server-side, you could expose some error information into the dataLayer and then pass it into Google Analytics. On your server, this might look something like:

var dataLayer = dataLayer||[];
<?php
foreach ( $err in $errors ) { ?>
  dataLayer.push({
    'event': 'eventFired',
    'eventCategory': 'Server Error',
    'eventAction': '<?php echo $err->errno . $err->errstr ?>',
    'eventLabel': 'URL: ' + {{href}} + '| File: <?php echo $err->errfile ?> | Line: <?php echo $err->errline ?>';
  });
<?php } ?>

And on the client, you'd see:

<script>
  var dataLayer = dataLayer||[];
  dataLayer.push({
    'event': 'eventFired',
    'eventCategory': 'Server Error',
    'eventAction': 'Fatal error: Undefined class constant "MYSQL_ATTR_USE_BUFFERED_QUERY"'
    'eventLabel': 'URL: http://example.com/test/ | File: /local/www/example.com/includes/database/mysql/database.inc | Line: 43',
    'eventValue': 0,
    'eventNonInteraction': true
  });
</script>

Sidenote:

You'll notice me using the syntax var dataLayer = dataLayer||[]; and then using dataLayer.push({}) in order to populate the dataLayer in my code; I recommend this as best practice to avoid accidentally overwriting needed information in the dataLayer. Basically, this is read by the browser as 'The dataLayer is equal to itself, or it's an empty array'. If the dataLayer doesn't exists, the next section of the 'OR' (||) statement is evaluated, namely 'dataLayer is an empty array'. In this way, if it exists, it will preserve itself, and if it doesn't, it will create a new array named dataLayer for us to use.

Not instantiating dataLayer in this way can lead to problems if your code gets messy. For example, if you're loading the dataLayer at the top of the page, then server errors inside the <content> of the page, this could happen:

<!-- Other HTML -->
<script>
  var dataLayer = [{'PageType':'Local'}, {'timestamp': 2849200492}];
  console.log(dataLayer); // Logs '[ { "PageType": "Local" }, {'timestamp': 2849200492} ]'
</script>
<!-- Other HTML -->
<script>
  var dataLayer = [{'event': 'Server Error'}];
  console.log(dataLayer); // Logs '[ { "event": "Server Error" } ]'
</script>

Should you need to reference either the PageType or timestamp values later, they would return undefined. Using dataLayer = dataLayer||[]; and then dataLayer.push() instead of just instantiating the dataLayer prevents this from happening.

FOR UNIVERSAL ANALYTICS:

The Universal Analytics Measurement Protocol provides a relatively painless way to send hits to Google Analytics directly from your server. All it takes is a POST request, which can be pretty simple to put together. Here's a quick and dirty example using NodeJS:

var http = require('http');

function fireMeasurementProtocolEvent(category, action, label, value, nonInteraction, cid) {

  var ni = !nonInteraction ? '1' : '0';

  var eventData = "?v=1&tid=UA-XXXXXXX-XX&t=event&cid=" + cid + "&ec=" + category + "&ea=" + action + "&el=" + label + "&ev=" + value + "&ni=" + ni;

  var payload = {

    'hostname': 'www.google-analytics.com',
    'path': '/collect' + eventData,
    'method': 'POST'

  };

  var req = http.request(payload);
  req.end();

};

FOR CLASSIC GOOGLE ANALYTICS:

The truly intrepid can manufacturer fake __utm.gif requests - all you need to do is generate a GET request to http://www.google-analytics.com/__utm.gif with the correct parameters appended to the request. Here's a great reference from Google on how to do just that.

Modal & Dialog Errors

Finally, a great 'error' type that I like to catch is any kind of modal or error dialog presented to a user. Even mundane error messages can reveal more sinister patterns lurking underneath. Tracking and analyzing common site messages is essential for good site hygiene.

FOR GOOGLE TAG MANAGER:

Either create an event tag and a macro to grab the text of the modal, or using the generic tracking event outlined above:

var modal = document.getElementById('modal-message');
dataLayer.push({
  'event': 'eventFired',
  'eventCategory': 'Error Modal',
  'eventAction': modal.textContent,
  'eventLabel': '',
  'eventValue':0,
  'eventNonInteraction': true
});

FOR UNIVERSAL ANALYTICS:

var modal = document.getElementById('modal-message');
ga('send', 'event', 'Error Modal', modal.textContent, '', 0, {'nonInteraction': true});

FOR CLASSIC GOOGLE ANALYTICS:

var modal = document.getElementById('modal-message');
_gaq.push(['_trackEvent','Error Modal', modal.textContent, '', 0, true]);

Have any error-collecting techniques of your own that I missed? Tweet them to me at @notdanwilkerson.

Heartbleed Bug Vulnerability Detection and Correction

For those who may not know, I write most of my posts over at one of my newer sites The Ecommerce Expert now. Most of my activity has moved there so be sure to head on over and subscribe to get the latest updates. With that said, I thought it would be i…

For those who may not know, I write most of my posts over at one of my newer sites The Ecommerce Expert now. Most of my activity has moved there so be sure to head on over and subscribe to get the latest updates. With that said, I thought it would be important to post […]

Heartbleed Bug Vulnerability Detection and Correction is an article taken from: Ecommerce Optimization & Marketing protected under copyright law. Reproduction in any form without consent is strictly prohibited.

If you want to find out how to increase your website conversion, increase sales, and win more customers you should visit the original Ecommerce Optimization site.

The post Heartbleed Bug Vulnerability Detection and Correction appeared first on Ecommerce Optimization & Marketing.

Understanding Cross Device Measurement and the User-ID

One of the fundamental new features of Universal Analytics is user-centric measurement. This includes measurement across multiple devices – computers, smart phones, tablets, kiosks, etc. But this change introduces a number of new challenges for analysts and marketers. In order to do cross device measurement you need to understand some of the challenges and limitation. […]

Understanding Cross Device Measurement and the User-ID is a post from: Analytics Talk by Justin Cutroni

The post Understanding Cross Device Measurement and the User-ID appeared first on Analytics Talk.

One of the fundamental new features of Universal Analytics is user-centric measurement. This includes measurement across multiple devices – computers, smart phones, tablets, kiosks, etc.

The User-ID feature let's you measure the user journey across multiple devices - and even in stores.

But this change introduces a number of new challenges for analysts and marketers. In order to do cross device measurement you need to understand some of the challenges and limitation. Let’s begin our exploration of cross device data with a discussion about how it works.

How Cross Device Measurement Works

You’ll recall that most analytics tools set an anonymous identifier to measure users. On websites the JavaScript code creates the identifier and stores it in a cookie. On mobile apps the SDK creates the identifier and stores it in a database on the device. (We call this default ID the Client-ID).

We actually discussed this concept in our Google Analytics Platform Principles course. Skip to 21 seconds for details – but the whole video is helpful :)

The User-ID feature lets you override this default behavior. So rather than letting the tracking code create the a Client-ID, YOU can create and use your own identifier. How do you do that?

Well, your business needs to have some way of identifying users. Don’t worry, most businesses do. A CRM system or customer database usually has a User-ID that you can use.

The important thing is that you can create the technology that moves the ID from your database into your website, app or other digital experience where your users interact with your content.

The User-ID value must originate from your systems. It must eventually appear in the tracking code on your site or in your app. The User-ID will then be sent to Google Analytics  with each data hit.

The User-ID value must originate from your systems. It must eventually appear in the tracking code on your site or in your app. The User-ID will then be sent to Google Analytics with each data hit.

In the above diagram the company would need to create code that pulls the User-ID from the database, then passes it through the web servers, and finally places it in the Google Analytics Tracking code that appears on the website.

I know – that seems like a lot of work! But a good tech person can make this happen.

After you add all the necessary code, and set up the User-ID feature in Google Analytics, then the actual id value that you supply is sent to Google Analytics with each hit (see my post on hits, sessions and users to learn about all the different hit types in Google Analytics.)

Then, as Google Analytics processes the data, it groups hits with the same User-ID together. It does not matter if the hits come from a website, mobile app or some other device.

Hits from the same user can be grouped together as long as each hit has the same User-ID.

Hits from the same user can be grouped together as long as each hit has the same User-ID.

In the above image there would be three unique users – one user with a User-ID=1, one user with a User-ID=2 and one user with a User-ID=5. Again – it doesn’t matter where the hits come from (mobile, web, kiosk, etc.).

But what about instances when the User-ID is not present? For example, what if the user is not logged in and we can not retrieve the User-ID? Good question.

In this case, Google Analytics will go back to its default behavior and generate it’s own User-ID (again, this is called a Client-ID, because the ID is specific to the client or device). Obviously this ID can not be used to measure across devices as it will only exist on the device where it is set.

But now we have a scenario where a user might have two different User-ID numbers for a single user? Isn’t this going to have an impact on the data? Aren’t we trying to avoid that? This sucks!

Well – it’s not that simple. Let’s talk about something called Session Unification.

Session Unification

The above scenario is very common. You will not always be able to set the User-ID in Google Analytics – even for known users. The result is some hits and sessions will have a User-ID value, and some with an automatically generated User-ID value.

It's not always possible to send your own User-ID to Google Analytics.

It’s not always possible to send your own User-ID to Google Analytics.

Google Analytics has a feature called Session Unification. When activated, it will unify, or group, hits with the manually set User-ID and hits with an auto-generated User-ID together. This means that Google Analytics can associate some hits that were received prior to setting the User-ID.

Here’s the definition of Session Unification from the Google Analytics Help center (I think it’s pretty good!):

Session unification allows hits collected before the User-ID is assigned to be associated with the ID, as long as those hits happen within the same session in which a specific ID value is assigned for the first time.

This means that Google Analytics will only associate hits collected in the same session AND it must be in the first session where the User-ID is set.

This functionality is sometimes called “stitching” – and it differs from one tool to another.

Google Analytics will not go back in time and stitch every single session from a given user together. I can hear the groans now – and the comparisons to other tools. I hope to write about session unification in a later post. But I think a lot of people that are going to complain about this are missing the point. It’s not “can we stitch data together” it’s “should we stitch data together?”. Rant over.

So how does Session Unification impact the data? Well, to understand that we need to talk about another topic the User-ID View and reports.

The User-ID View

We all know the basic hierarchy of a Google Analytics account. Within your account you can create a number of properties. Under a property you can create a number of views – which were formerly called profiles.

Now you can designate certain views as User-ID views. This means that the view will be filtered and the only data in this view is data that contains hits where you set the User-ID value.

Only a Google Analytics view with User-ID enabled will display information about cross-device users.

Only a Google Analytics view with User-ID enabled will display information about cross-device users.

Obviously this view will have less data than a standard view where the User-ID is not enabled. But the idea is that this view will be able to provide deeper insights into how users who are logged in – a VERY valuable segment of your users – interact with your business across multiple devices.

To view all of the data, hits with and without a User-ID, you would use a standard view.

Let’s also consider the scenario from above – when a manually set User-ID is present in some sessions, but not others. The result is that the data from sessions without your User-ID will not be in the User-ID view.

Only hits that contain a manually set User-ID will be included in a User-ID view.

Only hits that contain a manually set User-ID will be included in a User-ID view.

There are also some other significant differences between views that do, and do not, have User-ID feature enabled.

1. Certain metrics are calculated differently. Obviously if a User-ID view contains different data, then certain metrics will be calculated differently.

For example, the number of Users is calculated based on the number of unique User-ID values. This will provide a fairly accurate view of the number of users. It will probably be less than the number of users in a standard view because that that view will also include users where you do not set a User-ID.

2. Cross device reports. This is the HUGE benefit of a User-ID view. These reports provide some awesome insights into how users access your content from multiple devices. More info about the reports below.

3. Limited date range. When working with a User-ID view you can only change the date range to the past 90 days. This is consistent with the standard 90-day user look-back window in other features, like Multi-Channel Funnels and user segments.

Implementing Cross Device Measurement

Implementing the User-ID feature can be involved, depending on your specific infrastructure. Here’s a brief overview of the process.

1. First, you need to “turn on” the user ID feature for a given property.

2. Second, you need to add the actual user ID value to the data collection. For website, this means you need to modify the JavaScript tracking code. For mobile apps you need to change the SDK.

3. Third, create a User-ID view. This is a special data view that includes new reports.

Let’s get into a bit more detail.

1. Enable User-ID Feature

This is really important to read and understand the terms. For example, it’s important to note that you can not use personally identifiable information as the User-ID. This includes an email address, name, etc.

To use the User-ID feature you must read the User-ID policy and agree to the terms.

To use the User-ID feature you must read the User-ID policy and agree to the terms.

You also really need to take a look at your own privacy policy and make sure it complies with the following:

You will give your end users proper notice about the implementations and features of Google Analytics you use (e.g. notice about what data you will collect via Google Analytics, and whether this data can be connected to other data you have about the end user). You will either get consent from your end users, or provide them with the opportunity to opt-out from the implementations and features you use.

2. Implement User-ID in your Tracking Code

Now for the coding! Go get your nerds and Red Bull! Just kidding.

As I mentioned above, the User-ID value must come from you. You must generate the ID from one of your systems. Once you do that you must place it inside the tracking code. The hard part is writing the code that moves the User-ID from your systems and puts it in {{ USER_ID }} in the code snippets below..

Let’s look at some of the most common code formats.

Adding the User-ID to website tracking

Adding a User-ID to the JavaScript code is fairly easy – it’s a single line.

ga('create', 'UA-XXXX-Y', 'auto');
ga('set', '&uid', {{ USER_ID }});
ga('send', 'pageview');

Remember, the User-ID needs to be set before any hits are sent to Google Analytics. So make sure you call the set command before a pageview, event, transaction, etc. is sent.

It’s also recommended that you include the set method on ALL of the pages, not just one page.

See the developer docs for more about JavaScript information.

Adding the User-ID to the Android SDK

t.set("&uid", {{ USER_ID }});

See the developer docs for more Android information.

Adding the User-ID to the iOS SDK

[tracker set:@"&uid" value:{{ USER_ID }}];

See the developer docs for more iOS information.

For both the Android code and the iOS code, you only need to set the User-ID once. Once it is set once the User-ID will be sent with all subsequent hits. But try to set it before any hit is sent to Google Analytics.

Adding the User-ID to the Measurement Protocol

Adding the User-ID to a measurement protocol hit is actually really easy. All you need to do is add the uid parameter in each hit. So a hit might look something like this:

http://www.google-analytics.com/collect?v=1&_v=j16&a=164718749&t=pageview&_s=1&dl=http%3A%2F%2Fcutroni.com%2F&ul=en-us&uid=hsjfy4782jduyth6k4

Adding the User-ID via Google Tag Manager

A quick note that you can also set the User-ID with Google Tag Manager. You’ll find the setting in the ‘More Settings > Fields to set’. You’ll also need to create a macro to pull the actual User-ID value from a cookie or the data layer.

You can set the User-ID value with Google Tag Manager.

You can set the User-ID value with Google Tag Manager.

In addition to adding the User-ID to your data collection code, you must also choose if you want to use Session Unification. See above for more information on session unification.

The second step in setting up the User-ID is to add the actual identifier to the tracking code for your site or app.

The second step in setting up the User-ID is to add the actual identifier to the tracking code for your site or app AND configuring the session unification setting.

Now it’s time to add a User-ID view.

3. Create a User ID View

As mentioned above, a User-ID view is a filtered view of your data. It only includes hits in which you have set the User-ID value. This view also contains reports that show cross device usage and other user-centric metrics.

Please note, this view is in ADDITION to the other views that you have for a property. This means that you will need to configure things like goals, filters custom reports, dashboards, etc. on this new view.

You must create a new User-ID view to see the Google Analytics cross device reports.

You must create a new User-ID view to see the Google Analytics cross device reports.

That’s really it. I don’t want to oversimplify the implementation. But most of the work is really creating the code that pulls your User-ID from your systems and then places it in the correct tracking code.

Data and Reports

We finally made it, let’s look at some data and figure out how we can use this.

Remember, in all of these reports we’re trying to understand the behavior of our users. And we’re not just looking at the behavior of everyone – we’re looking at the behavior of those users that have self identified. This is really important as this group is naturally very valuable.

User-ID Coverage

Let’s start by understanding what percentage of our users are actually logged in.

Remember, you’ll have two different profiles with data. One profile will just be all of the data, the other will be a User-ID profile that only contains information about logged in users.

The Coverage Report identifies the data that has a User-ID associate with it vs. the data that does not have a User-ID.

The User-ID Coverage report shows what percentage of your sessions have a User-ID associated with them.

The User-ID Coverage report shows what percentage of your sessions have a User-ID associated with them.

Remember, you’re probably not going to get 100% User-ID coverage – unless your online experience requires authentication. But this depends on your specific business and your specific implementation.

You can use this data to get a better understanding of how big your data pool is – will you be making decisions on 1% of sessions or 50%?

Device Overlap

Ok this is where we start to get into the really interesting data. Here’s a visualization that shows the device overlap. That means the percentage of users that use various combinations of devices.

Device overlap shows the number of users and the value of users based on combinations of devices.

Device overlap shows the number of users and the value of users based on combinations of devices.

Rather than just looking at how many people use certain combinations of devices, let’s look at the associated revenue from those combinations. Notice that you can change the display using the selector at the top of the chart?

The Device overlap report also includes detailed information about how combinations of devices drive value.

The Device overlap report also includes detailed information about how combinations of devices drive value.

So what’s the actionability here?

Do people who use a certain combination of devices behave differently than others? Are people who use tablet and desktop more valuable than those that use tablet and phone? If so – how do we encourage more of that behavior? Is it via marketing? Changes to the platform?

And don’t forget, you need to add a LOT of context to this data. You need to keep in mind your marketing initiatives along with the user experience that you offer your users on each device.

Device Pathing

Now let’s move on to device pathing. This report shows the device used for a sequence of sessions.

Device Pathing shows the user sequence of devices.

Device Pathing shows the user sequence of devices.

You can look at a specific path prior to, or after, a user action. The action could be a goal conversion, a pageview, a transaction or an event.

You can view the device path prior to, or after, specific user actions.

You can view the device path prior to, or after, specific user actions.

What’s the actionability here? Let’s look at a use-case.

If you have a SaaS business you may offer your users a free trial. In this case the user would create an account for the trial and then use your service. At the end of the trial they would need to upgrade to a real account.

The first thing you could do is look at the user’s device behavior after creating their free trial account. Did they perform any specific tasks on a specific device? Was one device more popular than another? If so maybe you can simplify the workflow on that device.

You could also look at the device path at the end of their trial, when they upgraded to a paying account. Did they perform the upgrade on a certain device? Or, more importantly, was the conversion rate higher on on a certain type of device? If so, you might want to simplify or optimize the process on that type of device.

Don’t forget to look back at the Device Overlap report to understand if a certain combination of devices yielded a more valuable customer.

Also notice that there are a lot of ways that you can configure this report to view different paths. One of the most important things to note is that you can not choose specific instances of each item. For example, if a user generates multiple transactions you can not choose a specific transaction.

You can choose to view the device path before or after various user actions.

You can choose to view the device path before or after various user actions.

My suggestion is to create a goal, page or unique event for the most important user actions – the ones that represent the transition from one phase of the customer lifecycle to another. That way you will always be able to see the device path before and after the action.

Device Acquisition Report

Finally we have the Acquisition Device report. This is similar to the Device Overlap report in that it helps you understand the value of users on a certain device. But the difference is that it shows the value based on the first device type.

Use the Device Acquisition report to understand if users acquired on a certain device generate revenue on the same device or different devices.

Use the Device Acquisition report to understand if users acquired on a certain device generate revenue on the same device or different devices.

What’s the actionability here? Do users acquired on a specific type of device generate more value on the same device or on other devices? If so how can you drive more of that behavior?

Segmentation

One final thing to mention. You may have noticed that you can apply segmentation to all of these reports. Segmentation will work the same in these reports as it does in all other GA reports.

If you create a session based segment then Google Analytics will show all the paths that include a session that meets your criteria.

If you create a user based segment then Google Analytics will show all of the paths generated from users that match your criteria.

Did you make it to the end? I hope this post gave you some insights into how Cross Device Measurement works. There’s going to be a lot of chatter about User-ID and cross device measurement – some positive, some negative. And I have a lot more to say – but this post is long enough!

Understanding Cross Device Measurement and the User-ID is a post from: Analytics Talk by Justin Cutroni

The post Understanding Cross Device Measurement and the User-ID appeared first on Analytics Talk.