Course map
Stage 1: App Router Foundations
Stage 2: The Rendering Model
Stage 3: Data, Caching and Mutations
Stage 4: Full-Stack Next.js
Stage 5: Production and Specialization

Part 18 / Topic 6 of 8

instrumentation.ts: register() and onRequestError(), fired for real

The installed instrumentation.md/instrumentation.js (file-conventions) guides name two hooks: register() (once per server instance, before it accepts requests) and onRequestError() (whenever Next's own server catches a server-side error — a Server Component render, Route Handler, Server Action, or Proxy). Both are added to this harness's new instrumentation.ts/instrumentation-node.ts (examples 02/03), logging to the console rather than an external provider (no account, no API key — the same "works fully offline" rule every dependency choice in this course has followed). register() firing is visible in every transcript above ([instrumentation] server instance starting...); onRequestError() needed a deliberately-thrown error to observe, via a scratch Route Handler (examples/04-on-request-error-probe.ts, created, hit once, then deleted — never part of this harness's committed routes):

$ npm run dev -- -p 3102
...
[instrumentation] server instance starting - pid 64269, NEXT_RUNTIME=nodejs
$ curl -s -o /dev/null -w "scratch-boom: %{http_code}\n" http://localhost:3102/api/ops/scratch-boom
scratch-boom: 500
⨯ Error: Deliberate scratch error for Part 18's instrumentation check
    at GET (app/api/ops/scratch-boom/route.ts:2:9)
[onRequestError] App Router route (undefined) GET /api/ops/scratch-boom -> Deliberate scratch error for Part 18's instrumentation check

context.routerKind ("App Router"), context.routeType ("route"), and request.path/request.method all came through exactly as the installed docs' own type signature promises — real structured error context, not a generic stack-trace dump. The very first version of instrumentation.ts used process.pid unconditionally and hit a real Turbopack build warning: "A Node.js API is used (process.pid...) which is not supported in the Edge Runtime." register() runs in both the Node.js and Edge runtimes (proxy.ts is Edge, per Part 14), and a plain if (process.env.NEXT_RUNTIME === "nodejs") guard around the process.pid usage did not silence the warning — Turbopack's Edge-compatibility check flags the reference statically, not by tracing which runtime branch actually executes. The installed docs' own "Importing runtime-specific code" pattern — splitting the Node-only code into its own file and loading it with a dynamic import() (examples/03-instrumentation-node.ts) — was the fix that actually removed the warning, confirmed by rebuilding and re-running with no warning present in the output.

Done here? The practice set for Part 18 — including the solutions — is on the part page.

Search the guide