How to integrate Google Analytics with a Next.js app
Tags: analytics, nextjs, javascript
Published: 2021-09-28 01:51:45

TL;DR: Chuck tag and script into [`Script` tag](https://nextjs.org/docs/basic-features/script) in `_app.tsx` file. Also, note **to not include** the script tag inside the `head` or `_document.tsx` file.

Setting up analytics in a single-page application can be a PITA, specially if there is bunch of stuff going on under the hood when you use an opinionated framework like Next.js, eg. SSR, ISR etc. In this post we’ll be looking specifically into Next.js 11 and up, which has made lives much easier, and setting up GA4 with it's Global site tag aka `gtag.js`.

First thing first, if you don't already have a Google Analytics 4 property setup, check out the <a href="https://support.google.com/analytics/answer/9304153" rel="noopener nofollow">official walkthrough</a>, and set up default streams, at least the `Page views` stream.

It might look something like this:
<img src="https://bish.al/_next/image?url=%2F_next%2Fstatic%2Fimage%2Fpublic%2Fassets%2Fblog%2Fhow-to-add-google-analytics-to-next-js-app%2Fga-metrics.093c1e30393d712f87e3ed1cf00afaf8.webp&w=3840&q=75"  alt="GA4 metrics settings"/>

<img src="https://bish.al/_next/image?url=%2F_next%2Fstatic%2Fimage%2Fpublic%2Fassets%2Fblog%2Fhow-to-add-google-analytics-to-next-js-app%2Fgtag-instructions.09446af7b0ce375a0a9d8b7be1e0ed9a.webp&w=3840&q=75" width="1800" height="806" alt="GA4 metrics setup instructions"/>

Moving forward, we simply need to include the snippet provided by the GA into our Next app.

Before we do that, we'll pass in the GA ID through `.env` file (which we'll pass in via Vercel's environment variable setting, if you're using Vercel for deployment).
In the root folder, in your `.env.local` file:

```bash
// .env.local
NEXT_PUBLIC_GA_ID=G-12XXXXXXXX
```

In your `_app.tsx`, paste the snippet.

```jsx
// _app.tsx
...
import Script from 'next/script'
...

export default function MyApp({ Component, pageProps }: AppProps) {
  return (
    <>
      <Script
        strategy='lazyOnload'
        src={`https://www.googletagmanager.com/gtag/js?id=${process.env.NEXT_PUBLIC_GA_ID}`}
      />
      <Script id='ga-analytics'>
        {
          `
            window.dataLayer = window.dataLayer || [];
            function gtag(){dataLayer.push(arguments);}
            gtag('js', new Date());

            gtag('config', '${process.env.NEXT_PUBLIC_GA_ID}');
          `
        }
      </Script>
      <Component {...pageProps} />
    </>
  )
}
```

Few important things to note here:
1. `id` for enclosing inline scripts, so that Next.js knows what's where. Failing to do so, might result in undesirable results. I have noticed double reporting of `page_view` events.
2. We're setting `strategy='lazyOnload'` . It's recommended to use `afterInteractive` for analytics in the official docs, which is also the default. But that might cause slight hindrance on page load speed, so we're opting to load analytics scripts after everything else in the page have finished loading. I haven't noticed any drawbacks with this option.

### How do we verify everything is working?

Basic intuition is to login to your analytics dashboard, and monitor the **Realtime** tab under **Report**.

You can also make use of this <a href="https://chrome.google.com/webstore/detail/google-analytics-debugger/jnkmfdileelhofjcijamephohjechhna?hl=en" rel="noopener noreferrer">handy chrome extension</a>, and make sure a **single** `page-view` event is triggered on page load and page navigation (browser history state change).

<img src="https://bish.al/_next/image?url=%2F_next%2Fstatic%2Fimage%2Fpublic%2Fassets%2Fblog%2Fhow-to-add-google-analytics-to-next-js-app%2Fanalytics-extension-console-log.ede40298d768e06b243a81dd1fe14660.webp&w=3840&q=75" width="600" height="969" alt="Expected log from Google Analytics extension in the console"/>

That's it, happy tracking. Use it responsibly. 🎉

<a href="https://bish.al/posts/how-to-add-google-analytics-to-next-js-app" target="_blank">Original post</a>