Cloud

Correlation IDs

Request and correlation ID middleware for distributed tracing, attached to req.locals and echoed in response headers.

2 min readUpdated DocumentationEdit this page
On this page6

Overview

correlationId() gives every request a request ID and a correlation ID. The request ID identifies one hop; the correlation ID is shared across a chain of service calls. Incoming headers are reused when present; otherwise new IDs are generated. Both IDs are attached to req.locals and echoed in response headers.

Usage

TypeScript
TS
1import { correlationId } from '@axiljs/cloud'
2
3app.use(correlationId())
4
5app.get('/api/data', (req, res) => {
6  console.log(req.locals.requestId)     // 'req_3f9a1c0b7e2d4a58'
7  console.log(req.locals.correlationId) // 'corr_8b1e6d2f0a9c7e43'
8  res.success({ data: '...' })
9})

Generated IDs are a prefix (req_ or corr_) followed by 16 hex characters from crypto.randomBytes(8).

Response Headers

HeaderDescription
x-request-idRequest ID for this hop
x-correlation-idShared ID across a chain of service calls

Header names follow the requestIdHeader and headerName options.

Propagating Across Services

When calling downstream services, forward the correlation ID:

TypeScript
TS
1const response = await fetch('http://payment-service:3002/charge', {
2  headers: {
3    'x-correlation-id': req.locals.correlationId,
4  },
5})

The downstream service's correlationId() middleware keeps the incoming correlation ID. It also reuses an incoming x-request-id if you send one, so omit that header if each hop should get its own request ID.

Options

TypeScript
TS
1app.use(correlationId({
2  headerName: 'x-correlation-id',    // correlation ID header (read and echoed)
3  requestIdHeader: 'x-request-id',   // request ID header (read and echoed)
4  generateIfMissing: true,           // generate IDs when the header is absent
5}))
OptionTypeDefaultDescription
headerNamestring'x-correlation-id'Correlation ID header
requestIdHeaderstring'x-request-id'Request ID header
generateIfMissingbooleantrueWhen false, IDs are only set if the client sent them

Use lowercase header names: incoming headers are looked up exactly as given, and Node lower-cases incoming header names.

Using With Other Packages

auditMiddleware() records req.locals.requestId as the audit event's requestId, so register correlationId() before it. @axiljs/observability tracing uses its own W3C traceparent / B3 context and does not read these IDs; add them to spans yourself if you need both.

Was this page helpful?

Help improve the documentation

AxilJS is open source and documentation improvements are welcome.

AxilJS DocumentationMIT License · Built by SyntaxilitY