跳到內容

分析

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

自行建置

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 Hook 需要 "use client" 指示詞,效能最佳的方法是建立一個獨立的元件,讓根版面配置匯入。這將用戶端邊界完全限制在 WebVitals 元件中。

請查看 API 參考 以取得更多資訊。

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