コンテンツにスキップ
Pages Routerガイドアナリティクス

アナリティクスの設定方法

Next.jsには、パフォーマンスメトリクスを測定および報告するための組み込みサポートがあります。useReportWebVitalsフックを使用して自分でレポートを管理することもできます。あるいは、Vercelは、メトリクスを自動的に収集して可視化するための管理サービスも提供しています。

クライアントインストルメンテーション

より高度なアナリティクスおよびモニタリングのニーズに対応するため、Next.jsはinstrumentation-client.js|tsファイルを提供しており、アプリケーションのフロントエンドコードの実行前に実行されます。これは、グローバルアナリティクス、エラー追跡、またはパフォーマンスモニタリングツールの設定に最適です。

使用するには、アプリケーションのルートディレクトリにinstrumentation-client.jsまたはinstrumentation-client.tsファイルを作成します。

instrumentation-client.js
// Initialize analytics before the app starts
console.log('Analytics initialized')
 
// Set up global error tracking
window.addEventListener('error', (event) => {
  // Send to your error tracking service
  reportError(event.error)
})

自分で構築する

pages/_app.js
import { useReportWebVitals } from 'next/web-vitals'
 
function MyApp({ Component, pageProps }) {
  useReportWebVitals((metric) => {
    console.log(metric)
  })
 
  return <Component {...pageProps} />
}

詳細については、APIリファレンスをご覧ください。

Web Vitals

Web Vitals は、ウェブページのユーザーエクスペリエンスを捉えることを目的とした有用なメトリクスのセットです。以下の Web Vitals がすべて含まれています。

これらのメトリクスのすべての結果は、name プロパティを使用して処理できます。

pages/_app.js
import { useReportWebVitals } from 'next/web-vitals'
 
function MyApp({ Component, pageProps }) {
  useReportWebVitals((metric) => {
    switch (metric.name) {
      case 'FCP': {
        // handle FCP results
      }
      case 'LCP': {
        // handle LCP results
      }
      // ...
    }
  })
 
  return <Component {...pageProps} />
}

カスタムメトリクス

上記にリストされているコアメトリクスに加えて、ページのハイドレーションとレンダリングにかかる時間を測定する追加のカスタムメトリクスがいくつかあります。

  • Next.js-hydration: ページがハイドレーションを開始してから完了するまでの時間(ミリ秒)。
  • Next.js-route-change-to-render: ルート変更後にページがレンダリングを開始するまでの時間(ミリ秒)。
  • Next.js-render: ルート変更後にページがレンダリングを完了するまでの時間(ミリ秒)。

これらのメトリクスのすべての結果を個別に処理できます。

export function reportWebVitals(metric) {
  switch (metric.name) {
    case 'Next.js-hydration':
      // handle hydration results
      break
    case 'Next.js-route-change-to-render':
      // handle route-change to render results
      break
    case 'Next.js-render':
      // handle render results
      break
    default:
      break
  }
}

これらのメトリクスは、User Timing APIをサポートするすべてのブラウザで機能します。

結果を外部システムに送信する

サイトの実際のユーザーパフォーマンスを測定および追跡するために、結果を任意のエンドポイントに送信できます。例:

useReportWebVitals((metric) => {
  const body = JSON.stringify(metric)
  const url = 'https://example.com/analytics'
 
  // Use `navigator.sendBeacon()` if available, falling back to `fetch()`.
  if (navigator.sendBeacon) {
    navigator.sendBeacon(url, body)
  } else {
    fetch(url, { body, method: 'POST', keepalive: true })
  }
})

知っておくと便利: Google Analytics を使用する場合、id 値を使用すると、メトリクスの分布を手動で構築できます(パーセンタイルなどを計算するため)。

useReportWebVitals((metric) => {
  // Use `window.gtag` if you initialized Google Analytics as this example:
  // https://github.com/vercel/next.js/blob/canary/examples/with-google-analytics
  window.gtag('event', metric.name, {
    value: Math.round(
      metric.name === 'CLS' ? metric.value * 1000 : metric.value
    ), // values must be integers
    event_label: metric.id, // id unique to current page load
    non_interaction: true, // avoids affecting bounce rate.
  })
})

Google Analytics への結果送信 について続きを読む。