google-analyticsgoogle-tag-managergoogle-analytics-4google-datalayer

How do we clear old properties from GTM data layer after every data layer push


Old event properties from data layer are being carry forwarded to the new gtm event.

Current Behaviour :

  1. Trigger an event and call dataLayer.push with event properties. Properties Example: {name: 'Zack', lastName: 'Ryder'};
Recorded event = {name: 'Zack', lastName: 'Ryder'}
  1. Trigger another event and call dataLayer.push again with different event properties. Properties Example: {name: 'John', hobby: 'Sports'}
Recorded event = {name: 'John', lastName: 'Ryder', hobby: 'Sports'}

Expected Behaviour :

  1. Trigger an event and call dataLayer.push with event properties. Properties Example: {name: 'Zack', lastName: 'Ryder'};
Recorded event = {name: 'Zack', lastName: 'Ryder'}
  1. Trigger another event and call dataLayer.push again with different event properties. Properties Example: {name: 'John', hobby: 'Sports'}
Recorded event = {name: 'John', hobby: 'Sports'}

How can we achieve this expected behaviour?

I tried to call window.google_tag_manager[{{Container ID}}].dataLayer.reset(); after every event in tag sequencing but it clears all the properties old + new.

Solution

  • Well the proper solution here would be nullifying the unused/unset properties in every DL object.

    So instead of sending:

    {name: 'Zack', lastName: 'Ryder'}
    

    you send

    {name: 'Zack', lastName: 'Ryder', hobby: null, age: null}
    

    Another solution would be what you tried. Calling the tag that nullifies the DL through the tag sequencing. You just did it wrong. You're supposed to call it after the event is sent so that you wouldn't clear data that you need before you use it.

    Sequencing is not a good solution however. It introduces an odd state to your DL now. So if you have other things there that you rely on or want to use, you have to be very careful with how or when you use them. I would definitely not use the sequenced DL reset.

    If the front-end can't properly nullify the fields and you still want to fix it in GTM, you can. It's not elegant.

    Make a CJS variable and funnel your references to the DL variables through it. Its job would be to check what current event's values are and pass them on to you one way or another. You would probably need a variable for each DL field that you wanna sanitize like this.