Search code examples
javascriptnext.jsgoogle-tag-manager

Custom JavaScript using dynamic data


I'm trying to set ecommerce events on our web-site with GTM. And I'm trying to make custom value with custom JavaScript but it continuously shows undefined

First, I found data script on our website

<script id="__NEXT_DATA__" type="application/json">

And I write custom javascript code like below

function() {
  var productInfo = [{
    'id':window.__NEXT_DATA__.props.pageProps.program.products[0].id,
    'name':window.__NEXT_DATA__.props.pageProps.program.products[0].name,
    'price':window.__NEXT_DATA__.props.pageProps.program.products[0].price,
    'category':'exhibition'
  }];

  return productInfo;
}

Our website is developed with next.js, is it impossible to use script data(?) in custom JavaScript?


Solution

  • As far as I understand, __NEXT_DATA__ is loaded asynchronously. Depends on how you setup GTM. It is possible you are running into a race condition where GTM script runs your custom JavaScript function while Next.js is loading the data.

    I think a better approach will be:

    1. set up a trigger, which listens to a custom event, in GTM.
    2. set up a Tag, which is triggered by the trigger we just setup, in GTM.
    3. In your Next.js app, send a custom event when your app is ready. I suggest running the logic in useEffect hook.
    4. If set up correctly, you will run your custom JavaScript after your app is loaded, which can solve the race condition.