Next.jsのPreview Mode時はAnalyticsを無効化する

公開日時

ブログをGridsomeからNext.jsに移行するのが完了した。

Preview Modeを使うことで、Contentful管理画面で作成途中の記事も実際のサイト上で確認できるようになって非常に便利。

前回の記事でGoogle Analyticsを導入するようにしたが、Preview Mode時はAnalyticsを無効化するように改修することにした。

gtagのscript読み込みは pages/_document.tsx で設定しているため、PagePropsとして渡ってくるpreviewフラグを取得することができない。

Preview Modeが有効になっている場合はcookieに__next_preview_dataがセットされているので、このキーでPreview Modeかを判定することにした。

  • nookiesを追加

cookieのparseにはnookiesを利用する。

yarn add nookies
  • previewキーがセットされている場合は、ga-disable-GA_IDフラグをtrueにしてGAを無効化
import Document, { DocumentContext, Head, Html, Main, NextScript } from 'next/document'
import nookies from 'nookies'
import React from 'react'

import { GA_TRACKING_ID } from '@/lib/gtag'

type WithNonceProp = {
  preview: boolean
}

export default class MyDocument extends Document<WithNonceProp> {
  static async getInitialProps(ctx: DocumentContext) {
    const initialProps = await Document.getInitialProps(ctx)
    const cookies = nookies.get(ctx)
    const preview = cookies.__next_preview_data || false

    return {
      ...initialProps,
      preview,
    }
  }
  render() {
    const preview = this.props.preview

    return (
      <Html>
        <Head>
          <script
            async={true}
            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,
                });
                // ↓を追加
                ${preview ? "window['ga-disable-" + GA_TRACKING_ID + "'] = true;" : ''}
              `,
            }}
          />
        </Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    )
  }
}

これでPreview Mode時はGAを無効化できた。

より簡単な方法としては「Google アナリティクス オプトアウト アドオン」を入れるという手もある。

参考


Related #next.js

FigmaでSVG Octocatを作る その3

アウトライン化大事

Next.jsプロジェクトのGoogle Analytics V3をV4に更新する

トラッキングIDの差し替えのみで対応が完了した

Vercelで指定のブランチのみデプロイを実行する

Ignored Build Stepを設定した