アナリティクス
Next.jsにはパフォーマンスメトリクスの測定とレポート機能が組み込まれています。useReportWebVitals
フックを使用して自分でレポートを管理するか、またはVercelが提供するマネージドサービスを利用してメトリクスを自動的に収集・可視化できます。
独自実装
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がすべて含まれます:
- Time to First Byte (TTFB)
- First Contentful Paint (FCP)
- Largest Contentful Paint (LCP)
- First Input Delay (FID)
- Cumulative Layout Shift (CLS)
- Interaction to Next Paint (INP)
これらのメトリクスの結果はname
プロパティを使用して処理できます。
import { useReportWebVitals } from 'next/web-vitals'
function MyApp({ Component, pageProps }) {
useReportWebVitals((metric) => {
switch (metric.name) {
case 'FCP': {
// FCP結果を処理
}
case 'LCP': {
// LCP結果を処理
}
// ...
}
})
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':
// ハイドレーション結果を処理
break
case 'Next.js-route-change-to-render':
// ルート変更からレンダリングまでの結果を処理
break
case 'Next.js-render':
// レンダリング結果を処理
break
default:
break
}
}
これらのメトリクスはUser Timing APIをサポートするすべてのブラウザで動作します。
外部システムへの結果送信
結果を任意のエンドポイントに送信して、サイト上の実際のユーザーパフォーマンスを測定・追跡できます。例:
useReportWebVitals((metric) => {
const body = JSON.stringify(metric)
const url = 'https://example.com/analytics'
// 利用可能な場合は`navigator.sendBeacon()`を使用し、フォールバックとして`fetch()`を使用
if (navigator.sendBeacon) {
navigator.sendBeacon(url, body)
} else {
fetch(url, { body, method: 'POST', keepalive: true })
}
})
豆知識: Google Analyticsを使用する場合、
id
値を利用することで手動でメトリクス分布を構築できます(パーセンタイル計算など)
useReportWebVitals((metric) => { // この例のようにGoogle Analyticsを初期化した場合は`window.gtag`を使用: // https://github.com/vercel/next.js/blob/canary/examples/with-google-analytics/pages/_app.js window.gtag('event', metric.name, { value: Math.round( metric.name === 'CLS' ? metric.value * 1000 : metric.value ), // 値は整数である必要あり event_label: metric.id, // 現在のページロードに固有のID non_interaction: true, // バウンス率への影響を回避 }) })
Google Analyticsへの結果送信について詳しく読む