跳至內容

instrumentation.js

instrumentation.js|ts 檔案用於將可觀察性工具整合到您的應用程式中,讓您可以追蹤效能和行為,並在生產環境中除錯問題。

要使用它,請將檔案放在應用程式的根目錄下,或者如果您使用了 src 資料夾,則放在其中。

匯出 (Exports)

register(選用)

該檔案匯出一個 register 函式,它會在新 Next.js 伺服器實例啟動時被呼叫**一次**。register 可以是一個非同步函式。

instrumentation.ts
import { registerOTel } from '@vercel/otel'
 
export function register() {
  registerOTel('next-app')
}

onRequestError(選用)

此 API 可在 Next.js canary 中使用。

您可以選擇性地匯出一個 onRequestError 函式,以便將**伺服器**錯誤追蹤到任何自訂的可觀察性提供程式。

  • 如果您在 onRequestError 中運行任何非同步任務,請確保它們已被等待。當 Next.js 伺服器擷取到錯誤時,將會觸發 onRequestError
  • error 實例可能不是拋出的原始錯誤實例,因為如果在伺服器組件渲染期間遇到錯誤,它可能會被 React 處理。如果發生這種情況,您可以使用錯誤上的 digest 屬性來識別實際的錯誤類型。
instrumentation.ts
import { type Instrumentation } from 'next'
 
export const onRequestError: Instrumentation.onRequestError = async (
  err,
  request,
  context
) => {
  await fetch('https://.../report-error', {
    method: 'POST',
    body: JSON.stringify({
      message: err.message,
      request,
      context,
    }),
    headers: {
      'Content-Type': 'application/json',
    },
  })
}

參數
類型
export function onRequestError(
  error: { digest: string } & Error,
  request: {
    path: string // resource path, e.g. /blog?name=foo
    method: string // request method. e.g. GET, POST, etc
    headers: { [key: string]: string }
  },
  context: {
    routerKind: 'Pages Router' | 'App Router' // the router type
    routePath: string // the route file path, e.g. /app/blog/[dynamic]
    routeType: 'render' | 'route' | 'action' | 'middleware' // the context in which the error occurred
    renderSource:
      | 'react-server-components'
      | 'react-server-components-payload'
      | 'server-rendering'
    revalidateReason: 'on-demand' | 'stale' | undefined // undefined is a normal request without revalidation
    renderType: 'dynamic' | 'dynamic-resume' // 'dynamic-resume' for PPR
  }
): void | Promise<void>

  • error:擷取到的錯誤本身(類型始終為 Error),以及一個 digest 屬性,它是錯誤的唯一 ID。
  • request:與錯誤相關聯的唯讀請求資訊。
  • context:發生錯誤的上下文。這可以是路由器的類型(應用程式或頁面路由器),和/或(伺服器組件 ('render')、路由處理程式 ('route')、伺服器動作 ('action') 或中介軟體 ('middleware'))。

指定執行環境
instrumentation.js
export function register() {
  if (process.env.NEXT_RUNTIME === 'edge') {
    return require('./register.edge')
  } else {
    return require('./register.node')
  }
}
 
export function onRequestError() {
  if (process.env.NEXT_RUNTIME === 'edge') {
    return require('./on-request-error.edge')
  } else {
    return require('./on-request-error.node')
  }
}

版本歷史記錄
版本變更
v15.0.0-RC引進 onRequestErrorinstrumentation 正式推出
v14.0.4Turbopack 支援 instrumentation
v13.2.0instrumentation 作為實驗性功能推出