Skip to content

runWithCorrelationId

runWithCorrelationId<T>(correlationId, fn): T

Defined in: correlation.store.ts:72

Run a callback within a correlation context.

Use this in non-HTTP entry points (queue workers, message consumers, WebSocket handlers, scheduled jobs) to propagate an external correlation ID into everything the callback runs, wrapped operations included.

When correlationId is missing, empty, not printable ASCII without surrounding spaces, or, once configureCorrelation has been called, rejected by its rules, fn runs with the id getCorrelationId returns (the current one, or a new one from correlationSource.create()), so it always runs with a correlation id. A rejected id is reported to onRejected with the source 'runWithCorrelationId'. A pipeline dispatched inside fn takes the id as its context.correlationId.

T

string | undefined

The correlation ID to propagate, as received from outside.

() => T

The callback to execute within the correlation context.

T

// BullMQ worker
new Worker('emails', (job) =>
  runWithCorrelationId(job.data.correlationId, () => sendEmail(job.data)),
);

// RabbitMQ consumer (amqplib)
channel.consume('users', (message) =>
  runWithCorrelationId(message.properties.correlationId, () =>
    onUserCreated(JSON.parse(message.content.toString())),
  ),
);

// Scheduled job: no incoming id, so a new one is made
setInterval(() => runWithCorrelationId(undefined, () => hourlySync()), 3_600_000);