How To Implement Google Analytics Using AMP

December 08, 2015
By Dan Wilkerson

blog-implement-ga-using-amp-tinypng

AMP, or the Accelerated Mobile Pages Project, is an open-source project pioneered by Google aimed at increasing the speed of the mobile web. In essence, publishers trade configurability and custom “look-ma-no-hands” features for a predefined set of components. In return, they get super-snappy page load times, generous 3rd-party caching, and prominent placement in mobile SERPs.

AMP does support the addition of web analytics, albeit in a stripped down fashion. In order to get started, you’ll need to include the web analytics component in your AMP pages. Add the following snippet in the head of your AMP template, before the snippet for the AMP JS library.

Configuration

The analytics component offers a wealth of configuration options. These options make it easy to extend AMP to handle your specific tracking needs. Because the project is continuing to evolve, we’ll skip going into the specifics and instead point you to the Google Analytics and AMP documentation for the component. Ultimately, your configuration snippet should look something like this:



One additional feature to be aware of is the ability to specify a configuration file. This file is not cached by AMP, and can be used to supply user-, session-, or hit-specific information. You can even deliver on-the-fly triggers and hit customizations using this file; they will overrule existing configurations in the HTML of the AMP page. To use a configuration file, you must set the config attribute on the AMP component.

For a deep dive into configuration files, check out the official documentation.

Best Practices

A few recommendations I would like to share for those of you setting out to integrate your Google Analytics with your AMP HTML pages.

Property Selection

The current recommendation from Google is to use a separate property ID for measuring AMP-specific activity. This recommendation stems from the fact that AMP analytics will measure things differently than analytics.js. This is especially true of Client IDs, which AMP will endeavor to create on your behalf and store in a totally different pattern than the typical tracking code.

Using the same property as you use for your normal, everyday reporting can cause some problematic data to appear when running reports. For now, we would recommend creating a new, AMP-specific property for your reporting needs. For roll-up reporting, use a Premium Rollup Property or BigQuery and join together user data based on the Client ID (more on this in a second). If you’re not a Google Analytics 360 (née Premium) user, you’ll have to decide if complete data is more important than tracking users across your AMP pages, or you’ll need to create a manual rollup property and duplicate your hits.

Client IDs

As mentioned in the above, by default, AMP will take it upon itself to generate a Client ID, even if one exists in an _ga cookie on the host the content is being served from (this can be overridden, though). However, we’d like to use the same Client ID for a visitor for our AMP-generated hits and our normal website. This is desirable because a user may visit a non-AMP page and already be assigned a Client ID in Google Analytics. An easy way to accomplish this is to reflect any stored Client ID into the configuration JSON file that we set on the config attribute of the analytics component. This can be retrieved from the Cookie header of the request the browser generates for that configuration file.

// Node.js/Express pseudocode example
app.get('/some/path/to/config.json', function(req, res) {

  var json = generateAmpJson();
  var clientId;

  try {
    var gaCookie = req.cookie._ga;
    clientId = gaCookie.match(/\d+?\.\d+$/)[0];
  } catch (e) {
    clientId = generateClientId();  // Default is an unsigned 32-bit integer and a timestamp
    // Requires setting the data-credentials attribute to "include" on your amp-analytics component
    // Actual cookie value will vary depending on your configuration
    res.append('Set-Cookie', '_ga=1.2' + clientId + '; Path=/; Domain=example.com; Expires=' + twoYearsFromNow());
  }

  json.clientId = clientId;

  res.send(json);

});

Update: If you’d like to generate your own client IDs in the same format as analytics.js, here’s a helpful snippet I wrote that will do just that. The amp-analytics vendor configuration for Google Analytics now supports overriding CIDs, too, by setting the clientId var. The snippet above has been updated to reflect this.

As always, we recommend storing the Client ID in a Custom Dimension for easier mixing and matching with other data sets. This approach ensures consistent user identification, even if the user is visiting a cached version of our AMP page on a 3rd party domain (like in the Google search results).

Additional Dimensions

AMP will try and detect most of the dimensions we expect with our Google Analytics hits, including things like our Page Title and Page URL. For best results, you may want to hardcode the Page Title and desired reporting URL in your configuration file. You may also want to set additional pieces of information with your AMP hit, like Content Groupings or Custom Dimensions. Spend some time examining the data you currently send for your content on your desktop site and try and emulate as many of those values as possible.