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.

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

Alt Text

Related Article

If you are interested in implementing Tailwind CSS with PurgCSS in Next.js, visit https://alhaqi.com/blog/tailwind-css-with-next-js-and-typography.

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

Discussion (2)

Collapse
nkootstra profile image
Niels Kootstra • Edited

Isn't it much easier to implement the following? github.com/vercel/next.js/tree/mas...

Collapse
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.