This article describes a solution on how to implement Google Analytics on AMP (Accelerated Mobile Pages) using a consistent cross-domain GA client id. Using such a solution will allow a correct tracking of users on your own website and on possible AMP cache servers.

If you want to track visitors and their interactions on AMP pages using Google Analytics, you might have realized that there are some difficulties. The biggest problem is the fact that AMP pages might be cached on foreign servers like amp.cloudflare.com or cdn.ampproject.org. Therefore, you cannot just use the usual first party cookie to store the GA client id. If you would do so, you would not be able to identify the same user across your own website and possible AMP cache servers. To solve this problem, you can complete the following steps:

  1. Setup a Google Tag Manager container for your AMP pages
  2. Configure your GA pageview tracking tags and publish the container
  3. Implement a server-side script on your main website domain (PHP, ASP.NET, Servlet, ...) that performs the following tasks
    • Check if _ga cookie exists
    • If the _ga cookie exists, extract the GA client id (last two dot separated numbers)
    • If the _ga cookie does not exist, generate a new client id and set the 1st party cookie (_ga cookie value = "1.2." + random client id + "." + current timestamp)
    • Download the GTM AMP container JSON file from the Google Server (https://www.googletagmanager.com/amp.json?id=GTM-XXXXXX>m.url=SOURCE_URL)
    • Replace the string "CLIENT_ID(AMP_ECID_GOOGLE,,_ga)" in the JSON data with the GA client id
    • Return the modified JSON data
  4. Finally implement the container on your AMP pages, but load it from your own server-side script URL instead of the googletagmanager.com URL

Now you have a working solution that tracks the users across AMP cache servers and your own domain!

 

Cookies make it easier for us to provide you with our services. With the usage of our services you permit us to use cookies.
More information Ok