Co Compose Middleware

7.0.3 · active · verified Wed Apr 22

Co-compose is a lightweight, framework-agnostic middleware composition library for JavaScript and TypeScript applications, inspired by patterns found in Koa and AdonisJS. It enables developers to define an array of asynchronous functions (middleware) and execute them sequentially, with explicit control flow via a `next()` function. The current stable version is 7.0.3, which primarily includes dependency updates and minor fixes. Major versions, like v7, tend to update Node.js compatibility requirements, with minor and patch releases focusing on performance improvements and dependency hygiene. Key differentiators include its reported high performance (benchmarked against alternatives like `fastseries` and `middie`), flexibility with custom executors for different middleware shapes (e.g., ES6 classes), and a dedicated final handler mechanism. It ships with full TypeScript types, making it suitable for modern typed environments.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates basic middleware registration and sequential execution using the `Middleware` class, including how to pass context.

import { Middleware } from 'co-compose'

async function fn1(next) {
  console.log('executing fn1')
  await next()
}

async function fn2(next) {
  console.log('executing fn2')
  await next()
}

// Create a new middleware instance
const middleware = new Middleware()

// Register middleware functions
middleware.register([fn1, fn2])

// Run the middleware chain with optional context
async function runChain() {
  const ctx = { data: 'initial' }
  await middleware.runner().run([ctx])
  console.log('Middleware chain finished.')
}

runChain().catch(console.error)

view raw JSON →