如何設定分析工具

Next.js 內建支援測量與報告效能指標。你可以使用 useReportWebVitals 鉤子自行管理報告,或者 Vercel 提供 託管服務 自動為你收集並視覺化這些指標。

用戶端檢測工具

針對更進階的分析與監控需求,Next.js 提供 instrumentation-client.js|ts 檔案,該檔案會在應用程式的前端程式碼開始執行前運行。這非常適合用來設定全域分析、錯誤追蹤或效能監控工具。

要使用它,請在應用程式的根目錄中建立 instrumentation-client.jsinstrumentation-client.ts 檔案:

instrumentation-client.js
// 在應用程式啟動前初始化分析功能
console.log('分析功能已初始化')

// 設定全域錯誤追蹤
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 參考文件 以獲得更多資訊。

網頁核心指標 (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} />
}

自訂指標

除了上述核心指標外,還有一些額外的自訂指標用來測量頁面水合 (hydrate) 和渲染所需的時間:

  • Next.js-hydration: 頁面開始到完成水合所需的時間 (以毫秒為單位)
  • Next.js-route-change-to-render: 路由變更後頁面開始渲染所需的時間 (以毫秒為單位)
  • Next.js-render: 路由變更後頁面完成渲染所需的時間 (以毫秒為單位)

你可以分別處理這些指標的結果:

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

這些指標在所有支援 使用者時序 API 的瀏覽器中均可使用。

將結果發送至外部系統

你可以將結果發送到任何端點,以測量與追蹤網站上的真實使用者效能。例如:

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 的資訊。

On this page