Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Next.js + react-gtm-module ReferenceError: document is not defined

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?

like image 790
flppv Avatar asked Mar 02 '23 16:03

flppv


2 Answers

Wrapping the piece of TagManager initializer with a checker helped:

if (process.browser) {
  TagManager.initialize(tagManagerArgs);
}
like image 128
flppv Avatar answered Apr 29 '23 05:04

flppv


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

useEffect(()=>{
    TagManager.initialize({gtmId: 'GTM-XXXXXX'})
},[])
like image 22
Juan Chaher Avatar answered Apr 29 '23 04:04

Juan Chaher