コンテンツにスキップ

アナリティクス

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

独自に構築する

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 アナリティクスを使用している場合、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 アナリティクスへの結果の送信の詳細をご覧ください。