Compose Middleware

5.0.1 · active · verified Wed Apr 22

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.

Common errors

Warnings

Install

Imports

Quickstart

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}`);
});

view raw JSON →