How to add Google Analytics to Next.js app
Tags: nextjs, react
Published: 2023-04-09 08:12:56

If you have started working with Next.js recently and wanted to add Google Analytics to your website, then you are at the right place!

## Creating a Google Analytics tag

Login to https://analytics.google.com/analytics/web/ with your Google account.

Now click on the Settings Icon (⚙️ Admin) at the bottom and click on Create Account
(If you already have an account, you can click on Create Property).

![ga admin page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ib657b4wzxyqmz931dq2.png)

Now fill in the account name:

![ga account name](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bkwmij2nuwmxu58yzf14.png)

Fill in the property details along with the time zone and currency:

![ga property details](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5gauqc9npc7dxv9u32ti.png)

Finally, fill in the business details and click on Create:

![ga create tag](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zpvsonp2n4occhg5zav6.png)

Now you will be redirected to a page with the following options. Here click on Web.

![ga choose web](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c3y92p00yvg2v6d3n4m3.png)

In the next step provide your website details and click on Create stream.

![ga create stream](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vuj5fg0m0a1r0cbpah6q.png)

Now you will be provided with a measurement id. Make a note of it. It will be used in the next step.

![ga copy tag](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/iikjoulrfqxtoifo48x9.png)

## Creating a Next.js app

Now create a Next.js app, if you do not have one, using the following command:

```bash
npx create-next-app@latest next-ga-integration
```

## Adding Google Analytics

Create a file named `gtag.js` with the following content (replace `GA_TRACKING_ID` value with yours):

```js
export const GA_TRACKING_ID = "G-226MBLFR8V" //replace it with your measurement 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,
  })
}
```

We have 2 functions here:

- pageview: To track users navigating to different pages.
- event: To track events like add to cart, place order, etc.

Now open `_app.js` and include the following code:

```js
import "@/styles/globals.css"
import Script from "next/script"
import { useRouter } from "next/router"
import { useEffect } from "react"
import * as gtag from "gtag"

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

  return (
    <>
      <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} />;
    </>
  )
}
```

In the above code:

- We have included the Google Analytics script and loading it after the page becomes interactive so that it doesn't affect the page loading time.
- We have a `useEffect` where we listen to route changes and call the `pageview` function, defined inside `gtag.js`.
  This is required since in Next.js, whenever routing happens, the page doesn't completely reload and Google Analytics will not be able to pick up the route change automatically.

Now your application is setup with Google Analytics and you can track the live users:

![ga live user](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/34anb3nj6q0gsm6ixh1b.png)