Catalog My learning Blog
Micro-Frontends Course: React, Import Maps and Teams · Phase 3 · Lesson 8 · 6 min read

Micro-Frontend Communication with Custom Events

On this page
  1. Less talk is better
  2. Typed custom events
  3. Events are fire and forget, and that has a cost
  4. Use the URL for shareable state
  5. Why not a shared global store?
  6. Treat events like an API
  7. Check yourself

Less talk is better

Every message between micro-frontends is a dependency between teams. Before adding one, check whether a better boundary would remove the need (Day 2). Still, some communication is unavoidable. In the shop, clicking "Add" in the catalog must put an item in the cart, and the header must show the new count. That's three teams touching one user action.

There are four common channels, from most to least preferred:

  1. The URL, for state the user should be able to share or bookmark.
  2. Props from the shell, for settings the shell owns, like the locale or currency (Day 4).
  3. Browser events, for "something happened" notifications between peers.
  4. A backend, for anything that must survive a reload or be true across devices.

Typed custom events

The browser already has an event system. A CustomEvent dispatched on window can be heard by any micro-frontend, whatever its framework, and needs no shared library at run time. Wrap it in a few lines of types so names and payloads can't drift:

Shell
// @shop/contract: events are part of the public API between teams
export type ShopEvents = {
  'shop:item-added': { sku: string; title: string; quantity: number };
  'shop:cart-changed': { count: number };
};

export function emit<K extends keyof ShopEvents>(type: K, detail: ShopEvents[K]) {
  window.dispatchEvent(new CustomEvent(type, { detail }));
}

export function on<K extends keyof ShopEvents>(type: K, handler: (detail: ShopEvents[K]) => void) {
  const listener = (e: Event) => handler((e as CustomEvent<ShopEvents[K]>).detail);
  window.addEventListener(type, listener);
  return () => window.removeEventListener(type, listener);   // the unsubscribe function
}

Now the flow reads naturally:

JavaScript
// catalog: announce, don't command
<button onClick={() => emit('shop:item-added', { sku: p.sku, title: p.title, quantity: 1 })}>Add</button>

// cart: owns cart state, listens and announces the new count
on('shop:item-added', (item) => { addLine(item); emit('shop:cart-changed', { count: totalQuantity() }); });

// header: only displays
const off = on('shop:cart-changed', ({ count }) => { countEl.textContent = String(count); });

In the lab, three clicks in the catalog moved the header's count from 0 to 3, and the cart page listed "2 x Desk lamp, 1 x Coffee mug". The catalog doesn't know the cart exists. It announces a fact, and whoever cares reacts.

Events are fire and forget, and that has a cost

The lab also showed the weak spot. With the import map pointing the cart at a missing file, the catalog still said "Added Desk lamp", but the header count stayed at 0. The event went out and nobody was listening. Nothing failed loudly. The item was simply lost.

Ways to deal with it:

  • Make the owner listen early. The cart starts at boot with the shell, not when the cart page opens (Day 6), so it hears events on every page.
  • Let the owner confirm. The catalog shows "Added" only after it hears shop:cart-changed, not right after emitting. If no confirmation arrives within a second, it shows an error.
  • Move important state to the backend. For a real shop, adding to cart should call the cart service through the BFF (Day 11). The event then becomes a notification that the server state changed, not the only copy of the data.

Use the URL for shareable state

Filters, search terms, the selected tab, the current page of results: if a user might share the link or press back, the state belongs in the URL. /search?q=lamp&sort=price is state that every micro-frontend can read from location, that survives a reload, and that the back button restores for free. No event needed.

Why not a shared global store?

It's tempting to put one Redux or Zustand store in the shell and let every micro-frontend read and write it. It feels simple at first, but it couples everyone:

  • Every team depends on the store's shape, so changing it needs every team.
  • Teams must agree on the store library and its version.
  • Any team can change any other team's state, and debugging who did it is painful.

That's the coupling micro-frontends exist to remove. Keep state inside the team that owns it, and expose it through events, the URL or the backend.

Treat events like an API

Events are part of the contract between teams, so give them the same care as an HTTP API:

  • Namespace them (shop:), so they can't clash with third-party scripts.
  • Only add fields. Never rename or remove a field in place. For a breaking change, publish a new event name like shop:item-added.v2 alongside the old one for a while.
  • Keep payloads small and plain. Ids and simple values, never functions, DOM nodes or class instances.
  • Document each event: who emits it, who listens, and what the payload means.
  • Always unsubscribe in Unmount. The on helper returns the function to call.

For synchronizing across browser tabs, such as signing out everywhere, the BroadcastChannel API works the same way between tabs of the same origin.

TipLog every shop:* event in development with one window listener per event name. Seeing the sequence of events for a click explains most "why didn't the header update" bugs in seconds.

Check yourself

Emitting an event announces a fact without depending on the cart's code, its API or even its existence. The cart team can change how it stores lines, and new listeners can join later, without the catalog team changing anything. Calling a cart function would couple the two teams' releases.

Start the cart at boot so it always listens, have the catalog wait for a shop:cart-changed confirmation and show an error if none arrives, or keep the cart on the backend so events are only notifications.

It couples every team to one state shape and library version, and lets any team change another team's state, which brings back the coordination micro-frontends are meant to remove.

Treat it as a breaking API change. Keep emitting the old field, add a new event name such as shop:item-added.v2 with the new shape, move listeners over, and only then retire the old event. Renaming in place would silently break every team still reading quantity.

In the URL, for example /search?q=lamp&sort=price. State in the URL survives reloads, can be shared as a link, and is restored by the back button for free, and any micro-frontend can read it from location without an event.