How to set up analytics
Next.js 内置了对测量和报告性能指标的支持。你可以使用 useReportWebVitals 钩子自行管理报告,或者使用 Vercel 提供的托管服务来自动收集和可视化指标。
客户端检测
对于更高级的分析和监控需求,Next.js 提供了一个 instrumentation-client.js|ts 文件,该文件在应用程序的前端代码开始执行之前运行。这非常适合设置全局分析、错误跟踪或性能监控工具。
要使用它,请在应用程序的根目录中创建一个 instrumentation-client.js 或 instrumentation-client.ts 文件:
instrumentation-client.js
// Initialize analytics before the app starts
console.log('Analytics initialized')
 
// Set up global error tracking
window.addEventListener('error', (event) => {
  // Send to your error tracking service
  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 Vitals
Web Vitals 是一组有用的指标,旨在捕捉网页的用户体验。包括以下所有 web vitals:
- Time to First Byte (TTFB)
- First Contentful Paint (FCP)
- Largest Contentful Paint (LCP)
- First Input Delay (FID)
- Cumulative Layout Shift (CLS)
- Interaction to Next Paint (INP)
你可以使用 name 属性处理这些指标的所有结果。
pages/_app.js
import { useReportWebVitals } from 'next/web-vitals'
 
function MyApp({ Component, pageProps }) {
  useReportWebVitals((metric) => {
    switch (metric.name) {
      case 'FCP': {
        // handle FCP results
      }
      case 'LCP': {
        // handle LCP results
      }
      // ...
    }
  })
 
  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的所有浏览器中都可以工作。
将结果发送到外部系统
你可以将结果发送到任何端点,以测量和跟踪你网站上的真实用户性能。例如:
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的信息。