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