loading...
Cover image for Google Analytics With Next JS

Google Analytics With Next JS

mejanhaque profile image Muhammad Mejanul Haque ・1 min read

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.

Posted on by:

mejanhaque profile

Muhammad Mejanul Haque

@mejanhaque

I am a self-taught full-stack Web developer. Currently, I am into Blazor Web Assembly & Typescript Frameworks like Deno, React ts, etc.

Discussion

markdown guide
 
 

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