How do you implement request tracing and correlation IDs in Express?
Answer
A correlation ID is a unique identifier attached to every request and propagated through all logs, services, and responses — enabling end-to-end tracing of a request across distributed systems. Implement with middleware: app.use((req, res, next) => { req.correlationId = req.headers['x-correlation-id'] || uuid.v4(); res.set('x-correlation-id', req.correlationId); next(); });. Include the ID in all log lines: logger.info({ correlationId: req.correlationId, msg: 'Processing request' }). Pass it to downstream service calls in request headers. Use AsyncLocalStorage (Node.js 14+) to make the correlation ID available throughout the call stack without threading it through every function parameter, enabling "ambient" request context similar to thread-local storage.
Previous
How do you implement a graceful shutdown in Express.js?
Next
What is the Express.js application lifecycle?
More Express.js Questions
View all →- Advanced How do you implement WebSocket support alongside Express.js?
- Advanced What are security best practices for Express.js APIs?
- Advanced How does clustering work in Node.js/Express for better performance?
- Advanced What is the difference between Express 4.x and Express 5.x?
- Advanced How do you implement a graceful shutdown in Express.js?