分析 (Analytics)

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 核心指标 (Web Vitals)

Web 核心指标 是一组用于衡量网页用户体验的关键指标。包含以下所有指标:

您可以通过 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: 路由变更后页面完成渲染的时间(毫秒)

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

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
  }
}

这些指标在所有支持 用户计时 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 的信息。

On this page