6

I use this piece to initialize GTM in my Next.js app:

const tagManagerArgs = {
  gtmId: "GTM-XXXXXX"
};
TagManager.initialize(tagManagerArgs);

But when I am trying to start an app with it I am getting the error:

ReferenceError: document is not defined
    at Object.dataScript (/Users/username/work/projectname/node_modules/react-gtm-module/dist/TagManager.js:11:18)

How to solve this?

flppv
  • 4,111
  • 5
  • 35
  • 54
  • Hi there, not sure about your project struct but you must to put this inside your App.js, where are you exposing this code above? – felipekm Mar 17 '20 at 20:14
  • I've already found the solution and put the answer, posted here just in case someone will face same issue. – flppv Mar 17 '20 at 20:15
  • Right, I'd suggestion to expose better why document was undefined and show a tiny nextjs structure, you refered it in labels but shown nothing related – felipekm Mar 17 '20 at 20:25

2 Answers2

7

Wrapping the piece of TagManager initializer with a checker helped:

if (process.browser) {
  TagManager.initialize(tagManagerArgs);
}
flppv
  • 4,111
  • 5
  • 35
  • 54
2

You can initialize TagManager right when the website has mounted to ensure that the DOM api is available

useEffect(()=>{
    TagManager.initialize({gtmId: 'GTM-XXXXXX'})
},[])
Juan Chaher
  • 523
  • 3
  • 9