compose-middleware is a utility library designed to combine an array of Express- or Connect-style middleware functions into a single, cohesive middleware function. This package is currently stable at version 5.0.1, with recent updates primarily focusing on TypeScript type improvements and stricter function signatures. Historically, major versions have introduced changes to error handling logic and middleware validation. Its key differentiators include built-in support for inline error handling middleware, which can be composed separately using the `errors` export, and robust validation of middleware functions to prevent common pitfalls in middleware chains. It provides a flexible way to structure complex middleware pipelines for web frameworks.
npm install compose-middlewareVerified import paths — ran on the pinned version, not inferred.
This example demonstrates composing both standard middleware and error-handling middleware for an Express application using `compose` and `errors` exports. It sets up an Express server with logging, body parsing, and a global error handler, showing how different middleware types are integrated into the application's request processing pipeline.
Review and update middleware function signatures to match the stricter `(req, res, next)` or `(err, req, res, next)` patterns, ensuring all parameters are explicitly handled.
Thoroughly test existing error handling middleware after upgrading. Ensure custom error handling logic correctly catches and processes errors without unintended re-throws or missed errors.
Inspect middleware functions to ensure `next()` is only called once per request. If multiple asynchronous operations are involved, use promises or async/await to ensure `next()` is only invoked after all operations complete, or handle branching logic explicitly.
Ensure all entries in the middleware array are valid functions. Error handlers must accept exactly four arguments `(err, req, res, next)`, while regular middleware accepts three `(req, res, next)`.
Always use `compose` for regular middleware chains and `errors` for chains specifically designed to handle errors. Do not mix their intended uses as their signatures differ.
Review the middleware where the error originates and ensure `next()` is called exactly once. Use `return next();` to prevent accidental subsequent execution or wrap asynchronous calls in promises.
Explicitly define types for `req`, `res`, `next`, and `err` (if applicable) in your middleware functions. Ensure 3-argument middleware is used with `compose` and 4-argument middleware with `errors`, aligning with the library's expected types.
Verify that all items in the array passed to `compose` or `errors` are indeed functions, and not `null`, `undefined`, or other data types.