分析 (Analytics)

Next.js Speed Insights 允许您使用不同指标分析和测量页面性能。

您可以在 Vercel 部署 上零配置开始收集 真实体验评分 (Real Experience Score)

本文档其余部分描述了 Next.js Speed Insights 使用的内置转发器。

自定义实现

首先,您需要创建一个 自定义 App 组件并定义 reportWebVitals 函数:

pages/_app.js
export function reportWebVitals(metric) {
  console.log(metric)
}

function MyApp({ Component, pageProps }) {
  return <Component {...pageProps} />
}

export default MyApp

当页面上任何指标的最终值计算完成时,会触发此函数。您可以用它将结果记录到控制台或发送到特定端点。

函数返回的 metric 对象包含以下属性:

  • id:当前页面加载上下文中指标的唯一标识符
  • name:指标名称
  • startTime:性能条目的首次记录时间戳(以毫秒为单位,如适用)
  • value:性能条目的值或持续时间(以毫秒为单位)
  • label:指标类型(web-vitalcustom

跟踪的指标分为两种类型:

  • Web 核心指标 (Web Vitals)
  • 自定义指标 (Custom metrics)

Web 核心指标

Web 核心指标 (Web Vitals) 是一组用于衡量网页用户体验的关键指标,包含以下内容:

您可以使用 web-vital 标签处理所有这些指标的结果:

export function reportWebVitals(metric) {
  if (metric.label === 'web-vital') {
    console.log(metric) // 指标对象 ({ id, name, startTime, value, label }) 会被记录到控制台
  }
}

也可以单独处理每个指标:

export function reportWebVitals(metric) {
  switch (metric.name) {
    case 'FCP':
      // 处理 FCP 结果
      break
    case 'LCP':
      // 处理 LCP 结果
      break
    case 'CLS':
      // 处理 CLS 结果
      break
    case 'FID':
      // 处理 FID 结果
      break
    case 'TTFB':
      // 处理 TTFB 结果
      break
    case 'INP':
      // 处理 INP 结果(注意:INP 仍是实验性指标)
      break
    default:
      break
  }
}

测量这些指标使用了第三方库 web-vitals。浏览器兼容性因具体指标而异,请参考浏览器支持部分了解支持的浏览器。

自定义指标

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

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

您可以使用 custom 标签处理所有这些指标的结果:

export function reportWebVitals(metric) {
  if (metric.label === 'custom') {
    console.log(metric) // 指标对象 ({ id, name, startTime, value, label }) 会被记录到控制台
  }
}

也可以单独处理每个指标:

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 (User Timing API) 的浏览器中均可使用。

将结果发送到外部系统

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

export function reportWebVitals(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 值可以手动构建指标分布(用于计算百分位数等)

export function reportWebVitals({ id, name, label, value }) {
  // 如果按照此示例初始化了 Google Analytics,请使用 `window.gtag`:
  // https://github.com/vercel/next.js/blob/canary/examples/with-google-analytics/pages/_app.js
  window.gtag('event', name, {
    event_category:
      label === 'web-vital' ? 'Web Vitals' : 'Next.js custom metric',
    value: Math.round(name === 'CLS' ? value * 1000 : value), // 值必须为整数
    event_label: id, // 当前页面加载的唯一 id
    non_interaction: true, // 避免影响跳出率
  })
}

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

TypeScript

如果使用 TypeScript,可以使用内置类型 NextWebVitalsMetric

import type { AppProps, NextWebVitalsMetric } from 'next/app'

function MyApp({ Component, pageProps }: AppProps) {
  return <Component {...pageProps} />
}

export function reportWebVitals(metric: NextWebVitalsMetric) {
  console.log(metric)
}

export default MyApp

On this page