简介/指南/分析

如何为 Next.js 应用添加分析功能

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

自行构建

app/_components/web-vitals.js
'use client'

import { useReportWebVitals } from 'next/web-vitals'

export function WebVitals() {
  useReportWebVitals((metric) => {
    console.log(metric)
  })
}
app/layout.js
import { WebVitals } from './_components/web-vitals'

export default function Layout({ children }) {
  return (
    <html>
      <body>
        <WebVitals />
        {children}
      </body>
    </html>
  )
}

由于 useReportWebVitals 钩子需要 'use client' 指令,最高效的做法是创建一个单独的组件,由根布局导入。这样可以将客户端边界限制在 WebVitals 组件内。

查看 API 参考文档 获取更多信息。

Web 核心指标

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

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

'use client'

import { useReportWebVitals } from 'next/web-vitals'

export function WebVitals() {
  useReportWebVitals((metric) => {
    switch (metric.name) {
      case 'FCP': {
        // 处理 FCP 结果
      }
      case 'LCP': {
        // 处理 LCP 结果
      }
      // ...
    }
  })
}

将结果发送至外部系统

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

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