title: Allow google analytics to load only after consented in Next.js
body: <p>I integrated google analytics to next.js - to say, I followed these guides:</p>
  <ol>
  <li><a href="https://frontend-digest.com/using-nextjs-with-google-analytics-and-typescript-620ba2359dea" rel="nofollow noreferrer">https://frontend-digest.com/using-nextjs-with-google-analytics-and-typescript-620ba2359dea</a></li>
  <li><a href="https://github.com/vercel/next.js/tree/canary/examples/with-google-analytics" rel="nofollow noreferrer">https://github.com/vercel/next.js/tree/canary/examples/with-google-analytics</a></li>
  </ol>
  <p>Which works just fine, now the issue is I need to allow loading google analytics only after cookie consent, I store my cookie consent in localStorage at the moment simply in the format:</p>
  <pre><code>checkboxValues = {
    necessary: true,
    statistics: false,
    marketing: false,
  };
  </code></pre>
  <p>Now I need to check <code>localStorage.getItem('acceptCookies');</code> and make sure google analytics is loaded only when <code>statistics: true</code>.</p>
  <pre><code>import Document, { Html, Head, Main, NextScript } from &quot;next/document&quot;;
  
  import { GA_TRACKING_ID } from &quot;../utils/gtag&quot;;
  
  export default class MyDocument extends Document {
    render() {
      return (
        &lt;Html&gt;
          &lt;Head&gt;
            {/* Global Site Tag (gtag.js) - Google Analytics */}
            &lt;script
              async
              src={`https://www.googletagmanager.com/gtag/js?id=${GA_TRACKING_ID}`}
            /&gt;
            &lt;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,
                });
            `
              }}
            /&gt;
          &lt;/Head&gt;
          &lt;body&gt;
            &lt;Main /&gt;
            &lt;NextScript /&gt;
          &lt;/body&gt;
        &lt;/Html&gt;
      );
    }
  }
  </code></pre>
  <p>for me to check for the localStorage before <code>render()</code> is not possible as localStorage is only available after <code>componentDidMount</code>. Stuck with this, any direction?</p>