Observability in an Express.js application has traditionally involved wrapping framework methods, loading an APM agent before Express, or relying on an integration that knows the framework’s internal behaviour. Those approaches can work, but they are fragile. They may depend on import order, module loading hooks or implementation details that change between releases.
That changed on , when the Express project announced that its router now publishes a standard Node.js TracingChannel. The express.router.request channel exposes the lifecycle of middleware, route handlers and router.param() callbacks, allowing loggers, APM agents and application code to observe Express without patching its methods. The change is described in the project’s announcement, “Express is now observable by design”.
This is useful news for teams maintaining production Node.js services. You can add targeted diagnostics with a small amount of code, keep route labels low-cardinality, and gradually connect the events to an existing telemetry system. The feature is not a replacement for sound logging, metrics or tracing architecture, but it provides a much cleaner integration point.
What Express is exposing
Express uses the router package to execute middleware and route handlers. The new channel publishes lifecycle events for each of those operations. A subscriber can inspect the request, response, matched route pattern, handler function and any error reported during execution.
The channel is named express.router.request. Its context can include:
reqandres, the current HTTP request and response objects.route, the matched route pattern, such as/users/:id.handler, the middleware, route handler or parameter callback being invoked.param, when the operation is arouter.param()callback.error, when a handler throws, rejects or callsnext(error).errorHandler, indicating that the current handler is error-handling middleware.incomingError, when an error handler receives an error from an earlier operation.result, where an operation returns a value or resolves a promise.
The underlying Node.js API defines five lifecycle points: start, end, asyncStart, asyncEnd and error. This matters because Express handlers can be synchronous, callback-based or promise-based. A subscriber must not assume that every handler completes at the same event.
Tracing channels were introduced in Node.js 19.9 and backported to Node.js 18.19. Express’s announcement states that applications need Node.js 18.19 or later to receive these events. On older Node.js versions, the application may continue to run, but the channel will not publish the new router notifications.
Check your prerequisites first
The feature ships through router, the package used by Express 5. The Express project says it is available through router version 2.3.0 and that an Express upgrade is not necessarily required. However, your lockfile must resolve a sufficiently recent router version.
Before changing application code, check the runtime and dependency tree:
node --version
npm ls express router
If the router version is older, update dependencies through your normal review process. Do not blindly delete the lockfile and regenerate the entire dependency tree in production. A controlled update gives you a smaller diff and makes it easier to identify unrelated changes.
You also need to know whether your application runs Express 4 or Express 5. The announced tracing channel is intended for the router used by Express 5. If you operate an Express 4 service, confirm the resolved router version and test the integration in a staging environment before relying on the channel.
Start with a safe diagnostic subscriber
The simplest useful integration is a subscriber that reports which handler failed. This is more actionable than a generic “request failed” message because it identifies the middleware or route callback where the error originated.
const diagnosticsChannel = require('node:diagnostics_channel');
const expressRouterChannel =
diagnosticsChannel.tracingChannel('express.router.request');
expressRouterChannel.subscribe({
error({ req, route, handler, error }) {
const handlerName = handler?.name || '<anonymous>';
console.error(JSON.stringify({
event: 'express.handler.error',
method: req.method,
route,
handler: handlerName,
message: error?.message,
stack: error?.stack
}));
}
});
Load this module during application startup, before traffic reaches the router. The subscriber does not need to import the Express application instance, which is one of the important differences from monkey-patching app.use() or app.get().
Do not send the complete request object to a log aggregator. Express request objects contain headers, socket information and other data that may include credentials or personal information. Select the fields you need and apply the same redaction rules used elsewhere in your service.
Measure request latency without high-cardinality URLs
Latency data becomes difficult to use when every concrete URL becomes a separate metric label. For example, /users/42, /users/43 and /users/44 should normally be grouped under /users/:id, not stored as three unrelated routes.
The tracing channel provides the matched route pattern. You can combine that with the response’s finish event to record the time until Node.js has handed the response to the underlying socket.
const diagnosticsChannel = require('node:diagnostics_channel');
const { performance } = require('node:perf_hooks');
const channel =
diagnosticsChannel.tracingChannel('express.router.request');
const requestState = new WeakMap();
channel.start.subscribe(({ req, res, route, errorHandler }) => {
if (errorHandler || requestState.has(req)) {
return;
}
const state = {
route,
startedAt: performance.now()
};
requestState.set(req, state);
res.once('finish', () => {
const durationMs = performance.now() - state.startedAt;
console.log(JSON.stringify({
event: 'http.server.request',
method: req.method,
route: state.route,
statusCode: res.statusCode,
durationMs: Number(durationMs.toFixed(1))
}));
requestState.delete(req);
});
});
There are two details worth calling out. First, a WeakMap avoids keeping request objects alive after the request has completed. Secondly, the first router operation is used to initialise the request state, while later operations can update the route if necessary. In a real metrics implementation, you should decide whether the route should be taken from the first matched layer, the final route handler or the response’s own routing metadata.
For production metrics, replace console.log() with a non-blocking metrics client or an internal aggregation layer. Logging one record per middleware can create substantial volume on busy services. Usually, one request-level latency metric plus selected handler-level timings is enough.
Understand the lifecycle before recording timings
It is tempting to measure every start event and close the timer on end. That is not always correct. A promise-based handler may complete through asyncEnd, while an error may arrive through error. If your subscriber closes a span or timer at the wrong point, you can record incomplete or duplicate durations.
A robust handler timer needs to account for both synchronous and asynchronous completion:
const activeHandlers = new WeakMap();
channel.subscribe({
start(ctx) {
ctx.startedAt = performance.now();
activeHandlers.set(ctx, true);
},
end(ctx) {
if ('result' in ctx || 'error' in ctx) {
recordHandlerDuration(ctx);
}
},
asyncEnd(ctx) {
recordHandlerDuration(ctx);
},
error(ctx) {
recordHandlerDuration(ctx, true);
}
});
function recordHandlerDuration(ctx, failed = false) {
if (!activeHandlers.has(ctx)) {
return;
}
activeHandlers.delete(ctx);
const durationMs = performance.now() - ctx.startedAt;
const handler = ctx.handler?.name || '<anonymous>';
console.log(JSON.stringify({
event: 'express.handler.duration',
route: ctx.route,
handler,
durationMs: Number(durationMs.toFixed(1)),
failed
}));
}
The exact completion logic should be tested against the handlers your application uses. Include synchronous middleware, middleware that calls next(), promise-returning handlers, rejected promises and error-handling middleware. The diagnostic channel gives you visibility; it does not remove the need to understand Express’s execution model.
Connect the channel to OpenTelemetry
If your organisation already uses OpenTelemetry, the channel can become the Express-specific part of a broader trace. The Express announcement demonstrates creating a span for each middleware or route handler and using the active OpenTelemetry context to keep concurrent requests separate.
A simplified integration looks like this:
const diagnosticsChannel = require('node:diagnostics_channel');
const {
context,
trace,
SpanStatusCode
} = require('@opentelemetry/api');
const tracer = trace.getTracer('express');
const parentContexts = new WeakMap();
const channel =
diagnosticsChannel.tracingChannel('express.router.request');
channel.subscribe({
start(ctx) {
if (!parentContexts.has(ctx.req)) {
parentContexts.set(ctx.req, context.active());
}
const parent = parentContexts.get(ctx.req);
const name = ctx.handler?.name || '<anonymous>';
ctx.span = tracer.startSpan(name, {}, parent);
ctx.token = context.attach(
trace.setSpan(parent, ctx.span)
);
},
end(ctx) {
finishSpan(ctx);
},
asyncEnd(ctx) {
finishSpan(ctx);
},
error(ctx) {
if (ctx.span && ctx.error) {
ctx.span.recordException(ctx.error);
ctx.span.setStatus({
code: SpanStatusCode.ERROR
});
}
}
});
function finishSpan(ctx) {
if (!ctx.span) {
return;
}
ctx.token?.dispose();
ctx.span.end();
}
This is intentionally not a complete OpenTelemetry distribution. A production integration must handle duplicate completion signals, exceptions in instrumentation code, span naming, status codes and shutdown flushing. Prefer an established instrumentation package when one supports your versions and requirements. The channel is especially useful for teams building internal tooling or integrating a library that does not yet have a suitable adapter.
Use AsyncLocalStorage for correlation
Observability becomes much more useful when a log line can be connected to the request and trace that produced it. Node.js AsyncLocalStorage is designed to carry request-scoped state across asynchronous boundaries, including most await and timer operations.
One common pattern is to create a request identifier in early middleware and make it available to later code:
const { AsyncLocalStorage } = require('node:async_hooks');
const crypto = require('node:crypto');
const requestContext = new AsyncLocalStorage();
app.use((req, res, next) => {
const requestId =
req.get('x-request-id') || crypto.randomUUID();
res.setHeader('x-request-id', requestId);
requestContext.run({ requestId }, next);
});
function currentRequestId() {
return requestContext.getStore()?.requestId;
}
Do not blindly trust an incoming request identifier for security decisions. It is a correlation value, not an authentication token. Validate its length and character set, or generate a new identifier and preserve the upstream value in a separately named field if your distributed tracing design requires it.
Also avoid putting large mutable objects into the store. A small immutable structure containing a request ID, trace ID and tenant identifier is easier to reason about and less likely to retain unnecessary data.
Security and privacy considerations
Instrumentation sees traffic at a sensitive point in the request lifecycle. Treat it as production code, not harmless debugging.
- Never log authorisation headers, cookies, session identifiers, API keys or full request bodies by default.
- Redact query parameters that can contain passwords, tokens or personal information.
- Use route templates rather than raw URLs to prevent identifiers appearing in metric labels.
- Limit error messages and stack traces sent to third-party telemetry services.
- Restrict who can query traces and logs, particularly where tenant or account identifiers are present.
- Make sure instrumentation failures cannot bring down the application.
Remember that handler names are not always stable. Anonymous functions, generated functions and minified bundles can produce unhelpful names. Treat handler names as diagnostic hints rather than an access-control or billing dimension.
Performance: measure before adding more signals
The Express announcement says that publishing to a tracing channel with no subscribers is close to free, and that libraries can avoid allocating context objects when there are no subscribers. That is helpful, but a subscriber can still introduce meaningful overhead if it serialises large objects, performs synchronous I/O or emits too many events.
Keep subscribers small and defensive:
- Check whether the event is relevant before doing work.
- Use route templates and bounded labels.
- Prefer an asynchronous transport or in-process aggregation over writing every event synchronously.
- Sample detailed handler spans while retaining complete request-level error data.
- Benchmark representative traffic with the subscriber enabled and disabled.
- Watch event-loop delay, CPU usage, memory use and telemetry export failures.
Do not claim that tracing channels make an application faster. Their primary benefit is a more stable observation boundary. Whether the result is faster, slower or neutral depends on the subscriber and exporter you attach.
Deployment checklist
- Confirm that production uses Node.js 18.19 or later.
- Check that the lockfile resolves the router version containing the tracing channel.
- Start with error attribution and request-level latency.
- Use route patterns, not concrete URLs, for metrics and span names.
- Test synchronous, callback-based, promise-based and rejected handlers.
- Redact sensitive request data before it reaches logs or telemetry.
- Load instrumentation during application startup and verify it in staging.
- Measure overhead under representative concurrency.
- Ensure the application still starts if the telemetry exporter is unavailable.
- Document which events are sampled, retained and accessible to operators.
Why this development matters
Express has been widely instrumented for years, but framework-level support changes the relationship between the application and its tooling. Instead of an APM agent guessing how routing works by replacing methods, Express can publish the events at the point where it knows what is happening.
The result is a smaller and more explicit contract: Express publishes router lifecycle data, while subscribers decide whether to turn it into logs, metrics, spans or debugging output. That separation should be easier to maintain across CommonJS, ESM and bundled deployments than integrations that depend on module interception.
The new channel is not a reason to remove existing observability libraries immediately. Treat it as a foundation for incremental improvement. Add a small subscriber, verify the event sequence in a non-production environment, and then connect only the signals that answer real operational questions. For many Express teams, that is enough to locate slow middleware, identify the handler responsible for failures and improve trace structure without rewriting the application.
For the complete event contract and the latest implementation details, read the official Express tracing-channel announcement and the linked router documentation. Recheck those sources when upgrading Node.js, Express or router, because diagnostics APIs and integration guidance can evolve.