Skip to content
jshacks.dev
Patterns

The Mediator Pattern in JavaScript, With Real Examples

The mediator pattern routes communication between objects through one coordinator so they stop depending on each other. See a chat room and a form.

8 min read
Summarize in AI
Flat illustration of an editor window full of code, with the JavaScript, Node.js, npm, TypeScript and Vite logos.

The mediator pattern replaces direct communication between many objects with communication through one coordinating object. Instead of each component holding references to every other component it needs to talk to, they all talk to the mediator, and the mediator decides who hears what. The aim is to cut a tangle of many-to-many dependencies down to a star. You see it in chat rooms, air traffic control towers, form controllers and the "container component" in a front-end app that owns the state its children share. This post builds mediators in JavaScript on Node.js 24: a chat room, a form where fields affect each other and a typed event mediator, and covers how it differs from the observer pattern, how to test it and the main hazard, a mediator that grows into a god object. Every sample prints its output.

The problem: everyone knows everyone

Consider a form with a country selector, a state selector and a postcode field. Picking the country changes which states are valid, which in turn changes the postcode format. Wired directly, each widget knows about the others.

tangled.mjsJavaScript
const state = { options: [], disabled: true };
const postcode = { pattern: null };

const country = {
  value: null,
  select(value) {
    this.value = value;
    // country reaches into the others
    state.options = value === "US" ? ["CA", "NY"] : value === "CA" ? ["ON", "QC"] : [];
    state.disabled = state.options.length === 0;
    postcode.pattern = value === "US" ? /^\d{5}$/ : value === "CA" ? /^[A-Z]\d[A-Z] ?\d[A-Z]\d$/ : null;
  },
};

country.select("US");
console.log(state, postcode.pattern.source);
Text
{ options: [ 'CA', 'NY' ], disabled: false } ^\d{5}$

The country widget now knows how states and postcodes work. Add a "shipping method" widget that depends on the country too, and you must edit country. Add a rule between state and postcode and you edit two widgets. The widgets cannot be reused elsewhere, because each drags its neighbors along.

The mediator

Move the coordination into one object. The widgets only report what happened to the mediator and expose a way to be updated.

form-mediator.mjsJavaScript
const RULES = {
  US: { states: ["CA", "NY"], postcode: /^\d{5}$/ },
  CA: { states: ["ON", "QC"], postcode: /^[A-Z]\d[A-Z] ?\d[A-Z]\d$/ },
};

function createFormMediator() {
  const widgets = {};
  return {
    register(name, widget) {
      widgets[name] = widget;
      widget.mediator = this;
    },
    notify(sender, event, value) {
      if (sender === "country" && event === "changed") {
        const rule = RULES[value];
        widgets.state.setOptions(rule ? rule.states : []);
        widgets.postcode.setPattern(rule ? rule.postcode : null);
      }
      if (sender === "state" && event === "changed") {
        widgets.postcode.clear();
      }
    },
  };
}

const log = [];
const widgets = {
  country: { change(v) { this.mediator.notify("country", "changed", v); } },
  state: {
    setOptions(options) { log.push(`state options: ${options.join("/") || "none"}`); },
    change(v) { this.mediator.notify("state", "changed", v); },
  },
  postcode: {
    setPattern(p) { log.push(`postcode pattern: ${p ? p.source : "none"}`); },
    clear() { log.push("postcode cleared"); },
  },
};

const mediator = createFormMediator();
for (const [name, widget] of Object.entries(widgets)) mediator.register(name, widget);

widgets.country.change("CA");
widgets.state.change("ON");
widgets.country.change("FR");
console.log(log);
Text
[
  'state options: ON/QC',
  'postcode pattern: ^[A-Z]\\d[A-Z] ?\\d[A-Z]\\d$',
  'postcode cleared',
  'state options: none',
  'postcode pattern: none'
]

Look at what changed. country knows nothing about state or postcode: it calls notify and stops. A new "shipping" widget registers with the mediator, and only the mediator's rules change. The widgets can be reused in other forms with other mediators. The cost is that the mediator now holds all the coordination logic, which is the point: it is all in one place, where you can read it.

A chat room

The textbook example is a chat room. Users do not hold references to each other. They send a message to the room, and the room delivers it.

chat.mjsJavaScript
class ChatRoom {
  #users = new Map();

  join(user) {
    this.#users.set(user.name, user);
    user.room = this;
    this.#broadcast(`${user.name} joined`, user.name);
  }

  leave(user) {
    this.#users.delete(user.name);
    this.#broadcast(`${user.name} left`, user.name);
  }

  send(from, text, to = null) {
    if (to) {
      this.#users.get(to)?.receive(from, text, { private: true });
      return;
    }
    this.#broadcast(text, from);
  }

  #broadcast(text, from) {
    for (const user of this.#users.values()) {
      if (user.name !== from) user.receive(from, text);
    }
  }
}

class User {
  inbox = [];
  constructor(name) {
    this.name = name;
  }
  say(text, to) {
    this.room.send(this.name, text, to);
  }
  receive(from, text, { private: isPrivate = false } = {}) {
    this.inbox.push(`${isPrivate ? "(private) " : ""}${from}: ${text}`);
  }
}

const room = new ChatRoom();
const ada = new User("ada");
const grace = new User("grace");
const alan = new User("alan");

room.join(ada);
room.join(grace);
room.join(alan);
ada.say("hello everyone");
grace.say("psst", "alan");
room.leave(alan);

console.log(ada.inbox);
console.log(alan.inbox);
Text
[ 'grace: grace joined', 'alan: alan joined', 'alan: alan left' ]
[ 'ada: hello everyone', '(private) grace: psst' ]

Ada's inbox holds the joins and the leave, since she was in the room for all of them, and none of her own messages. Alan received Ada's broadcast and Grace's private note, and nothing after he left. No user holds a reference to another user: each knows only room. The room owns membership, delivery and the rules, such as private messages, so adding muting or rate limits means changing ChatRoom only.

A typed event mediator

A common lightweight form is a small hub with named channels. It looks like an event emitter, with the difference that it represents a central coordinator that components agree to use, and it often holds the coordination rules too.

hub.tsTypeScript
type Events = {
  "cart:itemAdded": { sku: string; qty: number };
  "cart:cleared": undefined;
  "checkout:started": { total: number };
};

class Hub {
  private handlers: { [K in keyof Events]?: Array<(payload: Events[K]) => void> } = {};

  on<K extends keyof Events>(event: K, handler: (payload: Events[K]) => void) {
    (this.handlers[event] ??= []).push(handler);
  }

  emit<K extends keyof Events>(event: K, payload: Events[K]) {
    for (const handler of this.handlers[event] ?? []) handler(payload);
  }
}

const hub = new Hub();
const seen: string[] = [];
hub.on("cart:itemAdded", ({ sku, qty }) => seen.push(`badge +${qty} ${sku}`));
hub.on("cart:itemAdded", ({ sku }) => seen.push(`analytics ${sku}`));
hub.on("cart:cleared", () => seen.push("badge reset"));

hub.emit("cart:itemAdded", { sku: "A1", qty: 2 });
hub.emit("cart:cleared", undefined);
// hub.emit("cart:itemAdded", { sku: "A1" });  // error TS2345: Property 'qty' is missing

console.log(seen);
Text
[ 'badge +2 A1', 'analytics A1', 'badge reset' ]

The type map makes every channel's payload checked at compile time. A component that adds an item emits an event, and neither the badge nor the analytics code is referenced from it.

Mediator versus observer

The two look similar, since both route messages between objects, and they solve different problems.

ObserverMediator
RelationshipOne subject, many subscribersMany peers through a hub
Who knows whomObservers know the subjectPeers know only the mediator
Coordination logicNone, the subject just notifiesLives in the mediator
Typical shapesubject.subscribe(fn)mediator.notify(sender, event)

If the central object only broadcasts, it is an event emitter and the observer pattern. If it makes decisions, such as "when the country changes, also update the state list", it is a mediator.

Testing

A mediator is a good test target, because it holds the rules and takes its collaborators as arguments. Register fake widgets that record calls, send events and assert on what the fakes received.

mediator.test.mjsJavaScript
import assert from "node:assert/strict";
import { test } from "node:test";

test("changing the country clears nothing but updates states", () => {
  const calls = [];
  const mediator = {
    widgets: {
      state: { setOptions: (o) => calls.push(["state", o]) },
      postcode: { setPattern: (p) => calls.push(["postcode", p?.source ?? null]) },
    },
    notify(sender, event, value) {
      if (sender === "country" && event === "changed") {
        this.widgets.state.setOptions(value === "US" ? ["CA", "NY"] : []);
        this.widgets.postcode.setPattern(value === "US" ? /^\d{5}$/ : null);
      }
    },
  };
  mediator.notify("country", "changed", "US");
  assert.deepEqual(calls, [["state", ["CA", "NY"]], ["postcode", "^\\d{5}$"]]);
});
Text
✔ changing the country clears nothing but updates states (0.9ms)
ℹ tests 1
ℹ pass 1
ℹ fail 0

The widgets themselves can be tested with a fake mediator that records notify calls. Each side is tested alone.

The main hazard: the god mediator

Because all coordination lands in one object, it tends to grow. A mediator with sixty rules touching twenty components is a tangle that has only moved. Keep it healthy by splitting along feature lines, one mediator per form or screen, and by leaving trivial interactions out of it: a button that only affects its own label does not need the mediator. If you cannot read the mediator in one sitting, split it.

Another trap is hiding the data flow. When components communicate only through events, finding what triggers a change means searching event names. Typed events, consistent naming and logging every message in development keep the flow traceable.

Where the advice stops

With two or three objects, direct references are clearer. The pattern pays when you have many peers that interact in changing ways, because the number of direct links grows quickly with each new participant. In front-end code, lifting shared state to a parent component or a store is often the idiomatic mediator, and a dedicated class is for cases where the coordination has real rules.

Mediators in front-end frameworks

Front-end code uses mediators constantly without the name. When two sibling components need to coordinate, the standard advice is to lift their shared state into the parent, which then passes values and callbacks down. The parent is the mediator: the children report events upward, and the parent decides what changes. When the parent grows heavy, the next step is a store or a context provider, which is the same idea with a bigger scope. A form library such as React Hook Form or Formik is a mediator for fields, holding values, validation and touched state so individual inputs stay ignorant of one another.

Knowing this helps you decide where coordination belongs. If the rules concern only a few nearby components, keep the mediator as a parent component or a custom hook. If many unrelated parts of the application need to react, a shared store or an event hub is the right size. If you are tempted to build a global mediator for everything, stop and split it by feature first.

Making the flow traceable

The main complaint about mediators is that the flow of control becomes indirect. A cheap defence is to log every message that passes through the mediator in development, with the sender, event name and payload. A one-line console.log inside notify, switched off in production, turns a mystery into a readable trace. Name events for what happened, such as country:changed, rather than for what you want done, and keep payloads small and typed. When a bug report says "the postcode field cleared by itself", the trace shows exactly which event caused it.

Share

Keep reading

Flat illustration of two options weighed side by side, with the JavaScript, Vite and Node.js logos.
Functions

Classes vs Factory Functions

Classes vs factory functions in JavaScript compared on private state, this, instanceof, inheritance, memory, JSON and testing, with exact output.

7 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.