Frameworks 11 min read

OpenTelemetry for Express: tracing a Node.js app

A working setup for Express 4 and 5, then the parts the quickstarts skip: load order, ES modules, middleware span noise, route names, trace IDs in logs and flushing on shutdown. Tested with Express 4.22 and 5.3 and OpenTelemetry JS SDK 0.301 (November 2026).

David Granzin By David Granzin

Install and minimal setup

Tracing an Express app with OpenTelemetry takes two packages and one file that Node loads before your app. The same setup gives you distributed tracing once the services it calls are instrumented too.

npm install @opentelemetry/api \
  @opentelemetry/sdk-node \
  @opentelemetry/auto-instrumentations-node
  • @opentelemetry/sdk-node is the SDK: tracer, exporters and context tracking.
  • @opentelemetry/auto-instrumentations-node bundles instrumentations for Express, http, pg, Redis clients, fetch, Pino, Winston and about 30 other libraries.
  • @opentelemetry/api is what your own code imports to create spans.

The SDK goes in a file of its own:

// instrumentation.mjs
import { register } from "node:module";
import { NodeSDK } from "@opentelemetry/sdk-node";
import { getNodeAutoInstrumentations } from "@opentelemetry/auto-instrumentations-node";

// Lets instrumentations patch packages loaded with import.
register("@opentelemetry/instrumentation/hook.mjs", import.meta.url);

const sdk = new NodeSDK({
  instrumentations: [getNodeAutoInstrumentations()],
});
sdk.start();

The app needs no changes:

// app.mjs
import express from "express";

const app = express();
app.use(express.json());

const orders = express.Router();
orders.get("/:id", (req, res) => {
  res.json({ id: req.params.id, status: "paid" });
});
app.use("/orders", orders);

app.listen(3000, () => console.log("listening on :3000"));

Run it with the console exporter, so you see spans without a backend:

OTEL_SERVICE_NAME=checkout \
OTEL_TRACES_EXPORTER=console \
OTEL_METRICS_EXPORTER=none \
OTEL_LOGS_EXPORTER=none \
node --import ./instrumentation.mjs app.mjs

Request http://localhost:3000/orders/42 and the process prints one object per span. This is the server span, with the resource block removed:

{
  instrumentationScope: { name: '@opentelemetry/instrumentation-http', version: '0.301.2' },
  traceId: '4871f3a2309c625fe9e10522dce0a00b',
  parentSpanContext: undefined,
  name: 'GET /orders/:id',
  id: 'ce41e47c576883eb',
  kind: 1,
  duration: 2993.834,
  attributes: {
    'http.request.method': 'GET',
    'url.scheme': 'http',
    'server.address': 'localhost',
    'url.path': '/orders/42',
    'server.port': 3000,
    'http.response.status_code': 200,
    'http.route': '/orders/:id'
  },
  status: { code: 0 }
}

kind: 1 is a server span and parentSpanContext: undefined makes it the trace root. The name and http.route hold the route pattern, not the URL, so every order groups under one operation.

Node.js version

As of November 2026 the current line (sdk-node 0.300+, auto-instrumentations-node 0.82+) needs Node.js 22.15 or newer. On Node.js 18.19+ or 20.6+, pin @opentelemetry/sdk-node@0.223 with @opentelemetry/auto-instrumentations-node@0.81, the last line that supports them.

Load it before Express

Instrumentation wraps a module's functions at the moment the module loads. If express or http is already loaded when the SDK starts, there is nothing left to wrap.

The same Express 5 app started three ways. Only the first records the route.

The bottom row fails silently. An import at the top of app.mjs is not safe either: imports are hoisted, and a formatter or bundler may reorder them.

--import and --require run the file before the entry point is read. If you cannot change the start command, set NODE_OPTIONS="--import ./instrumentation.mjs".

ES modules and the loader hook

Node has two module loaders. Packages loaded with require() are patched through a require hook that needs no setup. Packages loaded with import need a loader hook, which is the register() line in the file above.

Leaving it out half works, which makes it hard to spot. http and everything Express loads with require() are patched, but the express your code imported is not. That is the middle row of the figure.

The flag --experimental-loader=@opentelemetry/instrumentation/hook.mjs does the same job, and Node 24 prints an ExperimentalWarning that recommends register().

CommonJS and zero-code

A CommonJS app uses the same SDK without the hook, loaded with --require:

// instrumentation.cjs
const { NodeSDK } = require("@opentelemetry/sdk-node");
const { getNodeAutoInstrumentations } = require("@opentelemetry/auto-instrumentations-node");

const sdk = new NodeSDK({
  instrumentations: [getNodeAutoInstrumentations()],
});
sdk.start();

// Run with: node --require ./instrumentation.cjs app.cjs

If the defaults are enough, skip the file. The bundle's register entry starts the SDK from environment variables:

# CommonJS: no instrumentation file at all
node --require @opentelemetry/auto-instrumentations-node/register app.js

# ES modules: the register entry does not install the loader hook, so add it
node --experimental-loader=@opentelemetry/instrumentation/hook.mjs \
  --import @opentelemetry/auto-instrumentations-node/register app.mjs

It takes no instrumentation options, so the noise settings below need the file. OTEL_NODE_DISABLED_INSTRUMENTATIONS still turns whole instrumentations off.

Express 4 vs Express 5

Both major versions work with the setup above (@opentelemetry/instrumentation-express supports express >=4.0.0 <6), but they do not produce the same trace.

Express 4Express 5
Spans for the sample request68
Built-in middleware spansquery and expressInit on every requestNone
Which instrumentations emitexpressexpress and router
Rejected promise in an async handlerNever reaches Express: call next(err) yourselfGoes to the error middleware, and the handler span is marked as an error
Server span name and http.routeGET /orders/:idGET /orders/:id

The sample request on Express 4.22:

GET /orders/:id                      http     SERVER
  middleware - query                 express
  middleware - expressInit           express
  middleware - jsonParser            express
  router - /:id                      express
  request handler - /orders/:id      express

Express 5 moved routing into the standalone router package, which has its own instrumentation in the bundle. Both fire, so each layer is reported twice. The router's copy is named middleware - patched, after the wrapper function it sees. The next figure shows all 8 spans.

Middleware span noise

A span per middleware sounds useful and rarely is, and two options remove them without losing the route name.

One request, as each instrumentation scope reported it. The right column names the scope that emitted the span.

Middleware spans measure less than they seem to:

  • A middleware span ends when the middleware calls next(), or when the response closes if it never does.
  • Work awaited before next() is counted. A middleware that waited 50 ms and then called next() got a 50.3 ms span in a test.
  • Work started after next() is not counted.
  • Router spans end as soon as they start. The request handler span runs until the response closes.

The Express instrumentation groups layers into three types: middleware, router and request_handler. ignoreLayersType turns types off. Options are passed per instrumentation, keyed by package name:

instrumentation.mjs

const off = { enabled: false };

const sdk = new NodeSDK({
  instrumentations: [
    getNodeAutoInstrumentations({
      // Keep the request handler span, drop middleware and router spans.
      "@opentelemetry/instrumentation-express": {
        ignoreLayersType: ["middleware", "router"],
      },
      // Express 5 routes through the router package, which adds its own spans.
      "@opentelemetry/instrumentation-router": off,
      // Socket and DNS spans under every outgoing call.
      "@opentelemetry/instrumentation-net": off,
      "@opentelemetry/instrumentation-dns": off,
      // No traces for health checks.
      "@opentelemetry/instrumentation-http": {
        ignoreIncomingRequestHook: (req) => req.url === "/healthz",
      },
    }),
  ],
});
  • Even fewer spans. Add "request_handler" to the list and only the server span is left, still named GET /orders/:id.
  • Keep the Express instrumentation on. It gives the server span its route. With OTEL_NODE_DISABLED_INSTRUMENTATIONS=express,router the request produced a span named GET with no http.route.
  • Drop one layer. ignoreLayers takes strings, regular expressions or functions matched against the layer's path.
  • Drop whole requests. ignoreIncomingRequestHook on the HTTP instrumentation skips health checks and static files. An ignored request starts no trace at all.

Route names and http.route

The server span's name decides how a backend groups your requests. The HTTP instrumentation creates the span before any route has matched and names it after the method. The Express instrumentation records the route as layers match, so the finished span is named GET /orders/:id and carries http.route.

  • Mounted routers are joined. A router mounted at /orders with a route /:id reports /orders/:id.
  • Unmatched requests have no route. A 404 is named GET with no http.route, so bot probes do not create one operation each. Routes missing on matched requests point at the loader hook.
  • The raw path is still there. url.path holds /orders/42. Filter on it, but group and alert on http.route.
  • 4xx is not an error. A server span is marked as an error for 5xx responses only.

Postgres, Redis and fetch spans

Outgoing calls get client spans with no code from you. The bundle patches pg, ioredis, redis, mysql2, mongodb, http, and fetch (through @opentelemetry/instrumentation-undici). Take a handler that reads a cache, then a database, then calls another service:

app.get("/orders/:id", async (req, res) => {
  const cached = await redis.get("order:" + req.params.id);
  if (cached) return res.json(JSON.parse(cached));

  const { rows } = await pool.query("SELECT id, status FROM orders WHERE id = $1", [req.params.id]);
  if (rows.length === 0) return res.status(404).json({ error: "not found" });

  const rate = await fetch("http://localhost:3001/rates/EUR").then((r) => r.json());
  logger.info({ orderId: rows[0].id }, "order loaded");
  res.json({ ...rows[0], rate });
});

With the quiet config, one request gives this trace:

Real durations from a local run, in milliseconds. Start offsets are rounded to the millisecond.
  • Queries keep their placeholders. db.query.text is SELECT id, status FROM orders WHERE id = $1, so parameter values stay out of traces. Redis differs: the command text includes the key (get order:42), so keep secrets out of key names.
  • The first query pays for the connection. pg-pool.connect took 17.7 ms because the pool was empty. On a warm pool it is close to zero. Slow on a busy service, it means requests wait for a free connection: a pool size problem, not a query problem.
  • fetch carries the trace on. The outgoing request had a traceparent header, so an instrumented rates service continues the same trace. Context propagation covers queues and other transports.
  • Client spans are named after the method. The fetch span is GET. The target is in url.full and server.address.

Without the two off lines in the config, the trace also had a tcp.connect span under each new connection and a dns.lookup span under the fetch call. Turn them on when you suspect DNS or connection setup.

Custom spans and recording errors

Auto-instrumentation shows time spent between your process and the network, not inside your own functions. Wrap the work that matters with tracer.startActiveSpan:

import { trace, SpanStatusCode } from "@opentelemetry/api";

const tracer = trace.getTracer("checkout");

function priceOrder(order) {
  return tracer.startActiveSpan("price order", async (span) => {
    try {
      span.setAttribute("order.items", order.items.length);
      if (order.items.length === 0) throw new Error("order has no items");
      return order.items.length * 10;
    } catch (err) {
      span.recordException(err);
      span.setStatus({ code: SpanStatusCode.ERROR, message: err.message });
      throw err;
    } finally {
      span.end();
    }
  });
}

app.post("/orders", async (req, res) => {
  const total = await priceOrder(req.body);
  // Attributes on the span that is already active, without a new span.
  trace.getActiveSpan()?.setAttribute("order.total", total);
  res.status(201).json({ total });
});

The new span is current for everything the callback does, including code after an await, so database spans started inside become its children.

  • Always end the span. A span that is never ended is never exported. finally covers both paths.
  • recordException does not set the status. It adds an exception event with the type, message and stack trace. The span counts as failed only after setStatus with SpanStatusCode.ERROR.
  • Prefer attributes for small facts. trace.getActiveSpan()?.setAttribute() puts order.total on the span that already exists.

For errors that escape a handler, record them once in the error middleware:

// Registered after every route.
app.use((err, req, res, next) => {
  const span = trace.getActiveSpan();
  span?.recordException(err);
  span?.setStatus({ code: SpanStatusCode.ERROR, message: err.message });
  logger.error({ err }, "request failed");
  res.status(500).json({ error: "internal error" });
});

On Express 5 the instrumentation already records a thrown or rejected error on the request handler span. The middleware adds it to the span that is active when it runs: the server span when middleware spans are ignored, the error middleware's own span when they are on.

Logs with trace_id

The bundle's Pino, Winston and Bunyan instrumentations add the active span's IDs to each record, with no change to your logging calls. The logger.info in the handler above printed:

{"level":30,"time":1795912095881,"pid":75318,"hostname":"web-1","trace_id":"23b362eb558110c9a5e0d3a7842cb8e8","span_id":"e15a57817287c22f","trace_flags":"01","orderId":42,"msg":"order loaded"}

The same call through Winston's console transport:

{"level":"info","message":"order loaded","orderId":"42","span_id":"e5b3e8e8ed5f9614","trace_flags":"01","trace_id":"de4ace66927189a847475816e7c5f265"}
  • trace_id matches the request's trace, so a backend can open the trace from a log line.
  • A record written outside any span, such as a startup message, has no IDs.
  • Each record is also forwarded to the OpenTelemetry Logs SDK, and NodeSDK exports those over OTLP by default. If you already collect stdout, set OTEL_LOGS_EXPORTER=none so lines are not stored twice.
  • console.log is not instrumented: no IDs, no export.

For log levels, redaction and request logging with pino-http, see the Pino logger guide.

Production config

Production setup is environment variables only, so one image runs everywhere. Without OTEL_TRACES_EXPORTER=console the SDK sends traces, metrics and logs as OTLP over HTTP (http/protobuf) to http://localhost:4318.

export OTEL_SERVICE_NAME="checkout"
export OTEL_RESOURCE_ATTRIBUTES="deployment.environment.name=production,service.version=1.4.2"

# Where the data goes. The SDK appends /v1/traces, /v1/metrics and /v1/logs.
export OTEL_EXPORTER_OTLP_ENDPOINT="http://otel-collector:4318"
export OTEL_EXPORTER_OTLP_COMPRESSION="gzip"

# Keep 10% of new traces, and follow the caller's decision when there is one.
export OTEL_TRACES_SAMPLER="parentbased_traceidratio"
export OTEL_TRACES_SAMPLER_ARG="0.1"

# Resource detectors to run. Leaving out "process" keeps command-line
# arguments out of your telemetry.
export OTEL_NODE_RESOURCE_DETECTORS="env,host,os,serviceinstance"
SettingDefaultWhat to do
service.nameunknown_service:nodeAlways set it. Add deployment.environment.name and service.version to split environments and compare releases.
Endpointhttp://localhost:4318A base URL for a Collector or a backend. The OTLP guide covers ports, headers and status codes.
SamplingEvery trace is keptparentbased_traceidratio keeps a fraction and follows the caller's decision, so traces stay whole. To keep all errors and slow requests, sample in a Collector.
BatchingExport every 5 s or 512 spans, queue of 2048Tune with OTEL_BSP_SCHEDULE_DELAY, OTEL_BSP_MAX_EXPORT_BATCH_SIZE and OTEL_BSP_MAX_QUEUE_SIZE. Spans beyond the queue are dropped while an export is stuck.
Resource detectorsenv, host, os, process, serviceinstancePick with OTEL_NODE_RESOURCE_DETECTORS. process records the full command line, so a secret passed as an argument lands on every span.

The cloud detectors (aws, gcp, azure, alibaba, container) are opt-in with NodeSDK. The zero-code register entry runs all of them unless you set the variable.

Flush spans on shutdown

Batching keeps the newest spans in memory. An orchestrator stops a container with SIGTERM, Node's default is to exit at once, and NodeSDK installs no signal handler. In a test, an app stopped half a second after a request delivered nothing without a handler and its trace with one.

Use one handler for the whole process. A second one in the instrumentation file that calls process.exit() would race the server's shutdown and cut off open requests. Export the SDK from the instrumentation file:

// instrumentation.mjs: export the SDK so the app can shut it down
export const sdk = new NodeSDK({
  instrumentations: [getNodeAutoInstrumentations()],
});
sdk.start();

Then close the server first and the SDK last, so the final requests' spans are included:

// app.mjs
import { sdk } from "./instrumentation.mjs";

const server = app.listen(3000, () => console.log("listening on :3000"));

process.on("SIGTERM", () => {
  // Exit anyway if draining or the export hangs.
  setTimeout(() => process.exit(1), 10_000).unref();
  // Stop accepting requests, let open ones finish, then flush telemetry.
  server.close(async () => {
    await sdk.shutdown().catch((err) => console.error("OpenTelemetry shutdown failed", err));
    process.exit(0);
  });
});
  • No second SDK. Node already loaded ./instrumentation.mjs for --import and hands the app the same instance.
  • One call flushes everything. sdk.shutdown() flushes traces, metrics and logs and closes the exporters.
  • The timer is the escape hatch. A deploy should not hang on an unreachable backend or a connection that never drains.
  • Zero-code still needs a handler. The register entry calls sdk.shutdown() on SIGTERM but does not exit. In a test the trace was delivered and the process kept running until it was killed.

Common problems

Most failures are silent, so match the symptom first.

SymptomCauseFix
No spans at all, no errorThe SDK started after express and http were loadedLoad the file with --import or --require
Server spans named GET, no Express spans, ES module appNo loader hook, so the imported express was not patchedAdd the register() call
Spans in development, none from the built serverA bundler inlined express and the drivers, so they are never loaded as modulesMark instrumented packages as external
Hundreds of fs spans@opentelemetry/instrumentation-fs is onRemove it from the enabled list, or upgrade the bundle
Spans printed locally, nothing in the backendWrong endpoint or header, or the process exits before a flushCheck the endpoint, then add the shutdown handler
Last requests before each deploy are missingNo SIGTERM handlerCall sdk.shutdown()
Service named unknown_service:nodeOTEL_SERVICE_NAME is not set in the processSet it where the process starts, not in your shell
  • Turn on SDK logs. OTEL_LOG_LEVEL=debug prints one line per patched module (@opentelemetry/instrumentation-express Applying instrumentation patch for module on require hook). A missing line means that library loaded before the SDK or through an unhooked loader.
  • fs spans. Current bundles ship the fs instrumentation disabled. Enabled in a test, it produced 128 spans from one startup and one request, almost all module loading. Older bundles had it on by default.
  • Bundlers. Code inlined by esbuild or webpack is never loaded as a module, so it is never patched. Keep express, your database drivers and the @opentelemetry packages external.
  • TypeScript. Compile first and preload the output: node --import ./dist/instrumentation.js dist/app.js. Whether you need the loader hook depends on what the compiler emits. import statements compiled to require() calls are CommonJS. To skip the build step, Node 24's type stripping (node --import ./instrumentation.mts app.mts) and tsx (node --import tsx --import ./instrumentation.ts app.ts) both produced route-named spans in a test.

For Next.js, use instrumentation.ts instead: OpenTelemetry in Next.js.

Send it to Maple

Maple accepts OTLP directly, so the setup above needs no Collector and no code change. Set the endpoint and your ingest key. The Node SDK also has gRPC exporters, so set the protocol explicitly:

export OTEL_SERVICE_NAME="checkout"
export OTEL_EXPORTER_OTLP_ENDPOINT="https://ingest.maple.dev"
export OTEL_EXPORTER_OTLP_HEADERS="Authorization=Bearer YOUR_INGEST_KEY"
export OTEL_EXPORTER_OTLP_PROTOCOL="http/protobuf"

node --import ./instrumentation.mjs app.mjs
A trace in Maple: a POST /api/checkout request shown as a timeline waterfall of 15 spans across 6 services, with one span marked as an error.
The spans from this guide arrive as a waterfall like this one, with each Express route as an operation.

The Node.js instrumentation docs cover the full setup, including metrics and logs.

Sources and further reading

FAQ

よくある質問

How do I add OpenTelemetry to an Express app?
Install @opentelemetry/sdk-node and @opentelemetry/auto-instrumentations-node, start a NodeSDK in its own file, and load that file before the app: node --import ./instrumentation.mjs app.mjs for ES modules, node --require ./instrumentation.cjs app.cjs for CommonJS. Every request then gets a server span named after the route, with child spans for database and HTTP calls.
Does OpenTelemetry support Express 5?
Yes. @opentelemetry/instrumentation-express supports express >=4.0.0 <6. Express 5 moved routing into the router package, which has its own instrumentation in the auto-instrumentations bundle, so an Express 5 app gets spans from both unless you disable one.
Why does my Express app produce no spans?
Almost always the SDK started after express and http were loaded, so there was nothing left to patch. Move the SDK into its own file and load it with --import or --require. In an ES module app you also need the loader hook from @opentelemetry/instrumentation/hook.mjs, and a bundled server needs express and the other instrumented packages marked as external.
How do I disable Express middleware spans in OpenTelemetry?
Pass ignoreLayersType: ["middleware", "router"] to @opentelemetry/instrumentation-express. On Express 5, also set enabled: false on @opentelemetry/instrumentation-router. The server span keeps its route name and http.route attribute.
How do I get trace_id in Express logs?
Log with Pino or Winston. The auto-instrumentations bundle includes instrumentations for both that add trace_id, span_id and trace_flags to every record written while a span is active, with no change to your logging calls.
What is the difference between auto-instrumentation and manual instrumentation in Express?
Auto-instrumentation patches libraries as they load, so Express routes, http, database drivers and fetch produce spans with no code changes. Manual instrumentation is code you write with @opentelemetry/api, such as tracer.startActiveSpan around a function, to see inside your own logic. Most apps use both: auto-instrumentation for requests and outgoing calls, manual spans for the business steps that matter.

今日、最初のトレースを。

SDKを追加し、OTLPエクスポーターをMapleに向ければトレースが届きます。

maple.dev:OpenTelemetryの上のオブザーバビリティ