DEV Community

Discussion on: Quickly adding Google Analytics to Next.js with FAQs

Collapse
 
jameswallis profile image
James Wallis • Edited

Hi, thanks for commentting!

I believe you could create a .js file in your public folder that contains the code inside the dangerouslySetInnerHTML block and add that as the src of the <script> tag.

So create a file in the public dir, e.g. /public/gtag-init.js, with the following contents:

window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '${GA_MEASUREMENT_ID}', {
    page_path: window.location.pathname,
});
Enter fullscreen mode Exit fullscreen mode

and then change the <Head> tag to be:

<Head>
  <script
    async
    src={`https://www.googletagmanager.com/gtag/js?id=${GA_MEASUREMENT_ID}`}
  />
  <script
    async
    src="/gtag-init.js" // or the name of the file you created
  />
</Head>
Enter fullscreen mode Exit fullscreen mode

Let me know how you get on and I will update the article, thanks!