Js mediator middleware pattern

From Intense-Visions/harness-engineering · View interactive version

Js mediator middleware pattern is an AI agent skill from the GitHub repository Intense-Visions/harness-engineering. > Route component interactions through a central mediator to reduce direct coupling

How to use this skill

Skill file

JS Mediator / Middleware Pattern

Route component interactions through a central mediator to reduce direct coupling

When to Use

Instructions

  1. Mediator: Create a central object that components register with. Components send messages to the mediator, not to each other.
  2. Middleware: Define a chain of functions that each receive (req, res, next) (or equivalent) and call next() to pass control.
  3. Keep the mediator/middleware functions pure — no shared mutable state between middleware steps.
  4. Provide a way to skip remaining middleware (next('skip') or returning early).
// Middleware pipeline
class Pipeline {
  constructor() {
    this.middlewares = [];
  }

  use(fn) {
    this.middlewares.push(fn);
    return this;
  }

  execute(context) {
    let index = 0;
    const next = () => {
      const fn = this.middlewares[index++];
      if (fn) fn(context, next);
    };
    next();
  }
}

const pipeline = new Pipeline();
pipeline
  .use((ctx, next) => {
    ctx.log = [];
    next();
  })
  .use((ctx, next) => {
    ctx.log.push('step1');
    next();
  })
  .use((ctx) => {
    ctx.log.push('step2');
  });

const ctx = {};
pipeline.execute(ctx);
console.log(ctx.log); // ['step1', 'step2']

Details

The Mediator pattern (GoF) centralizes communication. The Middleware pattern (popularized by Express.js) is a sequential pipeline variant. Both reduce point-to-point coupling by routing interactions through a shared hub or chain.

Trade-offs:

When NOT to use:

Source

https://patterns.dev/javascript/mediator-middleware-pattern

Process

  1. Read the instructions and examples in this document.
  2. Apply the patterns to your implementation, adapting to your specific context.
  3. Verify your implementation against the details and edge cases listed above.

Harness Integration

Success Criteria

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.