Skip to content

NEXT.JS

Next.js 15 instrumentation.ts: Server Lifecycle & Errors

Execute server startup logic once per process and capture unhandled server crashes with Next.js 15 instrumentation.ts, register(), and onRequestError.

Next.js 15 instrumentation.ts isolates server startup logic and global error observation from your request-handling pipeline. Code exported via register() runs once when the Node.js or Edge runtime boots, while onRequestError intercepts every unhandled server exception across Server Actions, Route Handlers, and Server Components with full context.

Placing database warmups, OpenTelemetry SDK initialization, or Sentry setups in root layouts causes them to run repeatedly during static prerendering and dynamic requests. Moving this logic to instrumentation.ts guarantees clean process bootstrapping without polluting client bundles.

Key takeaways

  • register() runs exactly once per server worker boot, never per HTTP request or client navigation.
  • onRequestError captures server exceptions with request path, method, headers, error digest, and router context (action, render, or route).
  • Guard Node-specific packages with process.env.NEXT_RUNTIME === "nodejs" to avoid Edge runtime compilation crashes.
  • Never throw or re-throw inside onRequestError; unhandled errors in your error handler mask the underlying response.
  • instrumentation.ts must reside in the project root directory or inside src/, never inside app/.

What instrumentation.ts actually runs

In earlier App Router versions, developers frequently put telemetry initialization in app/layout.tsx or a custom server.js. In Next.js 15, instrumentation.ts is the stable contract for server lifecycle events.

The file exports two reserved functions:

instrumentation.ts
export async function register() {
  // Executes once at process startup
}

export async function onRequestError(err: Error, request: { path: string; method: string }, context: { routerType: string }) {
  // Executes whenever a server request encounters an unhandled exception
}
Terminal
npm run check:instrumentation-contract
# check:instrumentation-contract — 6 guards
# ok   all 6 instrumentation contract assertions passed.

The runtime boots this file before mounting any routes. Unlike middleware, which executes on incoming requests at the network edge, register() runs during container initialization.

Phaseinstrumentation.ts (register)middleware.tsafter()
Execution triggerServer process bootEvery incoming HTTP requestResponse close lifecycle
FrequencyOnce per worker instancePer requestPer request (post-stream)
Runtime contextNode.js or Edge workerEdge or Node.js runtimeServer execution scope
Best use caseSDK setup, telemetry, pool warmupRouting, rewrites, auth headersNon-blocking analytics, audits

Server startup with register()

The register() function is asynchronous. Next.js awaits register() before opening the port to incoming traffic, ensuring external connections and tracing providers are active before the first request hits.

instrumentation.ts
export async function register() {
  if (process.env.NEXT_RUNTIME === "nodejs") {
    const { initTelemetry } = await import("./lib/telemetry");
    await initTelemetry();
    console.log("[server] OpenTelemetry SDK initialized");
  }
}

Dynamic imports inside register() are critical. If you write top-level static imports for Node.js modules like @opentelemetry/sdk-node, the bundler will attempt to evaluate them even when compiling the Edge bundle, resulting in missing module errors.

Handling runtime boundaries: Node.js vs Edge

Next.js projects frequently mix runtimes. A Route Handler might run on the Edge runtime for geographic proximity, while Server Actions run in Node.js for database compatibility.

Next.js executes instrumentation.ts across every runtime active in your application build. You must gate runtime-specific code using process.env.NEXT_RUNTIME:

instrumentation.ts
export async function register() {
  if (process.env.NEXT_RUNTIME === "nodejs") {
    // Database connection pools, native tracing SDKs
    const { pool } = await import("./lib/db");
    await pool.query("SELECT 1");
  }

  if (process.env.NEXT_RUNTIME === "edge") {
    // Edge-compatible logging or lightweight telemetry
    console.log("[edge] Edge runtime worker started");
  }
}

Without this check, importing packages that rely on native C++ bindings or node: modules breaks Edge compilation during next build.

Global error observability with onRequestError

Next.js 15 introduced onRequestError in instrumentation.ts. Previously, logging unhandled server exceptions required intercepting errors manually in every Route Handler or relying on client error boundaries, which redact server details.

onRequestError receives three arguments: the raw error object, the request descriptor, and the routing execution context.

instrumentation.ts
import type { Instrumentation } from "next";

export const onRequestError: Instrumentation.onRequestError = async (
  err,
  request,
  context
) => {
  const errorPayload = {
    message: err instanceof Error ? err.message : String(err),
    digest: (err as { digest?: string }).digest ?? "NO_DIGEST",
    path: request.path,
    method: request.method,
    headers: request.headers,
    routerType: context.routerType, // "action" | "render" | "route"
    renderType: context.renderType, // "dynamic" | "dynamic-resume"
  };

  // Dispatch to external logging or telemetry provider
  await fetch("https://telemetry.internal/errors", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(errorPayload),
  }).catch(() => {
    // Silently fall back to stdout if monitoring service is unreachable
    console.error("[error-logger-fail]", errorPayload);
  });
};

The context.routerType property tells you where the failure occurred:

  • action: A Server Action mutated state or rejected an unhandled promise.
  • render: A Server Component threw an exception while evaluating JSX.
  • route: A Route Handler (app/api/.../route.ts) returned an unhandled rejection.

Notice that the error's digest matches the hash shown to the end user in production, allowing you to correlate customer bug reports with internal stack traces instantly.

Connecting OpenTelemetry and tracer SDKs

Standard OpenTelemetry instrumentation hooks into Node.js HTTP and framework modules before they are imported by application code. Placing OTel setup inside register() fulfills this requirement:

lib/telemetry.ts
import { NodeSDK } from "@opentelemetry/sdk-node";
import { getNodeAutoInstrumentations } from "@opentelemetry/auto-instrumentations-node";

let sdk: NodeSDK | null = null;

export async function initTelemetry() {
  if (sdk) return;

  sdk = new NodeSDK({
    serviceName: "devventa-web",
    instrumentations: [getNodeAutoInstrumentations()],
  });

  sdk.start();

  process.on("SIGTERM", async () => {
    await sdk?.shutdown();
    process.exit(0);
  });
}

Combine this with Next.js experimental telemetry options in next.config.ts:

next.config.ts
import type { NextConfig } from "next";

const nextConfig: NextConfig = {
  experimental: {
    // Instrumentation hook is enabled by default in Next.js 15
  },
};

export default nextConfig;

When deployed to production or run locally, every HTTP request, Server Action, and internal fetch call automatically carries trace headers and spans.

What did not work: build-time evaluation traps

During our initial instrumentation deployment, we placed top-level database pool initialization directly at the module root of instrumentation.ts instead of within register():

instrumentation.ts
// BROKEN: Evaluates during next build prerendering
import { pool } from "./lib/db";
pool.connect(); // Fails during static page generation in CI

export async function register() {
  // ...
}

During CI compilation (npm run build), Next.js imports instrumentation.ts in an environment where live database credentials and production networks are inaccessible. The build failed with ECONNREFUSED on static route generation.

The fix was moving all initialization inside register() and wrapping it with dynamic import() statements. Next.js only executes register() at actual runtime startup or when generating on-demand dynamic requests, preventing build-time network lockouts.

Best practices for Next.js instrumentation

  • Dynamic imports inside register. Use await import(...) inside register() to ensure packages are only loaded for their intended runtime environment.
  • Always check NEXT_RUNTIME. Verify process.env.NEXT_RUNTIME === "nodejs" before importing any package that touches Node.js filesystem, network sockets, or binary modules.
  • Trap telemetry transport errors. Never allow network failures inside onRequestError to bubble up. Wrap external error logging calls in .catch() blocks.
  • Preserve error digests. Log err.digest alongside stack traces to enable exact lookup against production client error pages.
  • Graceful shutdown. Register SIGTERM and SIGINT handlers inside register() to flush pending traces before container termination.

Common mistakes

  • Static imports for Node packages. Writing import { NodeSDK } from "@opentelemetry/sdk-node" at the top level of instrumentation.ts, crashing Edge routes during compilation.
  • Placing instrumentation.ts inside app/. Next.js ignores app/instrumentation.ts. It must reside at the root level or inside src/.
  • Throwing inside onRequestError. Re-throwing an exception inside onRequestError disrupts the Next.js internal error responder, causing opaque connection resets.
  • Expecting register() to run per request. Using register() for per-request authentication or tenant switching instead of middleware.ts.
  • Omitting timeout safeguards. Awaiting an unresponsive external database in register() indefinitely, preventing the web process from ever passing readiness probes.

Decision guide: where code belongs

Use instrumentation.ts when you need code to run once when the server container starts, or when you need global error observation across every server route.

If your code needs to inspect or modify incoming HTTP headers, use middleware.ts. If your task needs to execute non-blocking cleanup after an HTTP response has already completed, use after(). If you are building transactional backend APIs, keep logic inside typed route.ts files.

Frequently asked questions

When does register() in instrumentation.ts execute?
The register() function runs once when a new Next.js server instance starts up, before any HTTP requests or dynamic pages are served. It does not re-run per request, making it the correct place to initialize telemetry SDKs, warm database connection pools, or register process-level hooks.
What is the difference between onRequestError and error.tsx?
React error boundaries like error.tsx only handle component rendering errors within the React tree and render a client fallback UI. onRequestError is a server-side hook that catches all unhandled exceptions across Server Components, Server Actions, and Route Handlers, logging full request metadata and error digests to monitoring systems.
Can instrumentation.ts run on Edge runtimes?
Yes. instrumentation.ts is executed for both Node.js and Edge runtimes. Because Node-specific modules like OpenTelemetry SDKs or node:crypto throw errors in Edge runtimes, you must conditionally branch initialization code using process.env.NEXT_RUNTIME === 'nodejs'.
Does onRequestError catch errors in production client components?
No. onRequestError is strictly a server runtime hook. Browser-only errors, hydration mismatches, and client event handler exceptions must be caught by client-side error boundaries or browser monitoring scripts.

Muhammad Kashif

Founder and editor of Devventa, covering AI coding assistants, Next.js and the modern AI development stack.