Import Google Analytics to your NextJS Web App

Google Analytics, NextJS, SEO

Requirments:

  • Next.js project
  • a Google Analytics account

Step 1:

Create a .env.local file where you will place your Google Analytics key.

  NEXT_PUBLIC_GOOGLE_ANALYTICS=<Your_tracking_ID>

Tip: Check your .gitignore to make sure that you don't commit this file by accident. .env.local

Step 2:

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.

ref - NEXTJS DOCUMENTATION -


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

export default class MyDocument extends Document {

const url: string = `https://www.googletagmanager.com/gtag/js?   id=${process.env.NEXT_PUBLIC_GOOGLE_ANALYTICS}`

  render() {
    return (
      <Html>
        <Head>
          {/* Global Site Tag (gtag.js) - Google Analytics */}
          <script
            async
            src={url}
          />
          <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>
    )
  }
}

Step 3:

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)
}


Step 4:

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

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).


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


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

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.