Search code examples
javascriptgoogle-analyticsamp-htmlclientid

AMP Client ID Error


Trying to implement the CLIENT_ID variable at the moment (https://github.com/ampproject/amphtml/blob/master/spec/amp-var-substitutions.md#variable-substitution-in-links) so the link is:

<a id="get-started" href="https://subdomain.website.com/?client_id=CLIENT_ID(_ga)" data-amp-replace="CLIENT_ID">

We have also whitelisted the domain names:

<meta name="amp-link-variable-allowed-origin" content="https://www.website.com https://subdomain.website.com">

And then amended the GA code:

    <amp-analytics type="googleanalytics">
     <script type="application/json">
      {
        "vars": {
          "account": "UA-XXXXXXX-X"
        },
        "extraUrlParams": {
          "clientId": "${clientId(_ga)}"
        },
        "triggers": {
          "trackPageview": {
            "on": "visible",
            "request": "pageview"
          }
        }
      }
    </script>
   </amp-analytics>

The console is reporting these errors:

element-service.js:63 The first argument to CLIENT_ID, the fallback Cookie name, is required:  undefined
log.js:317 Uncaught Error: The first argument to CLIENT_ID, the fallback Cookie name, is required: undefined​​​

Solution

  • Use CLIENT_ID(_ga) instead:

    <script type="application/json">
    {
      "vars": {
        "account": "UA-XXXXXX-X"
    
      },
      "extraUrlParams": {
        "ampClientId": "CLIENT_ID(_ga)"
      },
      "triggers": {
        "trackPageview": {
          "on": "visible",
          "request": "pageview"
        }
      }
    }
    </script>
    

    It's important to note what is happening here:

    When using the CLIENT_ID(_ga) we're actually telling AMP analytics to generate a cookie named _ga and then we use it as the extraUrlParams which get concatenated to the URL.

    It's important to note that we could create any cookie with this method, so if we would want to use a different analytics vendor we could generate whatever cookie we need, for example:

    CLIENT_ID(some_random_cookie) would set a cookie named some_random_cookie with the amp_client_id (some hash) as the value.