JavaScript

Middleware Pipeline

by @admin
10h ago
Apr 28, 2026
Public
A simple Koa/Express-style middleware runner for client-side use. Middleware functions receive a context object and a next() function — call next() to pass control to the next middleware or skip it to short-circuit the chain. Useful for building plugin systems, request pipelines, and composable validation logic.
JavaScript
function createPipeline(...middlewares) {
  return function run(context) {
    let index = -1;
    function dispatch(i) {
      if (i <= index) return Promise.reject(new Error('next() called multiple times'));
      index = i;
      const fn = middlewares[i];
      if (!fn) return Promise.resolve();
      try {
        return Promise.resolve(fn(context, () => dispatch(i + 1)));
      } catch (err) {
        return Promise.reject(err);
      }
    }
    return dispatch(0);
  };
}

// Usage
const pipeline = createPipeline(
  async (ctx, next) => { ctx.start = Date.now(); await next(); ctx.duration = Date.now() - ctx.start; },
  async (ctx, next) => { if (!ctx.user) throw new Error('Unauthenticated'); await next(); },
  async (ctx)       => { ctx.result = await fetch(`/api/user/${ctx.user}`).then((r) => r.json()); }
);
await pipeline({ user: 'alice' });
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.