useReportWebVitals

useReportWebVitals 钩子允许您上报 核心 Web 指标 (Core Web Vitals),并可与您的分析服务结合使用。

pages/_app.js
import { useReportWebVitals } from 'next/web-vitals'

function MyApp({ Component, pageProps }) {
  useReportWebVitals((metric) => {
    console.log(metric)
  })

  return <Component {...pageProps} />
}

useReportWebVitals

作为钩子参数传递的 metric 对象包含以下属性:

  • id:当前页面加载上下文中该指标的唯一标识符
  • name:性能指标名称。可能值包括特定于 Web 应用的 Web 指标 名称(TTFB、FCP、LCP、FID、CLS)
  • delta:当前指标值与先前值的差值。该值通常以毫秒为单位,表示指标值随时间的变化
  • entries:与指标关联的 性能条目 (Performance Entries) 数组。这些条目提供与指标相关的性能事件的详细信息
  • navigationType:指示触发指标收集的 导航类型。可能值包括 "navigate""reload""back_forward""prerender"
  • rating:指标值的定性评级,提供性能评估。可能值为 "good"(良好)、"needs-improvement"(需改进)和 "poor"(差)。评级通常通过将指标值与预定义阈值进行比较来确定
  • value:性能条目的实际值或持续时间,通常以毫秒为单位。该值提供了指标跟踪的性能方面的定量测量。值的来源取决于具体测量的指标,可能来自各种 性能 API (Performance API)

Web 指标

Web 指标 (Web Vitals) 是一组旨在捕捉网页用户体验的有用指标。包含以下所有核心指标:

您可以使用 name 属性处理所有这些指标的结果。

pages/_app.js
import { useReportWebVitals } from 'next/web-vitals'

function MyApp({ Component, pageProps }) {
  useReportWebVitals((metric) => {
    switch (metric.name) {
      case 'FCP': {
        // 处理 FCP 结果
      }
      case 'LCP': {
        // 处理 LCP 结果
      }
      // ...
    }
  })

  return <Component {...pageProps} />
}

自定义指标

除了上述核心指标外,还有一些额外的自定义指标用于测量页面水合 (hydrate) 和渲染所需时间:

  • Next.js-hydration:页面开始和完成水合所需时间(毫秒)
  • Next.js-route-change-to-render:路由变更后页面开始渲染所需时间(毫秒)
  • Next.js-render:路由变更后页面完成渲染所需时间(毫秒)

您可以分别处理这些指标的结果:

pages/_app.js
import { useReportWebVitals } from 'next/web-vitals'

function MyApp({ Component, pageProps }) {
  useReportWebVitals((metric) => {
    switch (metric.name) {
      case 'Next.js-hydration':
        // 处理水合结果
        break
      case 'Next.js-route-change-to-render':
        // 处理路由变更到渲染的结果
        break
      case 'Next.js-render':
        // 处理渲染结果
        break
      default:
        break
    }
  })

  return <Component {...pageProps} />
}

这些指标在所有支持 用户计时 API (User Timing API) 的浏览器中均有效。

在 Vercel 上的使用

Vercel 速度洞察 (Vercel Speed Insights) 在 Vercel 部署中会自动配置,无需使用 useReportWebVitals。此钩子在本地开发或使用其他分析服务时非常有用。

将结果发送到外部系统

您可以将结果发送到任何端点以测量和跟踪网站上的真实用户性能。例如:

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, // 当前页面加载的唯一标识符
    non_interaction: true, // 避免影响跳出率
  });
}

了解更多关于 将结果发送到 Google Analytics 的信息。

On this page