Skip to content
jshacks.dev
Functions

Build a middleware chain with reduce

Build a middleware chain in JavaScript with reduceRight, where each function receives a context and a next function. Works in any Node.js.

1 min read
Summarize in AI

Frameworks like Express and Koa pass a request through functions that each decide whether to call the next. reduceRight can build the chain from the last handler to the first.

JavaScript
const chain = (middlewares) => (ctx) =>
  middlewares.reduceRight((next, middleware) => () => middleware(ctx, next), () => {})();

const app = chain([
  (ctx, next) => {
    ctx.log.push('a in');
    next();
    ctx.log.push('a out');
  },
  (ctx, next) => {
    ctx.log.push('b in');
    next();
    ctx.log.push('b out');
  },
  (ctx) => {
    ctx.log.push('handler');
  },
]);

const ctx = { log: [] };
app(ctx);
console.log(ctx.log.join(' > '));
Text
a in > b in > handler > b out > a out

Going from the end, each step wraps the function that follows it in a next that calls the next middleware with the same context. The first step receives an empty function as its next. A middleware can run code before and after calling next(), which gives the nesting in the output.

This version is synchronous. For async middleware, make each step return a promise and await next(). A middleware that forgets to call next stops the chain, which is how guards work. See reduceRight.

Taggednode 24
Share

More snippets

Functions

Memoize a function with a Map

Memoize a function in JavaScript with a Map keyed by its argument, caching results including undefined. For single-argument pure functions on any Node.js.

1 min read
Functions

Write a once function

Write a once function in JavaScript that runs a callback a single time and returns the cached result after that. Works in any Node.js, ES2015 or later.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.