跳到內容

分析

Next.js 內建支援測量和報告效能指標。您可以自行使用 useReportWebVitals Hook 來管理報告,或者,Vercel 提供託管服務,自動為您收集和視覺化指標。

自行建置

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