Intermediate LevelExpress JS
How do you build a custom Express request logging middleware that injects unique Correlation IDs using AsyncLocalStorage?
❓ Interview Prompt: Explain trace context propagation, AsyncLocalStorage, generating X-Correlation-ID headers, and attaching trace IDs to logs.
In microservice architectures, tracing a single request through 10 downstream service logs requires propagating a Correlation ID ('X-Correlation-ID').
AsyncLocalStorage Integration:
Node.js 'AsyncLocalStorage' creates asynchronous execution contexts. Express middleware generates a UUID, stores it in 'AsyncLocalStorage', and sets headers. All downstream loggers retrieve the active Correlation ID automatically without passing it through function parameters!
Code Implementation Example
javascript
import express from 'express';
import { AsyncLocalStorage } from 'async_hooks';
import crypto from 'crypto';
const asyncLocalStorage = new AsyncLocalStorage();
const app = express();
app.use((req, res, next) => {
const correlationId = req.get('X-Correlation-ID') || crypto.randomUUID();
res.set('X-Correlation-ID', correlationId);
// Run downstream middleware inside AsyncLocalStorage context!
asyncLocalStorage.run({ correlationId }, () => next());
});
export const log = (msg) => {
const store = asyncLocalStorage.getStore();
console.log(`[${store?.correlationId || 'N/A'}] ${msg}`);
};💡Propagating Correlation IDs across log calls using AsyncLocalStorage.
🎯 Interview Key Takeaway
Use AsyncLocalStorage to propagate request Correlation IDs across all internal log calls without parameter passing.
#AsyncLocalStorage#Correlation ID#Logging#Intermediate
Back to all Express JS Questions→