Capítulo 371 de 456

instrumentation.js

Core Idea

instrumentation.js|ts at the project (or src) root integrates observability tooling: run setup code once at server start, and capture server errors centrally.

Key Concepts

  • register() (optional): async function called once when a new Next.js server instance starts, must complete before requests are handled.
  • onRequestError() (optional): tracks server errors to a custom observability provider; receives (error, request, context).
  • process.env.NEXT_RUNTIME: use to branch logic between 'edge' and Node.js runtimes, since the file runs in both.

Code Examples

import { registerOTel } from '@vercel/otel'

export function register() {
  registerOTel('next-app')
}
  • O que demonstra: registering OpenTelemetry at server startup.
export function onRequestError(
  error: unknown,
  request: {
    path: string
    method: string
    headers: { [key: string]: string | string[] }
  },
  context: {
    routerKind: 'Pages Router' | 'App Router'
    routePath: string
    routeType: 'render' | 'route' | 'action' | 'proxy'
    renderSource: 'react-server-components' | 'react-server-components-payload' | 'server-rendering'
    revalidateReason: 'on-demand' | 'stale' | undefined
    renderType: 'dynamic' | 'dynamic-resume'
  }
): void | Promise<void>
  • O que demonstra: full type shape of onRequestError's parameters.

Reference Tables

None beyond the type signature above.

Anti-patterns

  • Not awaiting async work inside onRequestError: unawaited tasks may be dropped since Next.js doesn't wait for them.
  • Assuming error is always an Error instance: it's typed unknown and may be processed by React; check digest for the real error type.

Key Takeaways

  1. Place the file at the project root or inside src/ alongside pages/app.
  2. register must fully complete before the server accepts requests.
  3. Use NEXT_RUNTIME to load runtime-specific implementations (edge vs Node).
  4. Stable since v15.0.0; Turbopack support added in v14.0.4; introduced experimentally in v13.2.0.

Connects To

  • Proxy: context.routeType can be 'proxy', tying error tracking to proxy-originated errors.
  • Script: another file-based hook, but for client-side third-party code instead of server observability.