5 Express.js Middleware Patterns You'll Use in Every App
Middleware is what makes Express powerful. These patterns show up in every production app.
What Is Middleware?
// A function that has access to req, res, and next function myMiddleware ( req , res , next ) { // Do something with the request console . log ( ` ${ req . method } ${ req . path } ` );
// Either respond (end the chain) if ( req . path === ' /health ' ) { return res . json ({ status : ' ok ' }); }
// Or pass control to the next middleware next (); }
app . use ( myMiddleware );
Enter fullscreen mode
Exit fullscreen mode
Pattern 1: Request Logging & Correlation IDs
import { randomUUID } from ' crypto ' ;
// Add a unique ID to every request for tracing function requestId ( req , _res , next ) { req . id = req . headers [ ' x-request-id ' ] || randomUUID (); next (); }
// Structured logging with context function logger ( req , _res , next ) { const start = Date . now ();
_res . on ( ' finish ' , () => { const duration = Date .…