Skip to content

instrumentation-client.js

instrumentation-client.js|ts 文件允许你添加监控、分析代码和其他在应用变为交互状态之前运行的副作用。这对于设置性能跟踪、错误监控、polyfill 或任何其他客户端可观察性工具非常有用。

¥The instrumentation-client.js|ts file allows you to add monitoring, analytics code, and other side-effects that run before your application becomes interactive. This is useful for setting up performance tracking, error monitoring, polyfills, or any other client-side observability tools.

要使用它,请将文件放在应用的根目录或 src 文件夹中。

¥To use it, place the file in the root of your application or inside a src folder.

用法

¥Usage

服务器端检测 不同,你无需导出任何特定函数。你可以直接在文件中编写监控代码:

¥Unlike server-side instrumentation, you do not need to export any specific functions. You can write your monitoring code directly in the file:

ts
// Set up performance monitoring
performance.mark('app-init')

// Initialize analytics
console.log('Analytics initialized')

// Set up error tracking
window.addEventListener('error', (event) => {
  // Send to your error tracking service
  reportError(event.error)
})

错误处理:在插桩代码周围实现 try-catch 块,以确保可靠的监控。这可防止单个跟踪故障影响其他检测功能。

¥Error handling: Implement try-catch blocks around your instrumentation code to ensure robust monitoring. This prevents individual tracking failures from affecting other instrumentation features.

路由导航跟踪

¥Router navigation tracking

你可以导出 onRouterTransitionStart 函数以在导航开始时接收通知:

¥You can export an onRouterTransitionStart function to receive notifications when navigation begins:

ts
performance.mark('app-init')

export function onRouterTransitionStart(
  url: string,
  navigationType: 'push' | 'replace' | 'traverse'
) {
  console.log(`Navigation started: ${navigationType} to ${url}`)
  performance.mark(`nav-start-${Date.now()}`)
}

onRouterTransitionStart 函数接收两个参数:

¥The onRouterTransitionStart function receives two parameters:

  • url: string - 导航到的 URL

    ¥url: string - The URL being navigated to

  • navigationType: 'push' | 'replace' | 'traverse' - 导航类型

    ¥navigationType: 'push' | 'replace' | 'traverse' - The type of navigation

性能考虑

¥Performance considerations

保持检测代码轻量。

¥Keep instrumentation code lightweight.

Next.js 会监控开发过程中的初始化时间,如果初始化时间超过 16 毫秒(这可能会影响页面的流畅加载),则会记录警告。

¥Next.js monitors initialization time in development and will log warnings if it takes longer than 16ms, which could impact smooth page loading.

执行时间

¥Execution timing

instrumentation-client.js 文件在应用生命周期的特定时间点执行:

¥The instrumentation-client.js file executes at a specific point in the application lifecycle:

  1. HTML 文档加载完成后

    ¥After the HTML document is loaded

  2. React Hydration 开始之前

    ¥Before React hydration begins

  3. 在用户交互之前

    ¥Before user interactions are possible

此时间安排非常适合设置需要捕获早期应用生命周期事件的错误跟踪、分析和性能监控。

¥This timing makes it ideal for setting up error tracking, analytics, and performance monitoring that needs to capture early application lifecycle events.

示例

¥Examples

错误跟踪

¥Error tracking

在 React 启动前初始化错误跟踪,并添加导航面包屑导航,以便更好地进行调试。

¥Initialize error tracking before React starts and add navigation breadcrumbs for better debugging context.

ts
import Monitor from './lib/monitoring'

Monitor.initialize()

export function onRouterTransitionStart(url: string) {
  Monitor.pushEvent({
    message: `Navigation to ${url}`,
    category: 'navigation',
  })
}

分析跟踪

¥Analytics tracking

初始化分析并使用详细的元数据跟踪导航事件,以便进行用户行为分析。

¥Initialize analytics and track navigation events with detailed metadata for user behavior analysis.

ts
import { analytics } from './lib/analytics'

analytics.init()

export function onRouterTransitionStart(url: string, navigationType: string) {
  analytics.track('page_navigation', {
    url,
    type: navigationType,
    timestamp: Date.now(),
  })
}

性能监控

¥Performance monitoring

使用 Performance Observer API 和性能标记跟踪交互时间和导航性能。

¥Track Time to Interactive and navigation performance using the Performance Observer API and performance marks.

ts
const startTime = performance.now()

const observer = new PerformanceObserver(
  (list: PerformanceObserverEntryList) => {
    for (const entry of list.getEntries()) {
      if (entry instanceof PerformanceNavigationTiming) {
        console.log('Time to Interactive:', entry.loadEventEnd - startTime)
      }
    }
  }
)

observer.observe({ entryTypes: ['navigation'] })

export function onRouterTransitionStart(url: string) {
  performance.mark(`nav-start-${url}`)
}

Polyfills

在应用代码运行前加载 polyfill。使用静态导入进行立即加载,使用动态导入进行基于特性检测的条件加载。

¥Load polyfills before application code runs. Use static imports for immediate loading and dynamic imports for conditional loading based on feature detection.

ts
import './lib/polyfills'

if (!window.ResizeObserver) {
  import('./lib/polyfills/resize-observer').then((mod) => {
    window.ResizeObserver = mod.default
  })
}

版本历史记录

¥Version history

版本更改
v15.3instrumentation-client 介绍