How to add Google Analytics to your Next.js Application

Davis Gitonga

Davis Gitonga / December 14, 2021

4 min read

How to add Google Analytics to your Next.js Application

Photo by Myriam Jessier

Here's how to add Google Analytics to your Next.js application.

Prerequisites

  • a Next.js application
  • a Google Analytics account

Google Analytics account setup

Set up a data stream

After setting up your Google Analytics account, the next step is to set up a data stream to start collecting data.

Setting up a Google Analytics data streams image.

Choose the platform you want to collect data from and create a stream.

NB: Choose the Web as the platform.

Creating data stream image.

After creating a data stream, you will get tagging information and a Measurement ID for web streams.

Google Analytics Measurement ID image.

Add your Google Analytics Measurement ID as an environment variable

First, create a .env.local file in your project root directory.

touch .env.local

Check your .gitignore to ensure 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.

.env.local
NEXT_PUBLIC_GA_ID=<Your-Measurement-ID>

Add the Analytics tag to your Next.js application

It's now time to configure the Google Analytics Global site tag (gtag) into your application.

In your pages/_app.js file, add the following code:

pages/_app.js
import Script from 'next/script'

const App = ({ Component, pageProps }) => {
  return (
    <>
      {/* Global Site Tag (gtag.js) - Google Analytics */}
      <Script
        strategy="afterInteractive"
        src={`https://www.googletagmanager.com/gtag/js?id=${process.env.NEXT_PUBLIC_GA_ID}`}
      />
      <Script
        id="gtag-init"
        strategy="afterInteractive"
        dangerouslySetInnerHTML={{
          __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,
            });
          `,
        }}
      />
      <Component {...pageProps} />
    </>
  )
}

export default App

This code will add the gtag function to the window object and configure the gtag function with the NEXT_PUBLIC_GA_ID environment variable.

We also use the Next.js Script component, next/script, an extension of the HTML <script> element. It enables us to set the loading priority of third-party scripts anywhere in our application without needing to append directly to next/head, saving developer time while improving loading performance.

You can find the code under Tagging instructions in the Webstream details window. See the last image above.

Custom functions for tracking page views and events

To correctly track user interactions with your application, you need to log page views and optionally events such as downloads, link clicks, form submissions, and video plays.

To do so, we'll create a gtag.js file in the lib directory of your Next.js project.

touch lib/gtag.js

Inside the file, export two functions: one to log page views and the other events.

lib/gtag.js
export const GA_TRACKING_ID = process.env.NEXT_PUBLIC_GA_ID

// https://developers.google.com/analytics/devguides/collection/gtagjs/pages
export const pageview = (url) => {
  window.gtag('config', GA_TRACKING_ID, {
    page_path: url,
  })
}

// https://developers.google.com/analytics/devguides/collection/gtagjs/events
export const event = ({ action, category, label, value }) => {
  window.gtag('event', action, {
    event_category: category,
    event_label: label,
    value: value,
  })
}

Logging pageviews

The simplest way to log page views in your Next.js app is to subscribe to your Next.js Router and listen for the routeChangeComplete event.

The routeChangeComplete event fires when a route changes completely.

Since Router events should be registered when a component mounts, we'll need to use the useEffect hook to subscribe and unsubscribe to new events happening in the router.

Update the pages/_app.js file to add the following code:

pages/_app.js
import { useEffect } from 'react'
import { useRouter } from 'next/router'
import Script from 'next/script'
import * as gtag from '../lib/gtag'

const App = ({ Component, pageProps }) => {
  const router = useRouter()
  useEffect(() => {
    const handleRouteChange = (url) => {
      gtag.pageview(url)
    }
    router.events.on('routeChangeComplete', handleRouteChange)
    router.events.on('hashChangeComplete', handleRouteChange)
    return () => {
      router.events.off('routeChangeComplete', handleRouteChange)
      router.events.off('hashChangeComplete', handleRouteChange)
    }
  }, [router.events])

  return (
    <>
      {/* Global Site Tag (gtag.js) - Google Analytics */}
      <Script
        strategy="afterInteractive"
        src={`https://www.googletagmanager.com/gtag/js?id=${gtag.GA_TRACKING_ID}`}
      />
      <Script
        id="gtag-init"
        strategy="afterInteractive"
        dangerouslySetInnerHTML={{
          __html: `
            window.dataLayer = window.dataLayer || [];
            function gtag(){dataLayer.push(arguments);}
            gtag('js', new Date());
            gtag('config', '${gtag.GA_TRACKING_ID}', {
              page_path: window.location.pathname,
            });
          `,
        }}
      />
      <Component {...pageProps} />
    </>
  )
}

export default App

Add your GA ID to your environment variables in production

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

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

Vercel enviroment variables image.

Additional Resources

Conclusion

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

Thank you for reading!

Happy Coding! 🤓

share your thoughts