Data analytics is a must if you want to keep track of the number of visitors your website is getting. There are different ways you can add analytics to your project, including Google Analytics. It’s a free service and is relatively simple to set up.

Learn how to add Google Analytics to your site using Next.js, a React framework for building SEO-friendly websites.

Setting Up Google Analytics

Google Analytics provides insights into the behavior of people visiting your website. It tells you which pages get the number of views and gives you audience data like location, age, interest, and the device they use. This data can help make decisions about the direction your business should take to be successful.

To get started, visit the analytics dashboard and create a new account by following these steps:

  1. Click the Create Account button in the admin tab to create a new account.
  2. Add an account name under the Account setup section.
  3. Create the analytics property by providing a name.
  4. Add the business details. Select the options that apply to your website.
  5. Click the Create button to finish setting up the property.
  6. Click on web stream to specify the data stream Google Analytics should track.
  7. Specify the URL to your website and give the data stream a name.
  8. Click on tagging instructions and get the script you will use on your website.
    Tagging instructions
  9. Copy the measurement ID (the tracking code) to use later.
    Google analytics measurementid

Once you get the tracking code, you can set up the Next.js project.

Setting Up the Next.js Project

If you don't already have a Next.js project set up, see the Next.js official guide to get started.

When you created the Global site tag property, you got a script like this:

        <!-- Google tag (gtag.js) -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXX"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());
  gtag('config', 'G-NHVWK8L97D');
</script>

You need to add this script to the head tag of your website. In Next.js, you use the Script component from next/script. This component is an extension of the HTML script tag. It allows you to include third-party scripts to your Next.js website and set their loading strategy, improving performance.

The Next.js Script component offers different loading strategies. The “afterinteractive” strategy is suitable for an analytics script. This means it will load after the page is interactive.

        import Script from "next/script"
<Script src="" strategy="afterInteractive" />

Open the pages/_app.js file and import the Script component at the top.

        import Script from 'next/script'

Next, modify the return statement of the App component to include the script tag from Google analytics.

        import '../styles/globals.css'
import Layout from '../components/Layout/Layout'
import Script from 'next/script'
 
function MyApp({ Component, pageProps }) {
  return (
    <>
    <Script strategy="afterInteractive" src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXX"/>
    <Script
      id='google-analytics'
      strategy="afterInteractive"
      dangerouslySetInnerHTML={{
        __html: `
          window.dataLayer = window.dataLayer || [];
          function gtag(){dataLayer.push(arguments);}
          gtag('js', new Date());
          gtag('config', 'G-XXXXXXX', {
            page_path: window.location.pathname,
          });
        `,
        }}
    />
    <Layout>
      <Component {...pageProps} />
    </Layout>
    </>
  )
}
 
export default MyApp

Note that this tag is slightly different from the one Google Analytics provides. It uses dangerouslySetInnerHTML and includes a loading strategy. They, however, work the same.

Remember to replace G-XXXXXXX with your tracking code. It is also advisable to store the tracking code in a .env file to keep it secret.

Adding Google Analytics to a Single Page Application

You can use the script tag above for a regular website and leave it at that. However, for a single-page application like a Next.js website, you need to take a few extra steps.

A single-page application (SPA) is a website that loads all content upfront, in response to an initial request. The browser loads content dynamically as a user clicks on links to navigate the site. It does not make a page request, only the URL changes.

This is different for Next.js pages that use getServerSideProps as the browser renders those on request.

The Google tag works by recording a page view when a new page loads. So, for SPAs, the Google tag is only executed once, when the page initially loads. Therefore, you must manually record the views as the user navigates to different pages.

See the single-page measurement Google Analytics guide to learn more.

To manually record page views in Next.js using the gtag script, create a new folder called lib and add a new file, gtag.js.

        export const GA_MEASUREMENT_ID = process.env.GA_MEASUREMENT_ID;
 
export const pageview = () => {
  window.gtag("config", GA_MEASUREMENT_ID, {
    page_path: url,
  });
};
 
export const event = ({ action, category, label, value }) => {
  window.gtag("event", action, {
    event_category: category,
    event_label: label,
    value,
  });
};

Next, modify /pages/_app.js to use these functions and track page views in the useEffect hook.

        import '../styles/globals.css'
import Layout from '../components/Layout/Layout'
import Script from 'next/script'
import { useRouter } from 'next/router';
import { useEffect } from "react";
import * as gtag from "../lib/gtag"
 
function MyApp({ Component, pageProps }: AppProps) {
  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=G-XXXXXX"></Script>
    <Script
      id='google-analytics'
      strategy="afterInteractive"
      dangerouslySetInnerHTML={{
        __html: `
          window.dataLayer = window.dataLayer || [];
          function gtag(){dataLayer.push(arguments);}
          gtag('js', new Date());
          gtag('config', 'G-XXXXXX', {
            page_path: window.location.pathname,
          });
        `,
        }}
    />
    <Layout>
      <Component {...pageProps} />
    </Layout>
    </>
  )
}

export default MyApp

This example uses the useRouter and useEffect hooks to record a page view every time the user navigates to another page.

Call the useRouter method from next/router and assign it to the router variable. In the useEffect hook, listen to the routeChangeComplete event on the router. When the event fires, record a page view by calling the handleRouteChange function.

The useEffect hook's return statement unsubscribes from the routeChangeComplete event with the ‘off’ method.

Use Google Analytics to Collect User Data

Data is hugely beneficial to making good decisions, and adding Google Analytics to your website is one way to collect it.

You can add Google Analytics to a Next.js project using hooks to ensure you record all the page views even when a page uses client-side routing. Now you can see how many views your site gets on your Google Analytics dashboard.