DEV Community

Cover image for Google Analytics With Next JS
Muhammad Mejanul Haque
Muhammad Mejanul Haque

Posted on

Google Analytics With Next JS

With Next.js you don't have to use any npm packages to add google analytics.

You just add the scripts in<Head> element on your _document.js/tsx or in your Layout.js/tsx file or any pages you want.

Go add your project in Google Analytics and they will give you a gtag code to paste in your <head> tag.

But pasting them directory will give you an Unexpected token error because of using React Framework.

I found a very simple solution in this GitHub issue.

Just wrap the gtag code with dangerouslySetInnerHTML like the code below and that's all.

    src=" code here%" >
<script dangerouslySetInnerHTML={
    { __html: `
        window.dataLayer = window.dataLayer || [];
        function gtag(){window.dataLayer.push(arguments)}
        gtag("js", new Date());
        gtag("config", "<%your code here%>");

Alt Text

Related Article

If you are interested in implementing Tailwind CSS with PurgCSS in Next.js, visit

I just created a new personal blog to share what I know best.

Discussion (2)

nkootstra profile image
Niels Kootstra • Edited on

Isn't it much easier to implement the following?

mejanhaque profile image
Muhammad Mejanul Haque Author

Yes, Of course, it is. I just went with more simpler like copying the code, paste it and wrap it with dangerouslySetInnerHTML.