Registry / web-framework / compose-middleware

compose-middleware

JSON →
library5.0.1jsnpmunverified

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-middleware
INSTALL
IMPORT
SIG · COMPOSE-MIDDLEWARE
C
compose-middleware
web-frameworkjavascriptv5.0.1
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

compose
import { compose } from 'compose-middleware'
const compose = require('compose-middleware').compose
The `compose` function is a named export for ESM. For CommonJS, it's accessed as a property of the default require.
errors
import { errors } from 'compose-middleware'
const errors = require('compose-middleware').errors
The `errors` function is a named export specifically for composing 4-argument error middleware. Similar CommonJS usage as `compose`.
ComposeMiddleware
import type { ComposeMiddleware } from 'compose-middleware'
Type import for the main middleware composition function signature, useful for strict TypeScript environments.

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.

import express from 'express'; import { compose, errors } from 'compose-middleware'; const app = express(); // A basic middleware function const logRequest = (req: express.Request, res: express.Response, next: express.NextFunction) => { console.log(`Request received: ${req.method} ${req.url}`); next(); }; // An error-handling middleware const handleError = (err: Error, req: express.Request, res: express.Response, next: express.NextFunction) => { console.error(`An error occurred: ${err.message}`); res.status(500).send('Something broke!'); }; // Composing a sequence of regular middleware app.use(compose([ logRequest, (req, res, next) => { req.body = req.body || {}; next(); }, (req, res, next) => { console.log('Processing request...'); next(); } ])); // Composing a sequence of error-handling middleware app.use(errors([ (err, req, res, next) => { if (err.message === 'validation error') { console.log('Validation failed'); return next(err); } next(err); }, handleError ])); // Example route to trigger middleware app.get('/', (req, res) => { res.send('Hello World!'); }); // Example route to trigger an error app.get('/error', (req, res, next) => { next(new Error('This is an intentional error!')); }); const PORT = process.env.PORT || 3000; app.listen(PORT, () => { console.log(`Server running on http://localhost:${PORT}`); });
Debug
Known issues
breakingVersion 5.0.0 introduced stricter TypeScript type signatures, removing optional types from function parameters. This may cause type errors in existing TypeScript projects.
fix
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.
affects: >=5.0.0
breakingVersion 3.0.0 changed the error re-throwing mechanism. Errors thrown synchronously from `done()` or other inconsistent states are now re-thrown higher up the stack, which might alter error handling flow for complex or edge-case error patterns.
fix
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.
affects: >=3.0.0
breakingVersion 2.2.0 introduced validation that throws an error if `next()` is called multiple times within a single middleware execution. This prevents common pitfalls and ensures predictable middleware execution.
fix
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.
affects: >=2.2.0
breakingVersion 2.0.0 added validation for all middleware functions and introduced support for 4-argument error handlers. Providing non-function middleware or incorrectly structured error handlers will now result in errors.
fix
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)`.
affects: >=2.0.0
gotchaThe `compose` function returns a 3-argument middleware function (req, res, next), suitable for regular request processing. The `errors` function returns a 4-argument error middleware function (err, req, res, next).
fix
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.
affects: >=2.0.0
Errors
Common errors & fixes
Error: next() called multiple times
A middleware function within the composed chain called `next()` more than once for a single request, which is disallowed since v2.2.0.
fix
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.
Argument of type '(...)' is not assignable to parameter of type '(...)'
This TypeScript error indicates a mismatch in middleware function signatures, often due to the stricter type definitions introduced in v5.0.0, or incorrect argument counts (e.g., passing a 4-arg function where a 3-arg is expected).
fix
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.
Error: Middleware must be a function
An element passed into the array for `compose` or `errors` was not a JavaScript function. This validation was added in v2.0.0.
fix
Verify that all items in the array passed to `compose` or `errors` are indeed functions, and not `null`, `undefined`, or other data types.
Upgrade
Version history
5.0.1latest on npm
Audit
Dependencies
debugrequiredUsed for internal debugging, updated to v3 in compose-middleware v4.0.0.
Agent activity
16 hits · last 30 days
node
14
OpenAI (training)
1
Resources
compose-middleware — npm install compose-middleware · libregistry