03 / 06

How to Implement instrumentation.js in a next.js project

The instrumentation.js file in Next.js is a special file used to integrate monitoring, logging, and observability tools into your application. It runs server-side code when your Next.js server instance initializes, making it ideal for setting up OpenTelemetry, error tracking, or any initialization logic that should execute once at startup. Starting with Next.js 15, this feature is stable and includes additional error tracking capabilities through the onRequestError function.

Basic instrumentation.js Setup
Key Implementation Steps
  1. 1

    Create the instrumentation file: Place instrumentation.js|ts in your project's root directory (or inside src folder if using one) - not inside app or pages directories

  2. 2

    Export a register function: This function is called once when the Next.js server instance is initiated and can be async

  3. 3

    For Next.js 14 or earlier: Enable experimental flag in next.config.js with experimental.instrumentationHook = true

  4. 4

    Use environment-specific code: Check process.env.NEXT_RUNTIME to conditionally import code for Node.js vs Edge runtime

  5. 5

    Import side-effect modules: Use await import() inside the register function for packages with side effects rather than importing at the top of the file

For production use, a common implementation pattern is integrating OpenTelemetry for observability. The @vercel/otel package provides a streamlined way to add OpenTelemetry instrumentation to your Next.js application. You can also create custom instrumentation for browser-side monitoring by conditionally initializing telemetry in your app component when running on the client side.

OpenTelemetry Integration Example
Error Tracking with onRequestError (Next.js 15+)