How to Add Google Analytics to a Next.js Application - TechvBlogs

How to Add Google Analytics to a Next.js Application

This tutorial will be covering how to add Google Analytics to the Next.js application.

Suresh Ramani - Author - TechvBlogs
Suresh Ramani

1 year ago

TechvBlogs - Google News

Data is today the world’s most valuable commodity. So understanding how your users are using your platform is crucial for taking your business to the next level.

And in the world of analytics, Google is the leader. And the great news is it’s completely free to use!

Google Analytics is a great, free way to track the performance of your web and mobile applications.

This tutorial will be covering how to add Google Analytics to the Next.js application.

1. Create a Google Analytics environment variable

First, let’s create an environment variable for our Google Analytics Measurement ID.


Locally, this should reside in a .env.local or .env file.

Remember to set this environment variable wherever this application is deployed in production.

2. Inject Google Analytics script in _document.js

Next, we’ll want to inject the Google Analytics Global Site Tag (gtag.js) into our site’s <head>.

To access the Next.js <Head> tag, we’ll need a Next.js custom document called /pages/_document.js.

Here, we’ll inject the Google Analytics script into /pages/_document.js.

import Document, { Html, Head, Main, NextScript } from 'next/document';
const gtag = `${process.env.NEXT_PUBLIC_GA_ID}`;
export default class MyDocument extends Document {
  render() {
    return (
          <script async src={gtag} />
              __html: `
                window.dataLayer = window.dataLayer || [];
                function gtag(){dataLayer.push(arguments);}
                gtag('js', new Date());
                gtag('config', '${process.env.NEXT_PUBLIC_GA_ID}', {
                  page_path: window.location.pathname,
          <Main />
          <NextScript />

3. Track page views in _app.js

In order to track page views in our application, we’ll want to add a simple useEffect() hook into our _app.js that listens for routeChangeComplete events.

import { useEffect } from 'react';
import { useRouter } from 'next/router';
function MyApp({ Component, pageProps }) {
  const router = useRouter();
  useEffect(() => {
    const handleRouteChange = url => {
      window.gtag('config', process.env.NEXT_PUBLIC_GA_ID, {
        page_path: url,
    }'routeChangeComplete', handleRouteChange);
    return () => {'routeChangeComplete', handleRouteChange);
  }, []);
  return <Component {...pageProps} />
export default MyApp

4. Optional: only track in production

If we want to limit analytics to our production environment, we can check process.env.NODE_ENV.

Modify _document.js

In /pages/_document.js, let’s declare a boolean variable to check for production (can be outside the component).

const isProd = process.env.NODE_ENV === "production";

Then, we can wrap everything in <Head> in a conditional.

  {isProd && (
      {/* The two script tags */}

Modify _app.js

In /pages/_app.js, let’s declare the same boolean variable for production.

const isProd = process.env.NODE_ENV === "production";

Then, we can modify handleRouteChange to only fire in production.

const handleRouteChange = url => {
  if (isProd) {
    window.gtag('config', process.env.NEXT_PUBLIC_GA_ID, {
      page_path: url,

Thank you for reading this article.

Read Also: How to Loop in React JSX

If you want to manage your VPS / VM Server without touching the command line go and  Checkout this linkServerAvatar allows you to quickly set up WordPress or Custom PHP websites on VPS / VM in a  matter of minutes.  You can host multiple websites on a single VPS / VM, configure SSL certificates, and monitor the health of your server without ever touching the command line interface.

If you have any queries or doubts about this topic please feel free to contact us. We will try to reach you.

Comments (0)


Note: All Input Fields are required.