1: posts
Reading ModeRO
$ cat 20210910_analytics.md

#Using Universal Analytics and GA4 together in Next.js

Date:2021-09-10 (Fri)
>How I configured both generations of Google Analytics and tracked page views as readers navigated a Next.js site.

##Table of Contents

##Introduction

I’ve been working on my blog again.

This time I added Google Analytics to understand how people visit the site.
There are a few things to watch for when using Google Analytics with Next.js, especially when running UA and GA4 together.

I hope this will be helpful for people who build websites with Next.js in the future.

##Universal Analytics and GA4

Google Analytics is a well-known web page traffic analysis service.
As for Google Analytics itself, there is a lot of information available if you look into it, so we will not provide any further explanation in this article.

When I set this up, Google Analytics offered two versions:

  • Universal Analytics (UA)
  • Google Analytics 4 (GA4)

UA was the established version. GA4 was the new generation, launched in October 2020.

I considered using GA4 alone, but it was a substantial redesign and still felt immature at the time.
On the other hand, GA4 looked like the direction things were heading.

One option for those of us who wanted both was to run UA and GA4 in parallel.
That let me use the familiar UA reports while collecting historical data in GA4 for the eventual transition.
I wanted both, so that’s the approach I took.

##Using Google Analytics with Next.js

The usual setup tracks visits by adding a script like this to <Head>:

HTML
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=(測定ID)"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag() {
    dataLayer.push(arguments);
  }
  gtag('js', new Date());

  gtag('config', '(測定ID)');
</script>

There are a couple of details to watch for in Next.js.

###UA and client-side page changes

Next.js can navigate between pages by updating the URL with JavaScript.
The script in <Head> detects the initial visit. With UA, it doesn’t see subsequent client-side route changes on its own.
I therefore had to send a page view explicitly on navigation.
I used next/router to do that.

I’ll show the implementation below.

###GA4 can detect page changes automatically

This is where I got stuck.

In my setup, GA4 detected the JavaScript-driven navigation automatically.
Initially I also sent a manual event to GA4 from next/router, just as I did for UA.
When I tested it, a single navigation registered two page views.
I’d run into double counting.
That made the visit totals unreliable.

There are quite a few articles online on how to use Google Analytics with Next.js, and I was able to quickly reach point 1 of the precautions.
However, I don't think there are any articles that clearly explain this yet.
Since you won't notice if you don't carefully verify the operation, I suspect that many people are still operating with double counting.

##An implementation example

Taking the aforementioned notes into consideration, I implemented it as follows.
Note that I have referred to the following article for implementation.

###Setting environment variables

First, we will describe the measurement IDs for UA and GA4 as environmental variables.

.env.local
NEXT_PUBLIC_UA_ID=(UAの測定ID)
NEXT_PUBLIC_GA4_ID=(GA4の測定ID)

Of course, this is setting environment variables in a local environment, so in the production environment, it will be set as an environment variable in a deployment platform such as Vercel.

Create a file to read in this environment variable.
Additionally, to be able to use it later, we will also implement the pageview function that transmits page access to Google Analytics.

gtag.tsx
export const GA4_TRACKING_ID = process.env.NEXT_PUBLIC_GA4_ID;
export const UA_TRACKING_ID = process.env.NEXT_PUBLIC_UA_ID;

// https://developers.google.com/analytics/devguides/collection/gtagjs/pages
export const pageview = (url: string) => {
  if (UA_TRACKING_ID) {
    window.gtag("config", UA_TRACKING_ID, {
      page_path: url,
    });
  }
};

In this case, an error occurs because there is no type definition for gtag.
Installing @types/gtag.js can resolve this.

yand add -D @types/gtag.js

###Adding the scripts to Head

Next, we will implement the portion to be described in the <Head> section.

GoogleAnalytics.tsx
import { GA4_TRACKING_ID, UA_TRACKING_ID } from "src/libs/gtag";

export const GoogleAnalytics = () => {
  let scriptText = `
    window.dataLayer = window.dataLayer || [];
    function gtag(){dataLayer.push(arguments);}
    gtag('js', new Date());
  `;
  if (GA4_TRACKING_ID) {
    scriptText += `
      gtag('config', '${GA4_TRACKING_ID}', {
        page_path: window.location.pathname,
      });
    `;
  }
  if (UA_TRACKING_ID) {
    scriptText += `
      gtag('config', '${UA_TRACKING_ID}', {
        page_path: window.location.pathname,
      });
    `;
  }
  return (
    <>
      {(GA4_TRACKING_ID || UA_TRACKING_ID) && (
        <>
          <script
            async
            src={`https://www.googletagmanager.com/gtag/js?id=${GA4_TRACKING_ID}`}
          />
          <script
            dangerouslySetInnerHTML={{
              // eslint-disable-next-line @typescript-eslint/naming-convention
              __html: scriptText,
            }}
          />
        </>
      )}
    </>
  );
};

This is called from _document.tsx.

_document.tsx
import Document, { Head, Html, Main, NextScript } from "next/document";
import { GoogleAnalytics } from "src/component/GoogleAnalytics";

export default class MyDocument extends Document {
  render() {
    return (
      <Html lang="ja">
        <Head>
          <GoogleAnalytics />
        </Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    );
  }
}

This should allow tracking when initially accessing the site.

###Tracking navigation in UA

Finally, to track on UA, we will make sure that access can be detected even during page transitions in JavaScript.
Specifically, we detect page transitions using next/router and execute the pageview function that we implemented earlier.

usePageView.ts
import { useRouter } from "next/router";
import { useEffect } from "react";
import { pageview, UA_TRACKING_ID } from "src/libs/gtag";

export const usePageView = () => {
  const router = useRouter();

  useEffect(() => {
    if (UA_TRACKING_ID) {
      const handleRouteChange = (
        path: string,
        { shallow }: { shallow: boolean }
      ) => {
        if (!shallow) {
          pageview(path);
        }
      };

      router.events.on("routeChangeComplete", handleRouteChange);
      return () => {
        router.events.off("routeChangeComplete", handleRouteChange);
      };
    }
  }, [router.events]);
};

You can call this from _app.tsx!

_app.tsx
import { AppProps } from "next/app";
import { usePageView } from "src/hooks/usePageView";

const App = ({ Component, pageProps }: AppProps) => (
  usePageView();

  return (
    <>
      <Component {...pageProps} />
    </>
  )
)

export default App;

##Open questions

With the implementation mentioned above, we were able to achieve the goal of combining Google Analytics UA and GA4 with Next.js.
However, there was something I wanted to improve even more.
That's delayed loading of scripts.

Starting with Next.js 11, next/script has been implemented, allowing for delayed script loading.
For things like Google Analytics Scripts, it's enough to load them after you've fully loaded the page, rather than during the first page load.
As a result, page rendering speeds up and performance improves.

In this article it was mentioned about delayed loading using next/script, but unfortunately it didn't work correctly in my environment (it doesn't count page access).
I want to write another article if it goes well in the future.

##Wrapping up

I finally got UA and GA4 working together in Next.js.
I want to understand how readers use the blog, and for those measurements to mean anything I need to be able to trust the page-view counts.
I hope these details help if you run into the same problem.

## Comments

"20210910_analytics.md" [readonly]2L, 8553B
utf-8100%