I am preparing to switch a site that's using Google Analytics 4 from using gtag()
over to Google Tag Manager (server-side). One of the things I would like to do is set custom dimensions after initial page load.
Basically I'd like to do something like:
In my case the key issue seems to be that step 3 above can happen at any point in time, such as while the user is scrolling around etc, and the page's GTM config has already run (so the data layer has already been defined and initialized).
Can I still simply push my dimension onto the data layer, and analytics will pick it up and "remember" that these users are in those groups? What is the proper syntax for pushing a dimension?
I've read through mountains of how-to's online, watched videos, as well as sifted through stack overflow questions/answers like this one and this one, but none seem to address my particular situation (or maybe it's late in the day and I missed the right one).
Here's what I ended up doing, which seems to be working so far.
First, I push a custom event onto the data layer variable, with a custom data layer variable for the dimension I want to track. For example, replace 'DimensionName' and 'DimensionValue' below with whatever you want your name and value to be:
let obj = { event: "setCustomDimension" };
obj[`cd_DimensionName`] = 'DimensionValue';
dataLayer.push(obj);
Then I prepared GTM to receive that custom variable ("cd_DimensionName"):
{{cd_DimensionName}}
Then I told GTM to watch for a custom event called "setCustomDimension":
{{DimensionName}}
Finally, make sure to set the variable up in google analytics as normal (Admin > Data display > Custom definitions).
This is working for me, but I'm open to suggestions on a less convoluted method.