This tutorial will be covering how to add Google Analytics to your Next.js application.
The implementation is straightforward and doesn't require any third-party library.
We are going to use new NextJS feature `Script Component`. For it to work you will need NextJs version 11.
Let's start the show!
Let me assume you already had the Next.js Project and Google Analytics Console.
Step 1:
In my case, I keep my `GA_MEASUREMENT_ID` in environment variables (.env).
NEXT_PUBLIC_GA_MEASUREMENT_ID=G-46xxxxxxxx
Update your 'next.config.js' file with the following content.
/** @type {import('next').NextConfig} */
module.exports = {
compilerOptions: {
noImplicitReturns: true,
noImplicitAny: false,
},
serverRuntimeConfig: {
// Will only be available on the server side
// ....
},
publicRuntimeConfig: {
// ...
staticFolder: '/static',
NEXT_PUBLIC_GA_MEASUREMENT_ID: process.env.NEXT_PUBLIC_GA_MEASUREMENT_ID
}
}
Passing Variable Flow.
We have to pass our GA_MEASUREMENT_ID variable from .env file to our layout as the following concept.

It is time to combine google analytics code to our layout.js.
I do not use additional third party component.
There is Build-In component in Next.js.
Please check the following code.
import React from 'react'
import Script from 'next/script';
import getConfig from 'next/config';
const { publicRuntimeConfig } = getConfig();
interface IMainLayout {
children: React.ReactNode;
head:React.ReactNode;
title:string;
}
export default function Layout({ children, ...props }:IMainLayout)
return(
<div>
<div>
{children}
</div>
{ /*START Global site tag (gtag.js) - Google Analytics*/ }
<Script
src={"https://www.googletagmanager.com/gtag/js?id="+publicRuntimeConfig.NEXT_PUBLIC_GA_MEASUREMENT_ID}
strategy="beforeInteractive"
/>
<Script id="google-analytics" strategy="afterInteractive">
{`
window.dataLayer = window.dataLayer || [];
function gtag(){window.dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '${publicRuntimeConfig.NEXT_PUBLIC_GA_MEASUREMENT_ID}');
`}
</Script>
{ /* END Global site tag (gtag.js) - Google Analytics*/ }
</div>
)
}
Go back to your google analytics console and check the status. It will work.
Congrulation
You have successfully combine you next.js and google analytics.
Thank you for taking the time to read my article.
I hope you find it helpful.
Please feel free to reach out if you have any questions or would like to discuss further.