Capítulo 383 de 456
useReportWebVitals (from next/web-vitals) reports Core Web Vitals and Next.js-specific timing metrics to any analytics service.
metric object: id, name, delta, entries, navigationType ("navigate", "reload", "prerender", "back-forward", "back-forward-cache", "restore"), rating ("good"/"needs-improvement"/"poor"), value.Next.js-hydration, Next.js-route-change-to-render, Next.js-render.import { useReportWebVitals } from 'next/web-vitals'
const logWebVitals = (metric) => {
console.log(metric)
}
function MyApp({ Component, pageProps }) {
useReportWebVitals(logWebVitals)
return <Component {...pageProps} />
}
_app.js.function postWebVitals(metric) {
const body = JSON.stringify(metric)
const url = 'https://example.com/analytics'
if (navigator.sendBeacon) {
navigator.sendBeacon(url, body)
} else {
fetch(url, { body, method: 'POST', keepalive: true })
}
}
useReportWebVitals(postWebVitals)
sendBeacon with fetch fallback.metric field | Meaning |
|---|---|
id | unique id per page load |
name | metric name (TTFB, FCP, LCP, FID, CLS, INP, or custom) |
delta | change from previous value |
entries | related PerformanceEntry[] |
navigationType | how navigation was triggered |
rating | good | needs-improvement | poor |
value | measured value (ms) |
Math.round(value * 1000) for CLS since GA requires integers.pages/_app.js to capture app-wide vitals.hydration, route-change-to-render, render) work in any browser supporting the User Timing API.metric.name to route different vitals to different handlers.