Next.js 内置了对测量和报告性能指标的支持。你可以使用 useReportWebVitals Hook 自行管理报告,或者,Vercel 提供了一个 托管服务 来为你自动收集和可视化指标。
为了满足更高级的分析和监控需求,Next.js 提供了一个 instrumentation-client.js|ts 文件,该文件在应用程序前端代码开始执行之前运行。这非常适合用于设置全局分析、错误跟踪或性能监控工具。
要使用它,请在应用程序的根目录中创建一个 instrumentation-client.js 或 instrumentation-client.ts 文件:
// 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)
})import { useReportWebVitals } from 'next/web-vitals'
function MyApp({ Component, pageProps }) {
useReportWebVitals((metric) => {
console.log(metric)
})
return <Component {...pageProps} />
}查看 API 参考 获取更多信息。
'use client'
import { useReportWebVitals } from 'next/web-vitals'
export function WebVitals() {
useReportWebVitals((metric) => {
console.log(metric)
})
}import { WebVitals } from './_components/web-vitals'
export default function Layout({ children }) {
return (
<html>
<body>
<WebVitals />
{children}
</body>
</html>
)
}由于
useReportWebVitalsHook 需要'use client'指令,因此性能最佳的方法是创建一个单独的组件,并由根布局导入。这会将客户端边界(client boundary)仅限于WebVitals组件。
查看 API 参考 获取更多信息。
Web Vitals 是一组有用的指标,旨在衡量网页的用户体验。以下 Web Vitals 指标均已包含:
你可以使用 name 属性来处理所有这些指标的结果。
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} />
}'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
}
// ...
}
})
}'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
}
// ...
}
})
}除了上述核心指标外,还有一些额外的自定义指标,用于衡量页面水合(hydrate)和渲染所需的时间:
Next.js-hydration: 页面开始并完成水合所需的时间长度(毫秒)Next.js-route-change-to-render: 路由更改后页面开始渲染所需的时间长度(毫秒)Next.js-render: 路由更改后页面完成渲染所需的时间长度(毫秒)你可以单独处理所有这些指标的结果:
export function reportWebVitals(metric) {
switch (metric.name) {
case 'Next.js-hydration':
// handle hydration results
break
case 'Next.js-route-change-to-render':
// handle route-change to render results
break
case 'Next.js-render':
// handle render results
break
default:
break
}
}这些指标适用于所有支持 User Timing API 的浏览器。
你可以将结果发送到任何端点,以衡量和跟踪你网站上的真实用户性能。例如:
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值可以让你手动构建指标分布(例如计算百分位数等)。
javascriptuseReportWebVitals((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 的信息。