Code Disciples

A blog for all things code

Wed 20 April 2022

Google Analytics 4 with Next.js

Posted by Abhishek Pednekar in Next.js   

Recently, Google announced that Universal Analytics (UA) would be sunset on July 1st, 2023. Post this date, UA would not process any new hits. The data collected by UA would be available for six months thereafter. Google has strongly recommended that individuals and businesses using the UA property switch to their new analytics measurement solution, Google Analytics 4.

In this article, we will see how Google Analytics 4 can be integrated with a Next.js website. The article assumes that the reader has a Google Analytics account and is familiar with Next.js.

Creating a Google Analytics 4 property

On the Admin section of your Google Analytics dashboard, click on the Create Property button. This by default will create a Google Analytics 4 property.


Once you enter basic information like the property name and work details, you will be prompted to create a data stream. Click on Web to generate the site tag for your Next.js website.


You will now see the code you need to embed in your website in the Tagging instructions section.


Embedding the site tag in Next.js

Step 1: Create an environment variable with the Google Analytics 4 measurement id.

// .env.local


Step 2: Create a _document.js file in the pages directory (if not already present) to add the tracking code. _document.js overrides the default document provided by Next.js.

// _document.js

import Document, { Html, Head, Main, NextScript } from "next/document";

class MyDocument extends Document {
  render() {
    return (
      <Html lang="en">
              __html: `
            window.dataLayer = window.dataLayer || [];
            function gtag(){dataLayer.push(arguments);}
            gtag('js', new Date());
            gtag('config', '${process.env.NEXT_PUBLIC_GA4_MEASUREMENT_ID}', {
              page_path: window.location.pathname,

          <Main />
          <NextScript />

export default MyDocument;

Step 3: Finally, in _app.js, we will use the useEffect hook and the routeChangeComplete event provided by the Next.js router to run the analytics code when a route changes. We will subscribe to the routeChangeComplete event whenever the component mounts and unsubscribe on unmount.

import { useEffect } from "react";

function MyApp({ Component, pageProps, router }) {

  useEffect(() => {
    const handleRouteChange = (url) => {
      window.gtag("config", process.env.NEXT_PUBLIC_GA4_MEASUREMENT_ID, {
        page_path: url,

    // Subscribe to the change event"routeChangeComplete", handleRouteChange);

    return () => {"routeChangeComplete", handleRouteChange);
  }, []);

 return <Component {...pageProps} />

export default MyApp;

That's it! Refresh your page a couple of times to see the activity on your Google Analytics dashboard.

Further reading

This article is inspired by a post from Marie Starch
Next.js custom document
Next.js router events