跳到內容

如何設定分析

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

自行構建

pages/_app.js
import { useReportWebVitals } from 'next/web-vitals'
 
function MyApp({ Component, pageProps }) {
  useReportWebVitals((metric) => {
    console.log(metric)
  })
 
  return <Component {...pageProps} />
}

更多資訊請查閱 API 參考

Web Vitals

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': {
        // handle FCP results
      }
      case 'LCP': {
        // handle LCP results
      }
      // ...
    }
  })
 
  return <Component {...pageProps} />
}

自定義指標

除了上面列出的核心指標,還有一些額外的自定義指標,用於衡量頁面水合和渲染所需的時間。

  • 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 值可以手動構建指標分佈(以計算百分位數等)。

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