/

How to Add Google Analytics 4 to Next.js

How to Add Google Analytics 4 to Next.js

In this tutorial, we will walk you through the process of adding Google Analytics version 4 to a Next.js website. Follow the steps below:

Step 1: Create a Google Analytics Property

First, create a Google Analytics property and remember to save the property ID. This property ID will be used later on in the implementation.

Step 2: Set Up Environment Variables

Next, set up environment variables for your Next.js project. Create an environment variable called NEXT_PUBLIC_GOOGLE_ANALYTICS and assign it the value of your Google Analytics property ID.

Step 3: Modify the _app.js File

Now, open the pages/_app.js file in your Next.js project and make the following modifications:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import { useEffect } from 'react'
import { useRouter } from 'next/router'

import 'tailwindcss/tailwind.css'
import '/public/style.css'

function MyApp({ Component, pageProps }) {
const router = useRouter()

useEffect(() => {
const handleRouteChange = (url) => {
window.gtag('config', process.env.NEXT_PUBLIC_GOOGLE_ANALYTICS, {
page_path: url,
})
}

router.events.on('routeChangeComplete', handleRouteChange)

return () => {
router.events.off('routeChangeComplete', handleRouteChange)
}
}, [router.events])

return <Component {...pageProps} />
}

export default MyApp

Here, we import the useEffect hook and the useRouter hook from the react and next/router libraries, respectively. Then, we add the useEffect hook to handle route changes. Within the useEffect hook, we define a function called handleRouteChange that triggers the Google Analytics tracking code.

Step 4: Create the _document.js File

Next, create a pages/_document.js file in your Next.js project. This file will serve as the custom document for injecting the Google Analytics script. Here’s the content of the _document.js file:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import Document, { Html, Head, Main, NextScript } from 'next/document'

export default class MyDocument extends Document {
render() {
return (
<Html>
<Head>
<script
async
src={`https://www.googletagmanager.com/gtag/js?id=${process.env.NEXT_PUBLIC_GOOGLE_ANALYTICS}`}
/>
<script
dangerouslySetInnerHTML={{
__html: `
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '${process.env.NEXT_PUBLIC_GOOGLE_ANALYTICS}', {
page_path: window.location.pathname,
});
`,
}}
/>
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
)
}
}

In this file, we import Html, Head, Main, and NextScript components from the next/document module. Inside the Head component, we include the Google Analytics script using the property ID from the environment variable.

That’s it! You’ve successfully added Google Analytics 4 to your Next.js website. Now you can track user activities and gain valuable insights about your website’s performance.

Note: This solution is adapted from a post by Marie Starck on mariestarck.com

tags: [“Next.js”, “Google Analytics”, “SEO”, “Tracking”, “Web Analytics”]