如何将分析添加到您的 Next.js 应用程序
Next.js 内置了对测量和报告性能指标的支持。您可以选择使用 useReportWebVitals
钩子自行管理报告,或者,Vercel 提供了一个托管服务来自动收集和可视化指标。
客户端检测
对于更高级的分析和监控需求,Next.js 提供了一个 instrumentation-client.js|ts
文件,该文件在应用程序前端代码开始执行之前运行。这非常适合设置全局分析、错误跟踪或性能监控工具。
要使用它,请在应用程序的根目录中创建一个 instrumentation-client.js
或 instrumentation-client.ts
文件。
instrumentation-client.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)
})
构建您自己的
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 Vitals
Web Vitals 是一组有用的指标,旨在捕捉网页的用户体验。包括以下所有 Web Vitals:
您可以使用 name
属性处理所有这些指标的结果。
app/_components/web-vitals.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
}
// ...
}
})
}
将结果发送到外部系统
您可以将结果发送到任何端点,以衡量和跟踪您网站上的真实用户性能。例如:
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
值可以手动构建指标分布(以计算百分位数等)。
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的信息。
这有帮助吗?