Skip to content

分析

¥Analytics

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

¥Next.js has built-in support for measuring and reporting performance metrics. You can either use the useReportWebVitals hook to manage reporting yourself, or alternatively, Vercel provides a managed service to automatically collect and visualize metrics for you.

客户端检测

¥Client Instrumentation

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

¥For more advanced analytics and monitoring needs, Next.js provides a instrumentation-client.js|ts file that runs before your application's frontend code starts executing. This is ideal for setting up global analytics, error tracking, or performance monitoring tools.

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

¥To use it, create an instrumentation-client.js or instrumentation-client.ts file in your application's root directory:

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

构建你自己的

¥Build Your Own

jsx
'use client'

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

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

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

由于 useReportWebVitals 钩子需要 "use client" 指令,因此性能最佳的方法是创建根布局导入的单独组件。这将客户端边界专门限制为 WebVitals 组件。

¥Since the useReportWebVitals hook requires the "use client" directive, the most performant approach is to create a separate component that the root layout imports. This confines the client boundary exclusively to the WebVitals component.

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

¥View the API Reference for more information.

网络生命体

¥Web Vitals

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

¥Web Vitals are a set of useful metrics that aim to capture the user experience of a web page. The following web vitals are all included:

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

¥You can handle all the results of these metrics using the name property.

tsx
'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
      }
      // ...
    }
  })
}
jsx
'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
      }
      // ...
    }
  })
}

将结果发送到外部系统

¥Sending results to external systems

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

¥You can send results to any endpoint to measure and track real user performance on your site. For example:

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

需要了解:如果你使用 谷歌分析,则使用 id 值可以让你手动构建度量分布(以计算百分位数等)

¥Good to know: If you use Google Analytics, using the id value can allow you to construct metric distributions manually (to calculate percentiles, etc.)

js
> useReportWebVitals((metric) => {
>   // Use `window.gtag` if you initialized Google Analytics as this example:
>   // 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
>     ), // values must be integers
>     event_label: metric.id, // id unique to current page load
>     non_interaction: true, // avoids affecting bounce rate.
>   })
> })
> ```

> 阅读有关 [将结果发送至 Google Analytics](https://github.com/GoogleChrome/web-vitals#send-the-results-to-google-analytics) 的更多信息。
>
> ¥Read more about [sending results to Google Analytics](https://github.com/GoogleChrome/web-vitals#send-the-results-to-google-analytics).

Next.js v15.3 中文网 - 粤ICP备13048890号