Node.js & Libuv•Part 4: Express, Fastify, APIs & Middleware (36 - 50)
Correlation IDs with `AsyncLocalStorage`.
In Simple Words:
Inject an X-Correlation-ID header into every outgoing HTTP request or log message, reading from AsyncLocalStorage to enable distributed tracing across microservice boundaries.
javascript
// Propagating correlation ID in outgoing fetch call:
async function callPaymentService(payload) {
const store = asyncLocalStorage.getStore();
return fetch('https://payment.internal/charge', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Correlation-ID': store?.traceId || 'unknown'
},
body: JSON.stringify(payload)
});
}