Google Analytics with Next.js

Adding Google Analytics with Nextjs

We understand how critical Analytics data is for a company's or website's success. Let's look at how to integrate Google Analytics into a Next.js site.

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 section of our website.

Analytics page sreenshot

Just copy the MEASUREMENT ID (G-{Your Code}) 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.

Analycs page view screenshot


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.

Mar 18 2022