Let me start by saying this: learning how to track private data in Magento 2 was a ballache. Now that’s out of my system I can continue with this post… Yes it was a ballache but it ended up being very easy. Here’s the situation:
Well, in case you haven’t guessed this post is all about how to implement GTM tracking in Magento 2 without having your data carved into stone for all to see by Magento 2’s full page cache.
I had a situation where I had to track a lot of customer data and therefore had to make this data available in the GTM Data Layer.
To keep it simple I’ll just focus on how to track a newsletter subscriber’s email address when they use the basic newsletter form. This data is not posted back to any page on the website, and even if it was, the name could potentially get cached on the next loaded page meaning the next user could see my email address.
As tracking code normally resides within the page HTML how do you get around this?
One option could be to save the posted data in local storage and then access it via JS on the next page load (in the same fashion as the mini cart). It then turned out that local storage is basically the last thing loaded so my
datalayer.push() script had already ran twenty minutes prior with a null value.
I looked at the way Magento had handled
datalayer.push() in their own
- Intercept the data in an observer/plugin
- Set data to a cookie in PHP
- Retrieve data on frontend in JS
- Delete cookie
I have left out the majority of the basic module files for simplicity, but here’s the key bits:
First I register a plugin that will watch a function in the following class: Magento\Newsletter\Model\Subscriber.
I’m using a plugin to set a cookie after a customer has successfully subscribed to the newsletter. Once I have the information I need I use the
CookieMetadataFactory classes to set my cookie and I’m JSON encoding the result.
I’m now declaring a new require class that will contain methods I use for handling cookies:
The reason for these functions will become clear in a moment.
This file is where the magic happens. First we initialise our new JS class
MagentoFoxTrack and we pass it as an argument with require. This allows our methods to be used wherever and whenever.
We then grab our
customerData cookie, check that it is not null, parse the JSON which will turn it back into an object, and push to GTM. Finally we delete the cookie on the fly.
This may not turn out to be the 100% best way of solving this particular problem, but having thoroughly tested with various types of customer data I have found it to be consistently reliable.
Thanks for reading and please feel free to comment if you have any suggestions or improvements.