Chapter 09

Google Analytics 連携

Google Analytics 連携

https://github.com/vercel/next.js/tree/canary/examples/with-google-analytics

公式にチュートリアルがあるので参考にして実装していきます

/lib/gtag.ts

Google Analytics の PageView, イベント発火の関数を実装します

export const GA_TRACKING_ID = '<YOUR_GA_TRACKING_ID>'

export const pageview = (url) => {
  window.gtag('config', GA_TRACKING_ID, {
    page_path: url,
  })
}

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

npm install --save-dev @types/gtag.js を読み込んで、TypeScript 対応させます

https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/gtag.js

/pages/document.tsx

Google Analytics の設定を読み込みます

import Document, {
  Html, Head, Main, NextScript,
} from 'next/document';
import { GA_TRACKING_ID } from '../lib/gtag';

class MyDocument extends Document {
  render() {
    return (
      <Html lang="ja">
        <Head>
          <script
            async
            src={`https://www.googletagmanager.com/gtag/js?id=${GA_TRACKING_ID}`}
          />
          <script
            dangerouslySetInnerHTML={{
              __html: `
            window.dataLayer = window.dataLayer || [];
            function gtag(){dataLayer.push(arguments);}
            gtag('js', new Date());
            gtag('config', '${GA_TRACKING_ID}', {
              page_path: window.location.pathname,
            });
          `,
            }}
          />
        </Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    );
  }
}

export default MyDocument;

pages/_app.tsx

ページを遷移する毎に PageView を送信させます

import { useEffect } from 'react';
import { useRouter } from 'next/router';
import { pageview } from '../lib/gtag';

function MyApp({ Component, pageProps }) {
  const router = useRouter();
  useEffect(() => {
    const handleRouteChange = (url) => {
      pageview(url);
    };
    router.events.on('routeChangeComplete', handleRouteChange);
    return () => {
      router.events.off('routeChangeComplete', handleRouteChange);
    };
  }, [router.events]);

  return <Component {...pageProps} />;
}

export default MyApp;