如何设置分析工具

Next.js 内置了测量和报告性能指标的支持。您既可以使用 useReportWebVitals 钩子自行管理报告,也可以选择 Vercel 提供的 托管服务 自动收集并可视化指标。

客户端插桩

对于更高级的分析和监控需求,Next.js 提供了 instrumentation-client.js|ts 文件,该文件会在应用前端代码开始执行前运行。这非常适合设置全局分析、错误追踪或性能监控工具。

要使用它,请在应用的根目录下创建 instrumentation-client.jsinstrumentation-client.ts 文件:

instrumentation-client.js
// 在应用启动前初始化分析
console.log('Analytics initialized')

// 设置全局错误追踪
window.addEventListener('error', (event) => {
  // 发送至您的错误追踪服务
  reportError(event.error)
})

自行构建

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

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

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

查看 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} />
}

自定义指标

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

  • 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 (User Timing 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
  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