JavaScript and React course ยท Module 10: React Ecosystem and Future
Micro-frontends with React - Scalable Architecture
In this lesson4
The fleet is growing: five teams work on one application, and every deployment needs everyone's approval, because the code is a single monolith. A fix in the cart waits for the product catalog tests, and a version conflict in one library blocks the whole crew. Micro-frontends are an architectural pattern that brings the idea of microservices to the frontend: independent teams develop, deploy and scale separate parts of the application.
Introduction to Micro-frontends
What Are Micro-frontends?
Micro-frontends are a technique for splitting a monolithic frontend application into smaller, independent applications (MFEs), each with its own repository and deployment process. The user sees a single page, because a shell application puts them together. You read the architecture from the outside in: the shell, inside it the router, the router loads the remote MFEs, and each MFE renders its own internal components. It is like a space station assembled from modules built by different agencies, joined by a shared dock.
Module Federation (Webpack 5)
The most popular way to connect MFEs is Module Federation, built into webpack 5 as require('webpack').container.ModuleFederationPlugin. It lets an application load, at runtime, modules exposed by other applications and share dependencies, e.g. React. This is what the shell configuration looks like:
// webpack.config.js - Shell Application
const { ModuleFederationPlugin } = require('webpack').container;
module.exports = {
mode: 'development',
devServer: {
port: 3000,
},
plugins: [
new ModuleFederationPlugin({
name: 'shell',
remotes: {
products: 'products@http://localhost:3001/remoteEntry.js',
cart: 'cart@http://localhost:3002/remoteEntry.js',
user: 'user@http://localhost:3003/remoteEntry.js',
},
shared: {
react: { singleton: true, eager: true },
'react-dom': { singleton: true, eager: true },
'@shared/ui-kit': { singleton: true },
'@shared/utils': { singleton: true },
},
}),
],
};remotes maps names to the addresses of the remoteEntry.js files that each MFE publishes. shared with singleton: true makes sure only one copy of React runs in the browser, because libraries with global state handle duplicates badly, and eager: true includes them in the initial bundle. For extras, such as a manifest and runtime plugins, reach for Module Federation 2.0 from the @module-federation/enhanced package.
Implementing the Shell Application
The shell loads MFEs lazily with lazy, just like regular components. The products/ProductsApp path points to a module from the remote named products:
// src/App.jsx - Shell Application
import React, { Suspense, lazy } from 'react';
import { BrowserRouter, Routes, Route } from 'react-router-dom';
import ErrorBoundary from './components/ErrorBoundary';
import Layout from './components/Layout';
// Lazy loading Micro-frontends
const ProductsApp = lazy(() => import('products/ProductsApp'));
const CartApp = lazy(() => import('cart/CartApp'));
const UserApp = lazy(() => import('user/UserApp'));
// Local components
const HomePage = lazy(() => import('./pages/HomePage'));
function App() {
return (
<ErrorBoundary>
<BrowserRouter>
<Layout>
<Suspense fallback={<div>Loading...</div>}>
<Routes>
<Route path="/" element={<HomePage />} />
{/* Products Micro-frontend */}
<Route
path="/products/*"
element={
<ErrorBoundary fallback={<div>Products unavailable</div>}>
<ProductsApp />
</ErrorBoundary>
}
/>
{/* Cart Micro-frontend */}
<Route
path="/cart/*"
element={
<ErrorBoundary fallback={<div>Cart unavailable</div>}>
<CartApp />
</ErrorBoundary>
}
/>
{/* User Micro-frontend */}
<Route
path="/user/*"
element={
<ErrorBoundary fallback={<div>User profile unavailable</div>}>
<UserApp />
</ErrorBoundary>
}
/>
</Routes>
</Suspense>
</Layout>
</BrowserRouter>
</ErrorBoundary>
);
}
export default App;Each MFE has its own ErrorBoundary, so a cart failure will not take down the catalog, and Suspense shows a loading state before the remote code arrives over the network. Paths ending in /* hand the rest of the address to the router inside the MFE.
Communication Between Micro-frontends
Event-driven Architecture
Micro-frontends should not import each other, because then a monolith forms again. Most often they talk through events: an in-memory Event Bus and native CustomEvent on the window object:
// shared/eventBus.js
class EventBus {
constructor() {
this.events = {};
}
subscribe(eventName, callback) {
if (!this.events[eventName]) {
this.events[eventName] = [];
}
this.events[eventName].push(callback);
// Return unsubscribe function
return () => {
this.events[eventName] = this.events[eventName].filter(
cb => cb !== callback
);
};
}
emit(eventName, data) {
if (this.events[eventName]) {
this.events[eventName].forEach(callback => callback(data));
}
// Also emit as CustomEvent for cross-MFE communication
window.dispatchEvent(new CustomEvent(`mfe:${eventName}`, {
detail: data
}));
}
}
export const eventBus = new EventBus();subscribe returns an unsubscribe function, so a component will detach itself in the effect's cleanup. emit also dispatches a CustomEvent with the mfe: prefix, which every MFE will hear, even one written in a different framework.
Shared State Management
Some data, like the logged-in user or the cart, has to be shared. A store from zustand/vanilla works without React, so it can live in a shared module:
// shared/stateManager.js
import { createStore } from 'zustand/vanilla';
// Global store accessible across MFEs
const globalStore = createStore((set, get) => ({
// User state
user: null,
isAuthenticated: false,
// Cart state
cartItems: [],
cartTotal: 0,
// Actions
setUser: (user) => set({ user, isAuthenticated: !!user }),
addToCart: (product) => set(state => {
const existingItem = state.cartItems.find(item => item.id === product.id);
let newItems;
if (existingItem) {
newItems = state.cartItems.map(item =>
item.id === product.id
? { ...item, quantity: item.quantity + 1 }
: item
);
} else {
newItems = [...state.cartItems, { ...product, quantity: 1 }];
}
const newTotal = newItems.reduce((sum, item) =>
sum + (item.price * item.quantity), 0
);
return { cartItems: newItems, cartTotal: newTotal };
}),
removeFromCart: (productId) => set(state => {
const newItems = state.cartItems.filter(item => item.id !== productId);
const newTotal = newItems.reduce((sum, item) =>
sum + (item.price * item.quantity), 0
);
return { cartItems: newItems, cartTotal: newTotal };
}),
}));addToCart increases quantity when the product is already in the cart, and cartTotal is recalculated on every change. A shared store is still a dependency between teams, though, so I advise you to keep only truly global data in it, and send everything else through events.
Testing Micro-frontends
An integration test checks whether the shell loads the MFE correctly, and the remote module is replaced by a mock from jest.mock:
// __tests__/integration/mfe-integration.test.jsx
import { render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import App from '../App';
// Mock of the remote MFE: the module is not on disk, hence virtual: true
jest.mock('products/ProductsApp', () => {
return function MockProductsApp() {
return <div data-testid="products-mfe">Products MFE Loaded</div>;
};
}, { virtual: true });
describe('MFE Integration', () => {
test('loads products MFE when navigating to /products', async () => {
const user = userEvent.setup();
// App renders BrowserRouter itself, so we do not wrap it in a second router
render(<App />);
// Navigate to products
await user.click(screen.getByRole('link', { name: /products/i }));
// Verify MFE is loaded
await waitFor(() => {
expect(screen.getByTestId('products-mfe')).toBeInTheDocument();
});
});
});The test clicks a link, and waitFor waits until the lazily loaded mock appears in the DOM. The remote module is not on disk, which is why jest.mock gets the { virtual: true } option (instead, you can add an entry in moduleNameMapper). App renders BrowserRouter itself, so the test renders it without a second router, because React Router would report a nesting error.
When Is It Worth It?
Micro-frontends offer powerful ways to scale React applications in large organizations, but they require a well-thought-out architecture and managing complexity: separate pipelines, event contracts and keeping an eye on the versions of shared dependencies. For a single team it is usually overkill, because a well-divided monolith will be simpler. In the exercise you will build the orchestration of several MFEs with shared dependencies and event-based communication.
Remember: a micro-frontend is a station module from another agency - it docks to the shared shell, but launches on its own schedule. In the example below, switch a section in the navigation or turn off a system: the communicator receives an event from the Event Bus, and the shell hears a CustomEvent on the window object.
Code for this lesson: App.jsx
import { useCallback, useEffect, useState } from 'react';
// === Micro-frontends - a simulation in a single file ===
// Each MF module pretends to be a separate application with its own state. The modules
// do not import each other, they talk through the Event Bus, as in the lesson.
class EventBus {
constructor() {
this.events = {};
}
subscribe(eventName, callback) {
if (!this.events[eventName]) this.events[eventName] = [];
this.events[eventName].push(callback);
// Unsubscribe function for the effect cleanup
return () => {
this.events[eventName] = this.events[eventName].filter(cb => cb !== callback);
};
}
emit(eventName, data) {
(this.events[eventName] || []).forEach(callback => callback(data));
// A CustomEvent with the mfe: prefix is heard even by an MF written in another framework
window.dispatchEvent(new CustomEvent('mfe:' + eventName, { detail: data }));
}
}
const eventBus = new EventBus();
// Hook for listening to events from other modules
function useEventBus(eventName, handler) {
useEffect(() => eventBus.subscribe(eventName, handler), [eventName, handler]);
}
// MF-1: Space station navigation
function NavigationModule() {
const [activeSection, setActiveSection] = useState('panel');
const sections = [
{ id: 'panel', label: 'Main panel' },
{ id: 'crew', label: 'Crew' },
{ id: 'systems', label: 'Systems' },
{ id: 'cargo', label: 'Cargo hold' },
];
const navigate = section => {
setActiveSection(section.id);
eventBus.emit('navigation:change', { label: section.label });
};
return (
<div style={{ ...styles.module, border: '2px solid #00d4ff' }}>
<div style={styles.moduleHeader}>
<h3 style={{ ...styles.moduleTitle, color: '#00d4ff' }}>MF-1: Navigation</h3>
<span style={styles.port}>port 3001</span>
</div>
<div style={{ display: 'flex', gap: '6px', flexWrap: 'wrap' }}>
{sections.map(section => (
<button
key={section.id}
onClick={() => navigate(section)}
style={{ ...styles.navButton, ...(activeSection === section.id ? styles.navActive : null) }}
>
{section.label}
</button>
))}
</div>
</div>
);
}
// MF-2: System status panel
function SystemStatusModule() {
const [systems, setSystems] = useState([
{ name: 'Warp drive', online: true, health: 95 },
{ name: 'Shields', online: true, health: 88 },
{ name: 'Communications', online: true, health: 100 },
{ name: 'Life support', online: true, health: 92 },
]);
const toggleSystem = index => {
const system = systems[index];
const online = !system.online;
// New state first, then the event - the setState updater stays pure
setSystems(prev => prev.map((s, i) => (i === index ? { ...s, online } : s)));
eventBus.emit('status:update', { system: system.name, online });
};
return (
<div style={{ ...styles.module, border: '2px solid #00ff88' }}>
<div style={styles.moduleHeader}>
<h3 style={{ ...styles.moduleTitle, color: '#00ff88' }}>MF-2: System status</h3>
<span style={styles.port}>port 3002</span>
</div>
{systems.map((system, i) => (
<button key={system.name} onClick={() => toggleSystem(i)} style={styles.systemRow}>
<span style={{ ...styles.dot, background: system.online ? '#00ff88' : '#ff6b6b' }} />
<span style={{ flex: 1, textAlign: 'left' }}>{system.name}</span>
<span style={{ color: '#778da9' }}>{system.online ? system.health + '%' : 'offline'}</span>
</button>
))}
</div>
);
}
// MF-3: Crew communicator - listens to events from MF-1 and MF-2
function CrewChatModule() {
const [messages, setMessages] = useState([
{ from: 'Commander Nova', text: 'Systems operational, ready to jump.', type: 'crew' },
{ from: 'Astro', text: 'Warp drive charged.', type: 'crew' },
]);
const [input, setInput] = useState('');
// Stable functions (useCallback), so we do not resubscribe to the bus on every render
const onStatusUpdate = useCallback(data => {
setMessages(prev => [...prev, { from: 'System', text: data.system + (data.online ? ' online' : ' offline'), type: 'system' }]);
}, []);
const onNavigationChange = useCallback(data => {
setMessages(prev => [...prev, { from: 'Navigation', text: 'Moved to section: ' + data.label, type: 'system' }]);
}, []);
useEventBus('status:update', onStatusUpdate);
useEventBus('navigation:change', onNavigationChange);
const send = () => {
if (!input.trim()) return;
setMessages(prev => [...prev, { from: 'You', text: input, type: 'crew' }]);
setInput('');
};
return (
<div style={{ ...styles.module, border: '2px solid #ffaa00' }}>
<div style={styles.moduleHeader}>
<h3 style={{ ...styles.moduleTitle, color: '#ffaa00' }}>MF-3: Communicator</h3>
<span style={styles.port}>port 3003</span>
</div>
<div style={styles.chat}>
{messages.map((msg, i) => (
<div key={i} style={{ marginBottom: '4px' }}>
<strong style={{ color: msg.type === 'system' ? '#ff6b6b' : '#00d4ff' }}>{msg.from}: </strong>
<span>{msg.text}</span>
</div>
))}
</div>
<div style={{ display: 'flex', gap: '6px' }}>
<input
value={input}
onChange={e => setInput(e.target.value)}
onKeyDown={e => e.key === 'Enter' && send()}
placeholder="Message..."
style={styles.input}
/>
<button onClick={send} style={styles.sendButton}>Send</button>
</div>
</div>
);
}
// Shell Application - puts the modules together and listens to CustomEvent on window
export default function App() {
const [currentSection, setCurrentSection] = useState('Main panel');
useEffect(() => {
const onNavigation = event => setCurrentSection(event.detail.label);
window.addEventListener('mfe:navigation:change', onNavigation);
return () => window.removeEventListener('mfe:navigation:change', onNavigation);
}, []);
return (
<div style={styles.page}>
<div style={{ maxWidth: '620px', margin: '0 auto' }}>
<h1 style={styles.title}>Shell Application - Space Station</h1>
<p style={styles.subtitle}>
The shell (port 3000) loads three independent modules. Active section according to the event from MF-1: <strong style={{ color: '#00d4ff' }}>{currentSection}</strong>
</p>
<div style={{ display: 'grid', gap: '12px' }}>
<NavigationModule />
<SystemStatusModule />
<CrewChatModule />
</div>
<div style={styles.patterns}>
<h4 style={{ margin: '0 0 8px', color: '#778da9' }}>Key micro-frontend patterns:</h4>
<ul style={{ margin: 0, paddingLeft: '20px', lineHeight: 1.8 }}>
<li><strong style={{ color: '#00d4ff' }}>Module Federation</strong> - loading modules of other applications at runtime</li>
<li><strong style={{ color: '#00ff88' }}>Event Bus and CustomEvent</strong> - loosely coupled communication</li>
<li><strong style={{ color: '#ffaa00' }}>Independent deployments</strong> - each team deploys its module separately</li>
<li><strong style={{ color: '#ff6b6b' }}>Own state</strong> - a shared store only for truly global data</li>
</ul>
</div>
</div>
</div>
);
}
const styles = {
page: { background: '#0d1b2a', minHeight: '100vh', padding: '20px', color: '#e0e1dd', fontFamily: 'system-ui, sans-serif', fontSize: '13px' },
title: { color: '#00d4ff', textAlign: 'center', fontSize: '19px', margin: '0 0 6px' },
subtitle: { color: '#778da9', textAlign: 'center', margin: '0 0 16px' },
module: { background: '#1b2838', padding: '14px', borderRadius: '12px' },
moduleHeader: { display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '10px' },
moduleTitle: { margin: 0, fontSize: '14px' },
port: { fontSize: '10px', color: '#778da9', border: '1px solid #415a77', padding: '2px 8px', borderRadius: '4px' },
navButton: { padding: '6px 12px', borderRadius: '6px', border: '1px solid #415a77', background: 'transparent', color: '#778da9', cursor: 'pointer' },
navActive: { border: '1px solid #00d4ff', background: 'rgba(0,212,255,0.15)', color: '#00d4ff' },
systemRow: { display: 'flex', alignItems: 'center', gap: '10px', width: '100%', background: '#0d1b2a', color: '#e0e1dd', border: 'none', padding: '8px 12px', borderRadius: '8px', cursor: 'pointer', marginBottom: '6px', fontSize: '13px' },
dot: { width: '8px', height: '8px', borderRadius: '50%', flexShrink: 0 },
chat: { background: '#0d1b2a', padding: '10px', borderRadius: '8px', maxHeight: '140px', overflowY: 'auto', marginBottom: '8px' },
input: { flex: 1, padding: '6px 10px', borderRadius: '6px', border: '1px solid #415a77', background: '#0d1b2a', color: '#e0e1dd' },
sendButton: { padding: '6px 12px', borderRadius: '6px', border: 'none', background: '#ffaa00', color: '#0d1b2a', fontWeight: 'bold', cursor: 'pointer' },
patterns: { marginTop: '16px', background: '#1b2838', padding: '12px', borderRadius: '8px', border: '1px solid #415a77' },
};Docs entries used in this lesson
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. What is Module Federation used for in the context of micro-frontends?
2. Which communication pattern is most commonly used between micro-frontends?
Hands-on tasks in the game
- Vertical ordering
Order the elements of micro-frontends architecture from outermost to innermost:
- Code editor
Connect two independent micro-frontends with an event bus: the parts catalogue (team Astro MFE) sends the cargo:add event, and the cargo hold (team Commander Nova MFE) receives it. ___BLANK1___: the function returned by on() removes only this one subscription (use the off method with the same event and handler). ___BLANK2___: emit calls every stored function with the event data (payload). ___BLANK3___: the effect in CargoHold returns a function that removes the subscription, so that no orphaned listener stays after hiding the cargo hold (and the double effect in StrictMode does not add parts twice).