Q: How to disable google analytics in document.js nextjs When a user first visits the website they can choose to accept or decline tracking cookies. If they decline I set a cookie with value false. I would like to use that value of the cookie to conditionally run the gtag script. I tried accessing the cookies in the custom document.js but the req/res from getInitialProps are undefined and document.js only runs on the serverside so I'm not able to access the browsers cookies. How can I still conditionally inject the google analytics script?

class MyDocument extends Document {
    static async getInitialProps (ctx) {
        const initialProps = await Document.getInitialProps(ctx);
        return { ...initialProps, lang: ctx.query.lng}
    }

    render () {

        return (
            <Html lang={this.props.lang}>
                <Head>
                    <link
                        rel="stylesheet"
                        href="https://fonts.googleapis.com/css2?family=Poppins&display=swap"
                    />

                    <script
                        async
                        src={`https://www.googletagmanager.com/gtag/js?id=${GA_TRACKING_ID}`}
                    />
                    <script
                        dangerouslySetInnerHTML={{
                            __html: `
            window.dataLayer = window.dataLayer || [];
            function gtag(){dataLayer.push(arguments);}
            gtag('js', new Date());
            gtag('config', '${GA_TRACKING_ID}', {
              page_path: window.location.pathname,
            });
          `,
                        }}/>

                </Head>
                <body>
                <Main/>
                <NextScript/>
                </body>
            </Html>
        )
    }
}

export default MyDocument



A: How you are setting the cookie is not shown but setting it as httponly or secure will prevent client side access - you could omit it and the cookie would be available client-side or you could use a webstorage API and avoid the cookie route.
Once you have access on the client-side, you can make the script embedding conditional.

A: One possible solution is to move the GTM injection script to a useEffect in the  _app.tsx.
Code placed in the UseEffect will only execute on the client-side.
const MyApp  = (props) => {
  
  useEffect(()=>{
     
     if(GDPRService.isConsentGiven()) { // your consent code
        const s = document.createElement('script');
        s.type =  'text/javascript';
        s.src = "..."; // your GTM link 
        document.getElementsByTagName('head')[0].appendChild(s);
        
        ...// code to push stuff into the datalayer. 

     }


    },[])

   ...
 }

