N Next.js 中文
原文 ↗

如何为你的 Next.js 应用添加分析

使用 Next.js Speed Insights 衡量并跟踪页面性能

更新于 2026-10-05Next.js 16.4.6

Next.js 内置了对衡量和报告性能指标的支持。你可以使用 useReportWebVitals hook 自行管理报告,或者,Vercel 提供了一个托管服务来为你自动收集和可视化指标。

客户端插桩

对于更高级的分析和监控需求,Next.js 提供了一个 instrumentation-client.js|ts 文件,它会在你的应用前端代码开始执行之前运行。这是设置全局分析、错误跟踪或性能监控工具的理想选择。

要使用它,请在应用的根目录中创建一个 instrumentation-client.js 或 instrumentation-client.ts 文件:

instrumentation-client.jsjs
// 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)
})

自行构建

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

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

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

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

由于 useReportWebVitals hook 必须在客户端组件中使用,请为 WebVitals 组件创建一个单独的文件,并在文件顶部、任何导入之前加上 'use client'。将此组件导入根布局,以使客户端边界仅限于此模块及其导入。

查看 API 参考 以了解更多信息。

Web Vitals

Web Vitals 是一组有用的指标,旨在捕捉网页的用户体验。以下 Web Vitals 均已包含:

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

TypeScript

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

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

export function WebVitals() {
  useReportWebVitals((metric) => {
    switch (metric.name) {
      case 'FCP': {
        // handle FCP results
      }
      case 'LCP': {
        // handle LCP results
      }
      // ...
    }
  })
}

JavaScript

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

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

export function WebVitals() {
  useReportWebVitals((metric) => {
    switch (metric.name) {
      case 'FCP': {
        // handle FCP results
      }
      case 'LCP': {
        // handle LCP results
      }
      // ...
    }
  })
}

将结果发送到外部系统

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

useReportWebVitals((metric) => {
  const body = JSON.stringify(metric)
  const url = 'https://example.com/analytics'

  // Use `navigator.sendBeacon()` if available, falling back to `fetch()`.
  if (navigator.sendBeacon) {
    navigator.sendBeacon(url, body)
  } else {
    fetch(url, { body, method: 'POST', keepalive: true })
  }
})

须知:

如果你使用 Google Analytics,使用 id 值可以让你手动构建指标分布(来计算百分位数, 等)

```jsuseReportWebVitals((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](https://github.com/GoogleChrome/web-vitals#send-the-results-to-google-analytics)的内容。