アナリティクス
Next.jsには、パフォーマンスメトリクスを測定および報告するための組み込みサポートがあります。useReportWebVitals
フックを使用してレポートを自分で管理するか、またはVercelがメトリクスを自動的に収集して視覚化するためのマネージドサービスを提供しています。
独自構築
pages/_app.js
import { useReportWebVitals } from 'next/web-vitals'
function MyApp({ Component, pageProps }) {
useReportWebVitals((metric) => {
console.log(metric)
})
return <Component {...pageProps} />
}
詳細については、APIリファレンスを参照してください。
ウェブバイタル
ウェブバイタルは、Webページのユーザーエクスペリエンスを把握することを目的とした便利なメトリクスのセットです。以下のウェブバイタルがすべて含まれています。
- Time to First Byte (TTFB)
- First Contentful Paint (FCP)
- Largest Contentful Paint (LCP)
- 初回入力遅延 (FID)
- 累積レイアウトシフト (CLS)
- Interaction to Next Paint (INP)
これらのメトリクスのすべての結果は、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への結果の送信について詳しくはこちらをご覧ください。
お役に立ちましたか?