NNext.js 中文网 GitHub

如何设置分析

使用 Next.js 衡量和跟踪页面性能

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

客户端检测#

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

要使用它,请在应用的根目录中创建一个 instrumentation-client.js 或 instrumentation-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 参考 了解更多信息。

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 钩子必须在 Client Component 中使用,请为 WebVitals 组件创建一个单独的文件,并在文件顶部、任何导入之前加上 'use client'。将该组件导入根布局,可将客户端边界限制在此模块及其导入内容中。

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

Web Vitals#

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} />
}
app/_components/web-vitals.tsx
'use client'

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

export function WebVitals() {
  useReportWebVitals((metric) => {
    switch (metric.name) {
      case 'FCP': {
        // 处理 FCP 结果
      }
      case 'LCP': {
        // 处理 LCP 结果
      }
      // ...
    }
  })
}
app/_components/web-vitals.js
'use client'

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

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

自定义指标#

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

  • Next.js-hydration:页面开始和完成水合所需的时间长度(以毫秒为单位)
  • Next.js-route-change-to-render:路由变更后页面开始渲染所需的时间长度(以毫秒为单位)
  • Next.js-render:路由变更后页面完成渲染所需的时间长度(以毫秒为单位)

你可以分别处理这些指标的所有结果:

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

这些指标适用于所有支持 User Timing API 的浏览器。

将结果发送到外部系统#

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

js
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 值可让你手动构建指标分布(以计算百分位数等)

js
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的内容。

Next.js 中文网