Node.js HTTP adapter for Stainless X-ray request logging
npm install @stainlessdev/xray-nodeNode.js HTTP adapter for Stainless X-ray request logging. Use this for node:http servers or to power framework integrations (Express/Fastify).
``sh`
pnpm add @stainlessdev/xray-node
`ts
import { createServer } from 'node:http';
import { createEmitter, wrapHttpHandler } from '@stainlessdev/xray-node';
const xray = createEmitter({
serviceName: 'my-service',
endpointUrl: 'http://localhost:4318',
// Optional: customize the request ID header name
requestId: { header: 'request-id' },
});
const server = createServer(
wrapHttpHandler((_req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('ok');
}, xray),
);
server.listen(3000);
`
`ts
import { getXrayContext } from '@stainlessdev/xray-node';
const handler = wrapHttpHandler((req, res) => {
const ctx = getXrayContext(req);
ctx?.setUserId('user-123');
res.end('ok');
}, xray);
`
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) accepts XrayRuntimeConfig from @stainlessdev/xray-core:
- serviceName (required)endpointUrl
- (required; falls back to STAINLESS_XRAY_ENDPOINT_URL when omitted; explicit endpointUrl wins)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
wrapHttpHandler(handler, xray, options) and createEmitter(config, options?) share:
- 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
- This package depends on OpenTelemetry packages as peer dependencies.
- Node.js >= 20 is required.