Add Google Analytics to your Next.js application in 5 easy steps
Published: 2021-02-22 11:12:00

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>
```

## 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](https://nextjs.org/docs/advanced-features/custom-document)._

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

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

```jsx
// 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: 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](https://nextjs.org/docs/api-reference/next/router#routerevents). You may, for example, be interested in logging when an error occurs (`routeChangeError`)._

```jsx
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
```

## 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](https://developers.google.com/analytics/devguides/collection/gtagjs/events#default_google_analytics_events) is a list of Google Analytics Default events.

This is an example of how to log search terms entered by users:
```jsx
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>
  )
}
```

## 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7cvlmpvh2od1l0iriui1.png)

### 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t8zxnk996phft3nnia3j.png)

### 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](https://chrome.google.com/webstore/detail/google-analytics-debugger/jnkmfdileelhofjcijamephohjechhna).

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](https://twitter.com/MStarckJS).