3 easy steps to set up Google Analytics in a Next.js application

In this article, we will walk through a step-by-step guide to setting up Google Analytics in a Next.js application. I will show you the way I set up Google Analytics on both my website and most other Next.js websites I work on. Let's get started!

Get Google tag ID

The first step is to get a Google Tag ID if you don't have one already. Follow the steps below to get your Google Tag ID.

For a more detailed guide, refer to the official Google Analytics setup guide.

Setup in code

Once you have the Google tag ID, put it in an environment variable named NEXT_PUBLIC_GOOGLE_TAG_ID. Next, install the @types/gtag.js package as a dev dependency, which provides us with type definitions for the Analytics scripts. After that, create a gtag.ts file with the following code:

export const TAG_ID = process.env.NEXT_PUBLIC_GOOGLE_TAG_ID;

type GtagEvent = {
  action: string;
  category: string;
  label: string;
  value: number;
};

export const pageview = (url: URL) => {
  window.gtag('config', TAG_ID as string, {
    page_path: url,
  });
};

export const event = ({ action, category, label, value }: GtagEvent) => {
  window.gtag('event', action, {
    event_category: category,
    event_label: label,
    value: value,
  });
};

In this code, we've created and exported a variable TAG_ID referring to the Google Tag ID from the environment variable. We've also exported the pageview and the event functions, both provided by Google. We've just typed the parameters of the functions.

Next, we'll add a few scripts to the _app.tsx file. Open the _app.tsx file, import the useRouter hook, and import everything as gtag from the gtag.ts file. After that, add the following code inside the App component.

const router = useRouter();

useEffect(() => {
  const handleRouteChange = (url: URL) => {
    gtag.pageview(url);
  };
  router.events.on('routeChangeComplete', handleRouteChange);
  return () => {
    router.events.off('routeChangeComplete', handleRouteChange);
  };
}, [router.events]);

The above useEffect hook, which is provided by Google, runs when the router events change. Within the hook, it runs the handleRouteChange function on the routeChangeComplete event.

Notice that the useEffect hook also returns a cleanup function to remove the routeChangeComplete event, which is one of the best practices.

If you're curious, I have an article on Understanding the React ‘useEffect’ hook and its practical applications that provides in-depth insights.

Anyway, let's now import the Script tag from next/script and add the following code within the return statement of the _app.tsx file:

<Script
  strategy='afterInteractive'
  src={`https://www.googletagmanager.com/gtag/js?id=${gtag.TAG_ID}`}
/>
<Script
  id='gtag'
  strategy='afterInteractive'
  dangerouslySetInnerHTML={{
    __html: `
      window.dataLayer = window.dataLayer || [];
      function gtag(){dataLayer.push(arguments);}
      gtag('js', new Date());
      gtag('config', '${gtag.TAG_ID}', {
        page_path: window.location.pathname,
      });
    `,
  }}
/>

In this code, we've used two more scripts provided by Google. Make sure to set the strategy as 'afterInteractive' so these scripts run only after the page content loads.

Test the integration

Now, open the browser dev tools, go to the Network tab, and refresh the page. Look for any fetch request with your TAG_ID. If you find one, your Google Analytics is set up correctly. Otherwise, review the steps and check for potential errors.

That's it! Your Next.js application now has a successful Google Analytics integration. Hope you found this article helpful. Feel free to share this content with your friends who might also find it useful.

Share this article with your friends

Copy URL

Elevate your JavaScript and freelance journey

Supercharge your JavaScript skills and freelance career. Subscribe now for expert tips and insights!