DEV Community

Marie Starck
Marie Starck

Posted on • Edited on • Originally published at mariestarck.com

Add Google Analytics to your Next.js application in 5 easy steps

This tutorial will be covering how to add Google Analytics to your Next.js application. The implementation is straightforward and doesn't require any third-party library.

In 5 easy steps, I will show you how to get Google Analytics set up.

For this tutorial, you will need:

  • a Next.js project
  • a Google Analytics account

Step 1: Add your Google Analytics ID to your Next.js .env.local file

First, start with creating a .env.local file where you will place your Google Analytics key.

Tip: Check your .gitignore to make sure that you don't commit this file by accident. .env.local should have already been included by default in your Next.js project but check to make sure.

NEXT_PUBLIC_GOOGLE_ANALYTICS=<Your_tracking_ID>
Enter fullscreen mode Exit fullscreen mode

Step 2: Inject Google Analytics tracking code into your Next.js application

Now that your key is set, you need to inject and configure Google Analytics' Global site tag (aka gtag) into your browser window.

To access the head element in your Next.js application, you need to create a custom _document.js file into your pages folder.

Tip: Confused about what a custom document file is? Don't hesitate to check out Next.js' documentation on custom document.

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

export default class MyDocument extends Document {
  render() {
    return (
      <Html>
        <Head>
          {/* Global Site Tag (gtag.js) - Google Analytics */}
          <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>
    )
  }
}
Enter fullscreen mode Exit fullscreen mode

Step 3: Custom functions to track pageviews and events

Key set: check! Global site tag configured: check!

Let's move on to the tracking piece of Google Analytics. In order to correctly track your user's behaviours, you will need to log page views and optionally, specific events triggered in your application.

To do so, I suggest you create a lib folder where you will put all your code related to third-party libraries and another folder inside called ga for Google Analytics.

Inside your lib/ga folder, create an index.js with two functions: one to log pageviews and the other events.

// log the pageview with their URL
export const pageview = (url) => {
  window.gtag('config', process.env.NEXT_PUBLIC_GOOGLE_ANALYTICS, {
    page_path: url,
  })
}

// log specific events happening.
export const event = ({ action, params }) => {
  window.gtag('event', action, params)
}
Enter fullscreen mode Exit fullscreen mode

Step 4: Log pageviews in your Next.js app

The simplest way to log pageviews in your Next.js app is to subscribe to your router and listen for the routeChangeComplete event.

To do so, go into your _app.js file and with useEffect, check for new events happening with your router. There are many types of events but we only care when users navigate to a new page successfully (routeChangeComplete).

Note: If you are interested, there are many router events types in Next.js. You may, for example, be interested in logging when an error occurs (routeChangeError).

import { useEffect } from 'react'
import { useRouter } from 'next/router'

import * as ga from '../lib/ga'

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

  useEffect(() => {
    const handleRouteChange = (url) => {
      ga.pageview(url)
    }
    //When the component is mounted, subscribe to router changes
    //and log those page views
    router.events.on('routeChangeComplete', handleRouteChange)

    // If the component is unmounted, unsubscribe
    // from the event with the `off` method
    return () => {
      router.events.off('routeChangeComplete', handleRouteChange)
    }
  }, [router.events])

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

export default MyApp
Enter fullscreen mode Exit fullscreen mode

Step 5: Log specific events in your Next.js app

Now that our page views are tracked, you may be interested in logging specific events in your application. Here is a list of Google Analytics Default events.

This is an example of how to log search terms entered by users:

import { useState } from 'react'

import * as ga from '../lib/ga'

export default function Home() {
  const [query, setQuery] = useState("");

  const search = () => {
    ga.event({
      action: "search",
      params : {
        search_term: query
      }
    })
  }

  return (
    <div>
        <div>
          <input type="text" onChange={(event) => setQuery(event.target.value)}></input>
        </div>
        <div>
            <button onClick={() => search()}>Search</button>
        </div>
    </div>
  )
}
Enter fullscreen mode Exit fullscreen mode

Next steps:

Add your Google Analytics ID to your environment variables in production

Once deployed to production, don't forget to add your Google Analytics secret key to your environment variables.

In Vercel, you can do so by going to your project, then Settings and finally Environments Variables.
Alt Text

Check that Google Analytics is connected

It takes between 24-48 hrs for data to show up in Google Analytics. However, you can check if your tag is working by looking at the Realtime view.
Alt Text

Test and Debug your pageviews and events with Google Analytics Debugger

If you don't see any data in Realtime, another way to test your Google Analytics tag is with the Chrome extension Google Analytics Debugger.

Once installed and turned on, it prints Google Analytics messages to your console making it easy to see what happens behind the scene.

Et voilà!

You now have a Next.js application with Google Analytics set up and ready to start tracking.

If you liked the article, you can follow me on Twitter.

Top comments (0)