Skip to content

How to add Google Analytics 4 to Next.js

New Course Coming Soon:

Get Really Good at Git

Here’s how to add Google Analytics version 4 to a website based upon Next.js.

Create a Google Analytics property and save the property ID in a NEXT_PUBLIC_GOOGLE_ANALYTICS environment variable.

Then, you need to add a useEffect() call in the pages/_app.js file, which might look like this now:

import '/public/style.css'

function MyApp({ Component, pageProps }) {
  return <Component {...pageProps} />
}

Change it to

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

Finally, add a pages/_document.js file that creates a Next.js custom document that injects the Google Analytics script, with:

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>
    )
  }
}

Note: solution adapted from a post by Marie Starck on https://mariestarck.com/add-google-analytics-to-your-next-js-application-in-5-easy-steps/

Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. A course that helps you feel less frustrated with Git. Launching May 21, 2024. Join the waiting list!

Here is how can I help you: