How to Add Google Analytics to a Next.js website

We know how important Analytics data is for the growth of a business or website. Let’s have a look at the ways to add Google Analytics to a Next.js website.


To continue with this article, you must have basic knowledge of the Next.js framework and Google Analytics.

What we will learn

Here in this article, we will learn:-

  1. Setup a Google Analytics account for our website
  2. Creating a _document.js file
  3. Add code to track events

Setup a Google Analytics account for our website

We can easily set up a Google Analytics account for our website with the URL below.

After setting up, we will get a code to paste inside the <head> section of our website.

Just copy the MEASUREMENT ID (G-123456789) from this code.

Create a _document.js file in our Next.js app

Inside the pages directory, create a file _document.js and copy the code below. Note that you need to replace the MEASUREMENT ID with yours.

// pages/_document.js

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

class MyDocument extends Document {
  static async getInitialProps(ctx) {
    const initialProps = await Document.getInitialProps(ctx);
    return { ...initialProps };

  render() {
    return (


              __html: `
            window.dataLayer = window.dataLayer || [];
            function gtag(){dataLayer.push(arguments);}
            gtag('js', new Date());
            gtag('config', 'G-123456789', {
              page_path: window.location.pathname,
          <Main />
          <NextScript />

export default MyDocument;

This will inject Google Analytics code into our Next.js website.

Add the code to track events

Now add some code inside our pages/_app.js file to track the events. So that the complete _app.js fie looks the same as below.

// pages/_app.js

import { useEffect } from "react";
import "../styles/globals.css";
import { useRouter } from "next/router";

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

  useEffect(() => {
    const handleRouteChange = (url) => {
      window.gtag("config", "G-123456789", {
        page_path: url,
    };"routeChangeComplete", handleRouteChange);
    return () => {"routeChangeComplete", handleRouteChange);
  }, []);

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

export default MyApp;

Test the working

Now we can see that Google Analytics is tracking the pageviews on our website.


Here we are going to end the quick guide to add Google Analytics to a Next.js website. We injected the Google analytics tracking code, added code to track custom events, and tested.

Be the first to reply

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.