DEV Community

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

jameswallis profile image
James Wallis Author • 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:

    src="/gtag-init.js" // or the name of the file you created
Enter fullscreen mode Exit fullscreen mode

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