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-nodeis the SDK: tracer, exporters and context tracking.@opentelemetry/auto-instrumentations-nodebundles instrumentations for Express,http,pg, Redis clients,fetch, Pino, Winston and about 30 other libraries.@opentelemetry/apiis 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 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 4 | Express 5 | |
|---|---|---|
| Spans for the sample request | 6 | 8 |
| Built-in middleware spans | query and expressInit on every request | None |
| Which instrumentations emit | express | express and router |
Rejected promise in an async handler | Never reaches Express: call next(err) yourself | Goes to the error middleware, and the handler span is marked as an error |
Server span name and http.route | GET /orders/:id | GET /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.
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 callednext()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 handlerspan 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 namedGET /orders/:id. - Keep the Express instrumentation on. It gives the server span its route. With
OTEL_NODE_DISABLED_INSTRUMENTATIONS=express,routerthe request produced a span namedGETwith nohttp.route. - Drop one layer.
ignoreLayerstakes strings, regular expressions or functions matched against the layer's path. - Drop whole requests.
ignoreIncomingRequestHookon 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
/orderswith a route/:idreports/orders/:id. - Unmatched requests have no route. A 404 is named
GETwith nohttp.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.pathholds/orders/42. Filter on it, but group and alert onhttp.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:
- Queries keep their placeholders.
db.query.textisSELECT 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.connecttook 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
traceparentheader, so an instrumented rates service continues the same trace. Context propagation covers queues and other transports. - Client spans are named after the method. The
fetchspan isGET. The target is inurl.fullandserver.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.
finallycovers both paths. - recordException does not set the status. It adds an
exceptionevent with the type, message and stack trace. The span counts as failed only aftersetStatuswithSpanStatusCode.ERROR. - Prefer attributes for small facts.
trace.getActiveSpan()?.setAttribute()putsorder.totalon 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_idmatches 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
NodeSDKexports those over OTLP by default. If you already collect stdout, setOTEL_LOGS_EXPORTER=noneso lines are not stored twice. console.logis 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" | Setting | Default | What to do |
|---|---|---|
service.name | unknown_service:node | Always set it. Add deployment.environment.name and service.version to split environments and compare releases. |
| Endpoint | http://localhost:4318 | A base URL for a Collector or a backend. The OTLP guide covers ports, headers and status codes. |
| Sampling | Every trace is kept | parentbased_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. |
| Batching | Export every 5 s or 512 spans, queue of 2048 | Tune 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 detectors | env, host, os, process, serviceinstance | Pick 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.mjsfor--importand 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
registerentry callssdk.shutdown()onSIGTERMbut 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.
| Symptom | Cause | Fix |
|---|---|---|
| No spans at all, no error | The SDK started after express and http were loaded | Load the file with --import or --require |
Server spans named GET, no Express spans, ES module app | No loader hook, so the imported express was not patched | Add the register() call |
| Spans in development, none from the built server | A bundler inlined express and the drivers, so they are never loaded as modules | Mark instrumented packages as external |
Hundreds of fs spans | @opentelemetry/instrumentation-fs is on | Remove it from the enabled list, or upgrade the bundle |
| Spans printed locally, nothing in the backend | Wrong endpoint or header, or the process exits before a flush | Check the endpoint, then add the shutdown handler |
| Last requests before each deploy are missing | No SIGTERM handler | Call sdk.shutdown() |
Service named unknown_service:node | OTEL_SERVICE_NAME is not set in the process | Set it where the process starts, not in your shell |
- Turn on SDK logs.
OTEL_LOG_LEVEL=debugprints 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
fsinstrumentation 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@opentelemetrypackages 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.importstatements compiled torequire()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
The Node.js instrumentation docs cover the full setup, including metrics and logs.