如何為你的 Next.js 應用程式添加分析功能
Next.js 內建支援測量與報告效能指標。你可以使用 useReportWebVitals
鉤子自行管理報告,或者 Vercel 提供 託管服務 自動為你收集並視覺化這些指標。
用戶端檢測工具
針對更進階的分析與監控需求,Next.js 提供 instrumentation-client.js|ts
檔案,該檔案會在應用程式的前端程式碼開始執行前運行。這非常適合用來設定全域分析、錯誤追蹤或效能監控工具。
要使用它,請在應用程式的根目錄中建立 instrumentation-client.js
或 instrumentation-client.ts
檔案:
// 在應用程式啟動前初始化分析功能
console.log('分析功能已初始化')
// 設定全域錯誤追蹤
window.addEventListener('error', (event) => {
// 發送至你的錯誤追蹤服務
reportError(event.error)
})
自行建置
'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>
)
}
由於
useReportWebVitals
鉤子需要'use client'
指令,最高效的做法是建立一個獨立元件,由根佈局導入。這樣可以將客戶端邊界限制在WebVitals
元件內。
查看 API 參考文件 以獲得更多資訊。
網頁核心指標 (Web Vitals)
網頁核心指標 是一組實用的指標,旨在捕捉網頁的使用者體驗。以下指標全部包含在內:
你可以使用 name
屬性來處理這些指標的所有結果。
'use client'
import { useReportWebVitals } from 'next/web-vitals'
export function WebVitals() {
useReportWebVitals((metric) => {
switch (metric.name) {
case 'FCP': {
// 處理 FCP 結果
}
case 'LCP': {
// 處理 LCP 結果
}
// ...
}
})
}
'use client'
import { useReportWebVitals } from 'next/web-vitals'
export function WebVitals() {
useReportWebVitals((metric) => {
switch (metric.name) {
case 'FCP': {
// 處理 FCP 結果
}
case 'LCP': {
// 處理 LCP 結果
}
// ...
}
})
}
將結果發送至外部系統
你可以將結果發送到任何端點,以測量與追蹤網站上的真實使用者效能。例如:
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
值可以手動構建指標分佈 (例如計算百分位數等)
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, // 當前頁面載入的唯一識別碼 non_interaction: true, // 避免影響跳出率 }) })
閱讀更多關於 將結果發送至 Google Analytics 的資訊。