A Typed Event Bus for Microfrontends
Keeping cross-app messages versioned and discoverable without turning the event bus into a global wild west.
- Engineering
- TypeScript
- Architecture
- Events
Microfrontends need to talk, but an untyped emit('thing-happened', payload) gives every team permission to invent a new contract. A typed bus makes the message catalogue a compile-time artifact: rename an event and every publisher fails to build.
Define one map of events
Put the event names and payloads in a shared package. The bus API derives its signatures from that map, so autocomplete shows the allowed topics and TypeScript rejects a payload that does not match.
export interface AppEvents {
'cart:item-added': { sku: string; quantity: number };
'auth:session-expired': { reason: 'idle' | 'revoked' };
}
type Handler<K extends keyof AppEvents> = (payload: AppEvents[K]) => void;
export function on<K extends keyof AppEvents>(topic: K, handler: Handler<K>): () => void {
return subscribe(topic, handler as Handler<keyof AppEvents>);
}
Version the contract, not every event
Add a version field to the envelope and keep two versions alive during migration. Consumers ignore versions they do not understand; publishers can ship before every consumer has deployed. Retire old versions only after telemetry shows no traffic.
Scope the bus
A single global channel lets a debug listener (or a buggy app) observe everything. Give each app its own namespace and expose an explicit bridge for the handful of cross-app events. Fewer visible topics make ownership obvious.
Keep the bus boring
No retries, no persistence, no middleware chain. If a message must survive a reload, use a queue. An event bus that tries to be both a transport and a database becomes the most fragile part of the architecture.