アナリティクス
Next.jsにはパフォーマンスメトリクスの測定とレポート機能が組み込まれています。useReportWebVitals
フックを使用して自分でレポートを管理するか、またはVercelが提供するマネージドサービスを利用してメトリクスを自動的に収集・可視化できます。
独自実装
'use client'
import { useReportWebVitals } from 'next/web-vitals'
export function WebVitals() {
useReportWebVitals((metric) => {
console.log(metric)
})
}
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がすべて含まれます:
- 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
プロパティを使用して処理できます。
'use client'
import { useReportWebVitals } from 'next/web-vitals'
export function WebVitals() {
useReportWebVitals((metric) => {
switch (metric.name) {
case 'FCP': {
// FCP結果を処理
}
case 'LCP': {
// LCP結果を処理
}
// ...
}
})
}
'use client'
import { useReportWebVitals } from 'next/web-vitals'
export function WebVitals() {
useReportWebVitals((metric) => {
switch (metric.name) {
case 'FCP': {
// FCP結果を処理
}
case 'LCP': {
// LCP結果を処理
}
// ...
}
})
}
外部システムへの結果送信
結果を任意のエンドポイントに送信して、サイト上の実際のユーザーパフォーマンスを測定・追跡できます。例:
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への結果送信について詳しく読む