Micro-Frontends & Module Federation Sandbox
Architect, simulate, and stress-test distributed web applications. Inspect shared singletons, simulate React 19 vs 18 version drift, evaluate Error Boundary resilience during CDN outages, and export copy-ready Webpack 5, Rspack, Vite 6, and Next.js production configurations.
Micro-Frontends & Module Federation Control Plane
Simulate dynamic container orchestration, singleton resolution, cross-boundary fault isolation, and multi-bundler generation.
Host and all remotes share a single verified React 19.0.0 singleton in __webpack_share_scopes__.default. Zero duplicate overhead, zero hook collisions.
Distributed Container Topology Graph
app-shell (Host Application)
Port 3000Root Router, Shared Scope Coordinator, Error Boundary Orchestrator
Navigation & Shell Global
:3001 • Team NavigationHeader, mega-menu, global notifications, and dynamic search bar with category filtering.
Product Catalog & Search
:3002 • Team CatalogProduct listing grid, dynamic facet filtering, stock indicators, and sorting controls.
Checkout & Payment Gateway
:3003 • Team CheckoutCart slide-over drawer, tax computation, multi-currency payment forms, and Stripe checkout elements.
User Identity & Profile
:3004 • Team AuthJWT session management, OAuth SSO badge, avatar dropdown, and permission gate components.
Container Node Inspector
index.html / main.tsxHost initializes __webpack_init_sharing__('default'). Remotes attach modules at runtime before rendering.
The Evolution of Micro-Frontends: From IFrames to Module Federation
As enterprise software organizations scale beyond hundreds of frontend engineers, the traditional monolithic Single-Page Application (SPA) becomes an organizational and operational bottleneck. In a monolithic frontend architecture, disparate cross-functional teams (e.g. Navigation, Search & Catalog, Checkout & Payments, Identity & Auth) commit into a single repository and share a unified build and deployment pipeline. A single syntax error, test failure, or breaking dependency upgrade in the Checkout team blocks deployment for the entire company. Furthermore, the compilation and bundle time grows quadratically with codebase size, resulting in CI/CD pipeline runs exceeding 45 to 60 minutes.
To decouple team release velocity, engineering leaders historically turned to several micro-frontend isolation patterns, each introducing significant trade-offs:
Run-Time IFrames
Offers absolute CSS, DOM, and JavaScript isolation. However, IFrames prevent responsive reflows, break accessibility, degrade search engine indexing, and cause severe memory bloating because every nested iframe downloads duplicate copies of React, Vue, CSS resets, and browser runtime runtimes.
Web Components (Custom Elements)
Provides W3C-standard component encapsulation via Shadow DOM. However, Web Components lack native shared dependency management. If ten micro-frontends are authored in React, each micro-frontend embeds its own 140KB React runtime inside its bundle, destroying page load performance and Core Web Vitals.
Module Federation
Pioneered in Webpack 5 and extended to Rspack, Vite, and Next.js. Allows independently compiled and deployed applications to dynamically share modules, components, and singletons at runtime in the browser without code duplication, iframe boundaries, or build-time coupling.
Under the Hood: Container Runtime Architecture & The Shared Scope
Module Federation is not a static packaging format; it is a distributed runtime protocol executed in browser memory. Every federated micro-frontend acts as either a Host (an application consuming remote modules), a Remote (an application exposing modules to consumers), or a Bi-directional Host/Remote (consuming and exposing modules simultaneously).
The execution lifecycle follows a rigorous multi-phase sequence:
- Remote Entry Discovery: When the Host shell launches, it fetches the lightweight manifest file (e.g.
http://localhost:3001/remoteEntry.js). This script attaches a global container object towindow[scope](such aswindow.team_nav). - Two-Phase Shared Scope Initialization: The Host invokes
__webpack_init_sharing__('default'). This constructs the global shared module registry located atwindow.__webpack_share_scopes__.default. In this phase, every container advertises the vendor libraries it contains, their SemVer versions, and their lazy factory functions. - Container Binding: The Host calls
window.team_nav.init(__webpack_share_scopes__.default). The remote container receives the Host's shared scope pointer. If the Host already provided a shared singleton (e.g. React 19.0.0), the remote container binds its internal imports to the Host's existing instance rather than fetching its own copy. - Dynamic Module Resolution: When the Host application renders
const GlobalHeader = React.lazy(() => import('team_nav/GlobalHeader')), the container executeswindow.team_nav.get('./GlobalHeader'), downloads only the specific asynchronous chunk containing the header code, and evaluates it using the negotiated shared scope dependencies.
Shared Singleton Resolution & The React Split-Brain Collision
In standard JavaScript libraries (such as Lodash, Day.js, or utility formatters), having two versions loaded in memory is harmless—each module executes pure functions in its own closure without side effects. However, for stateful UI runtimes like React, React-DOM, Vue, and Angular, running multiple instances in the same browser window creates catastrophic state corruption.
The Root Cause of React Hook Dispatcher Null Pointer Crashes
Inside the React core engine, hooks like useState(), useEffect(), and useMemo() do not store state directly. Instead, they forward their invocations to an internal global pointer: ReactCurrentDispatcher.current. When the Host application renders, its React runtime sets this pointer to its active fiber reconciler. If a Remote micro-frontend was bundled with its own unshared copy of React, the remote component invokes hooks against its own React module. Because that second instance was never activated by the Host's render loop, its internal dispatcher pointer remains null. The browser immediately crashes with:TypeError: Cannot read properties of null (reading 'useState').
To eliminate hook collisions, the Module Federation configuration must explicitly configure singleton resolution rules:
| Configuration Option | Type | Architectural Impact & Behavioral Guarantee |
|---|---|---|
| singleton: true | boolean | Guarantees that only one instance of the library is ever instantiated in __webpack_share_scopes__. Subsequent containers reuse the first instantiated instance. |
| strictVersion: true | boolean | Enforces zero tolerance for SemVer mismatches. If the loaded singleton version does not satisfy the container's requiredVersion range, Webpack throws a fatal runtime error to prevent subtle behavioral bugs. |
| requiredVersion: '^19.0.0' | string | Specifies the valid SemVer range acceptable for negotiation. Can automatically read from package.json via dependencies[key]. |
| eager: false | boolean | Critical for dynamic remotes. Setting eager: false allows the shared package to be loaded as an asynchronous chunk only when needed, avoiding bundle size bloating on initial load. |
Distributed Fault Isolation: Error Boundary Topologies & Graceful Degradation
In a distributed micro-frontend architecture, network calls are no longer restricted to backend REST or GraphQL APIs; the frontend application code itself is fetched across distributed CDN edge locations at runtime. A failure in an edge node hosting team_checkout (due to a 500 error, TLS certificate expiry, DNS resolution timeout, or deployment corrupting remoteEntry.js) must never take down the entire user journey.
Production micro-frontend architectures enforce a strict Compartmentalized Error Boundary Topology:
Antipattern: Unshielded Remote Imports
Directly rendering <RemoteCheckout /> without an Error Boundary means any script crash or network timeout bubbles directly to the root DOM container. The entire page blanks out, and the user cannot even navigate away or view previously loaded products.
Best Practice: Granular Boundary + SWR Cache
Each remote is wrapped in a dedicated <RemoteErrorBoundary> with React <Suspense>. If Checkout drops offline, the boundary catches the exception, displays a friendly offline card with cached cart items from localStorage, and offers a retry button without disturbing Navigation, Catalog, or Auth.
Multi-Bundler Ecosystem Comparison: Webpack 5 vs Rspack vs Vite 6 vs Next.js
| Bundler / Framework | Core Technology | Build Performance | SSR Support | Recommended Use Case |
|---|---|---|---|---|
| Webpack 5 | Node.js JavaScript AST Engine | Moderate (1x baseline) | Custom Node SSR setups | Legacy enterprise codebases with extensive Webpack plugin ecosystems |
| Rspack (ByteDance) | Native Rust Multi-Threaded Engine | Blazing Fast (10x-20x speedup) | Full Node & Edge SSR | High-scale production monorepos requiring instant HMR & drop-in Webpack parity |
| Vite 6 (@originjs) | ESBuild / Rollup ESM Map Plugin | Very Fast Dev Server | Experimental | Modern client-only SPAs with Vite development toolchains |
| Next.js (@nextjs-mf) | Webpack + Next Server Chunk Bridge | Standard Next.js Build | Native Server-Side Hydration | SEO-critical e-commerce platforms requiring server-rendered remote components |
Cross-Micro-Frontend Communication & Shared State Strategies
When independent teams build components that share a single page (e.g. Catalog adding an item that must update Cart in the Header), choosing the appropriate communication channel is vital to avoid tight coupling:
Custom DOM Events
window.dispatchEvent(new CustomEvent('cart:add', { detail: item })). Completely decoupled, framework-agnostic, and zero runtime overhead. Ideal for fire-and-forget notifications across distinct frameworks.
Shared Singleton Store (Zustand)
By marking zustand as singleton: true in ModuleFederationPlugin, store closures are shared across all remotes. Remotes import useCartStore() with full TypeScript autocomplete and reactive rendering.
URL & Browser History State
Filter facets, search queries, pagination, and modal dialog states should live directly in URL search params (?category=tools&page=2). This enables deep linking, browser back/forward buttons, and seamless bookmarking.
Micro-Frontends & Module Federation Engineering FAQs
Why does React throw 'Cannot read properties of null (reading useState)' when shared singleton is misconfigured?
React hook execution depends on an internal mutable global pointer: ReactCurrentDispatcher.current. When a component calls useState, useEffect, or useContext, it accesses this dispatcher. If two distinct instances of the React library bundle are loaded into the browser runtime simultaneously (which occurs when singleton is set to false or when version negotiation fails to unify instances), a remote component running on React instance B that is mounted inside a host component running on React instance A attempts to access the dispatcher of instance A. Because instance B's dispatcher was never initialized by instance A's render loop, ReactCurrentDispatcher.current is null, triggering an unrecoverable runtime crash. Enforcing singleton: true in ModuleFederationPlugin ensures that exactly one instance of React is instantiated in __webpack_share_scopes__.default, regardless of how many remotes are mounted.
What is the difference between strictVersion: true and strictVersion: false in Module Federation?
The strictVersion configuration flag controls how the Module Federation container handles SemVer mismatches during shared scope resolution. When strictVersion is true, if a remote specifies requiredVersion: '^19.0.0' and the host or loaded shared scope provides React 18.2.0, Webpack immediately throws a fatal runtime exception: 'Shared module react has no version matching ^19.0.0 in shared scope default', halting execution unless caught by an ErrorBoundary. When strictVersion is false, Webpack logs a console warning but executes a fallback negotiation algorithm, selecting the highest compatible SemVer version available across all loaded containers to keep the application running.
How does the two-phase bootstrapping mechanism (__webpack_init_sharing__) prevent race conditions?
In Module Federation, remote containers and host shells must establish a synchronized shared module registry before any application code attempts to evaluate or render components. Two-phase bootstrapping solves this: in Phase 1 (__webpack_init_sharing__('default')), each container registers its own declared shared libraries, versions, and factory functions into a global memory table on window.__webpack_share_scopes__.default. In Phase 2 (container.init(__webpack_share_scopes__.default)), the container is bound to that unified scope. This ensures that when container.get('./Component') is invoked, the remote code resolves vendor packages from the shared scope rather than bundling duplicate local copies. To enable this asynchronous handshake, host application entry points must always use an async import boundary (import('./bootstrap')) rather than importing React directly in index.ts.
Why are granular Error Boundaries mandatory when composing independent remote micro-frontends?
Unlike a monolithic application where all scripts are packaged and deployed simultaneously, micro-frontends load independent bundles across diverse CDN domains, edge servers, or network routes. If a team deploys a breaking change, if an edge CDN returns an HTTP 500 error, or if a user suffers a transient timeout while fetching remoteEntry.js, an unhandled script error or module rejection will bubble up the React fiber tree. Without localized Error Boundaries, a failure in a non-critical micro-frontend (such as a marketing banner, comments widget, or recommendation drawer) will crash the entire root React application, producing a total White Screen of Death (WSOD). Wrapping every federated remote import in a dedicated RemoteErrorBoundary isolates failures to that specific component box, enabling graceful fallback UI and preserving core navigation, catalog, and checkout workflows.
How does Rspack Module Federation compare to Webpack 5 in enterprise continuous integration?
Rspack is a Rust-based web bundler engineered for high-performance enterprise applications, offering full drop-in compatibility with Webpack's ModuleFederationPlugin API via @rspack/core. While Webpack 5 evaluates ASTs and federation chunks using Node.js JavaScript threads, Rspack executes dependency parsing, chunk splitting, and module federation container assembly in native compiled Rust threads. In large enterprise micro-frontend monorepos containing dozens of remotes, switching from Webpack 5 to Rspack commonly yields a 10x to 20x improvement in cold build times and near-instantaneous Hot Module Replacement (HMR), drastically reducing developer feedback loops and CI/CD deployment pipeline duration while emitting fully compatible remoteEntry.js bundles.
What are the trade-offs between dynamic manifest discovery (mf-manifest.json) versus hardcoded remoteEntry.js URLs?
Hardcoding static remote URLs (e.g. remotes: { team_checkout: 'team_checkout@https://cdn.example.com/checkout/remoteEntry.js' }) creates tight compile-time coupling between the host and remote hosting infrastructure. If the checkout team updates their CDN domain, implements canary blue/green deployments, or alters asset paths, the host application must be recompiled and redeployed. Dynamic manifest discovery (introduced in modern Module Federation v2 via mf-manifest.json or runtime container resolvers) allows the host to fetch an environment-driven JSON manifest at runtime. The host inspects current remote URLs, asset hashes, and type definitions dynamically, enabling continuous zero-downtime micro-frontend deployments without host rebuilds.