Express integration for Stainless X-ray request logging. Provides a middleware that wraps Express requests and responses.
pnpm add @stainlessdev/xray-emitterimport express from 'express';
import { createEmitter } from '@stainlessdev/xray-emitter/express';
import { getXrayContext } from '@stainlessdev/xray-emitter/node';
const app = express();
const xray = createEmitter({ serviceName: 'my-service' });
app.use(xray);
app.use((req, _res, next) => {
const ctx = getXrayContext(req);
ctx?.setActor('tenant-123', 'user-123');
next();
});
app.get('/', (_req, res) => {
res.send('ok');
});The middleware also attaches the context to req.xray and res.locals.xray for convenience.
X-ray will auto-generate a request ID and inject it into your response headers under the configured name (requestId.header, default request-id, emitted as Request-Id) if the header is missing. If you set your own request ID first (via options.requestId or by setting the response header yourself), X-ray preserves it and does not overwrite the header.
createEmitter(config, options?) accepts XrayRuntimeConfig (config) and WrapOptions (per-request defaults):
serviceName(required)endpointUrl(required; falls back toSTAINLESS_XRAY_ENDPOINT_URLwhen omitted; explicitendpointUrlwins)environment,version,logger,logLevelexporter:endpointUrl,headers,timeoutMs,spanProcessor,instance(custom SpanExporter)capture: request/response headers and bodiesredaction: headers/query/body JSON-path redactionrequestId: header name to read/writeroute: normalization options
route: override the route name for the requestrequestId: explicit request ID to use (prevents auto-generation)capture: per-request capture overridesredaction: per-request redaction overridesonRequest(ctx),onResponse(ctx, log),onError(ctx, err)hooks
If you already have an XrayEmitter instance, use createExpressMiddleware(xray, options) to create middleware.
- This package depends on OpenTelemetry packages as peer dependencies.
- Node.js >= 20 is required.