How to Unify AMP and Non-AMP Pages Into One Amplitude Event Stream

A simple JavaScript snippet can help you to overcome, at least partially, another hurdle introduced by AMP to product analytics work.

AMP is a great way to improve page experience and speed, and hence to rank better in Google search results. But it has its drawbacks, for example, it makes product analytics work cumbersome. To start with, not all analytics providers even have AMP support. Luckily, Amplitude has AMP support, and it is a great tool. But even with AMP support, it’s not all roses.

Amplitude doesn’t unify AMP and non-AMP into the same user’s event stream

Even if you choose to use AMP, many times you will have to disable it on some pages, for example, a checkout page. For these non-AMP pages, you will have to implement and use Amplitude’s regular JavaScript SDK. That’s not a big deal for itself, but the problem is that out-of-the-box Amplitude doesn’t assign AMP and non-AMP events to the same user. Amplitude assigns each page type, AMP and non-AMP, to a different user. This means some Event Streams are broken, and it makes product analytics work more difficult and mistakes prone.

An already placed cookie can help to unify AMP and non-AMP events

Luckily, you can easily overcome it, at least partially. When visiting an AMP page, Amplitude plants a cookie named amplitude_amp_id. If a user later navigates to a non-AMP page all you need to do is to get this cookie value and set it as the device ID, using Amplitude’s JavaScript SDK.

This is the JavaScript code for doing so:

var amplitudeAmpId = getCookie('amplitude_amp_id'); if (amplitudeAmpId) { amplitude.getInstance().setDeviceId(amplitudeAmpId); } // A helper function to get a cookie by name function getCookie(cookieName) { var name = cookieName + '='; var decodedCookies = decodeURIComponent(document.cookie); var cookiesArray = decodedCookies.split(';'); for (var i = 0; i < cookiesArray.length; i++) { var cookie = cookiesArray[i]; while (cookie.charAt(0) == ' ') { cookie = cookie.substring(1); } if (cookie.indexOf(name) == 0) { return cookie.substring(name.length, cookie.length); } } return false; }
Code language: JavaScript (javascript)

Now AMP and non-AMP events of the same user will be unified into one event stream. This is how it will look like on Amplitude:

AMP and non-AMP events in the same Amplitude event stream

Drawbacks

This won’t work if a user first visits a non-AMP page and doesn’t have a cookie already set from previous sessions.

Conclusion

A simple and short JavaScript snippet can help you to overcome, at least partially, another hurdle introduced by AMP to product analytics work.

Leave a comment

Your email address will not be published. Required fields are marked *