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

Next.js アプリケーションにアナリティクスを追加する方法

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)
})

自作する

app/_components/web-vitals.js
'use client'
 
import { useReportWebVitals } from 'next/web-vitals'
 
export function WebVitals() {
  useReportWebVitals((metric) => {
    console.log(metric)
  })
}
app/layout.js
import { WebVitals } from './_components/web-vitals'
 
export default function Layout({ children }) {
  return (
    <html>
      <body>
        <WebVitals />
        {children}
      </body>
    </html>
  )
}

useReportWebVitals フックは 'use client' ディレクティブを必要とするため、最もパフォーマンスの高いアプローチは、ルートレイアウトがインポートする別のコンポーネントを作成することです。これにより、クライアント境界が WebVitals コンポーネントに限定されます。

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

Web Vitals

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

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

app/_components/web-vitals.tsx
'use client'
 
import { useReportWebVitals } from 'next/web-vitals'
 
export function WebVitals() {
  useReportWebVitals((metric) => {
    switch (metric.name) {
      case 'FCP': {
        // handle FCP results
      }
      case 'LCP': {
        // handle LCP results
      }
      // ...
    }
  })
}

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

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

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 への結果送信 について続きを読む。