Micro-Frontend Communication
Problem
Independently deployed micro-frontends need to share state and coordinate behavior, but they can’t import each other’s modules. One team’s shopping cart needs to notify another team’s header when items are added. Global variables create tight coupling and version conflicts. Without clear communication protocols, micro-frontends become isolated silos.
Solution
Enable independent micro-frontends to communicate through shared event buses or custom elements. This allows coordination while maintaining loose coupling between teams and deployments.
Example
This example shows two independent micro-frontends communicating via custom events on the window object, allowing them to coordinate without direct imports or dependencies.
// Micro-frontend A (shopping cart)
// Dispatches custom event when cart changes
window.dispatchEvent(new CustomEvent('cart:updated', {
detail: { itemCount: 5 }
}));
// Micro-frontend B (header badge)
// Listens for cart updates from other micro-frontends
window.addEventListener('cart:updated', (e) => {
// Update badge with new item count from event detail
updateBadge(e.detail.itemCount);
});
Benefits
- Enables coordination between independent micro-frontends without tight coupling.
- Allows teams to deploy and update their frontends independently.
- Maintains loose coupling by using standardized communication protocols.
- Prevents version conflicts and breaking changes across micro-frontend boundaries.
Tradeoffs
- Adds complexity with event naming conventions and coordination protocols.
- Can create debugging challenges when tracking communication across frontends.
- May lead to tight coupling if event contracts aren’t carefully designed.
- Requires documentation and governance to prevent protocol fragmentation.