AI & Agent Dev Bug Sandbox logo
AI & Agent Dev Bug Sandbox
Back to Radar

OpenTelemetry HttpInstrumentation In Instrumentation.Ts Never Instruments Incoming Requests Due To Late Require Hook

Next.js loads the http and https core modules before instrumentation.ts register() runs, so require-in-the-middle never sees a subsequent require to patch. This silently disables @opentelemetry/instrumentation-http, causing missing incoming HTTP spans even though the OpenTelemetry SDK starts successfully.

highConfidence 95%Next.jsAffected V15.5.20Affected V16.2.10

Origin Analysis

In standalone mode, next/dist/server/lib/start-server imports http/https at module top before register() is invoked. HttpInstrumentation relies on require-in-the-middle patching Module.prototype.require, which only applies to the next require call. Since Next.js has already loaded http and no later require passes through the hook, the instrumentation never attaches.
1. Clone the repro repo https://github.com/r34son/next-otel-http-instrumentation-repro. 2. Run npm install && npm run build && npm run start. 3. Execute curl -sI http://localhost:3000/ | grep -i x-otel-trace-id. 4. Observe no x-otel-trace-id header because the HTTP instrumentation was never applied.

Fixing Code Block

Edge Case Audit

This fix requires Node.js >= 20.16 and require-in-the-middle >= 7.4. On older versions the calls silently do nothing and HTTP instrumentation remains broken. The fix is specific to the Node.js runtime; guard with NEXT_RUNTIME to avoid execution in edge runtimes. If Next.js later adds its own module pass after register(), this workaround may cause double patching or conflicts; remove these lines when upgrading to a version that addresses the issue. Rollback: simply delete the two process.getBuiltinModule calls and restart.

Ecosystem Topology