Menu

1 / 2

Stop Passing req Everywhere — Express Middleware for Request Context Propagation

DEV Community·Saifuddin Tipu·6 months ago
#QIzbhU7d
#typescript#node#express#webdev#correlation
Reading 0:00
15s threshold

There's a pattern I've seen in almost every Express codebase I've worked in. It starts small.

You need to log a correlation ID inside a service function. So you add req as a parameter. Then the function that calls it needs req . Then the one above that. Within a few weeks, half your codebase takes req as a parameter even though it only ever reads one field from it.

// This is where it starts async function processOrder ( orderId : string , req : Request ) { logger . info ( ' Processing order ' , { correlationId : req . headers [ ' x-correlation-id ' ] }); await notifyWarehouse ( orderId , req ); // now warehouse needs req too await sendEmail ( orderId , req ); // and email await auditLog ( ' order.processed ' , req ); // and audit }

Enter fullscreen mode

Exit fullscreen mode

Every function signature is polluted. Tests need a mock req . Services are coupled to Express internals.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.