DEV Community

Cover image for Micro-Frontends with Module Federation: From Zero to Multi-Team Deploy
Mango Developer
Mango Developer

Posted on Originally published at mangodeveloper.com

Micro-Frontends with Module Federation: From Zero to Multi-Team Deploy

The first time I tried to split a React monolith into micro-frontends, I made every mistake in the book. I started with iframes (terrible UX), switched to runtime script injection (race conditions), tried single-spa (powerful but heavy), and finally landed on Webpack Module Federation. By then I'd wasted three weeks. This article is what I wish I'd read first.

Micro-frontends get a bad reputation because most teams reach for them to solve organizational problems they don't actually have. "Our frontend is too big" is a symptom; "five teams step on each other in the same codebase" is the actual problem. If you don't have the latter, you don't need micro-frontends. You need a refactor and maybe a stricter ESLint config.

But if you do have multiple teams, an actual product surface that's split along team boundaries, and a release cadence that's bottlenecked by one monolithic build-micro-frontends are the cleanest answer we have right now. Module Federation, which shipped in Webpack 5, made this practical without iframes or bespoke script loaders. Let's build it properly.

Why Micro-Frontends (and Why Not)

Let's be honest about when this pattern pays off.

Problem Micro-frontend helps? Why
Monolith is slow to build Yes Each MFE builds independently
5+ teams editing same codebase Yes Teams own their own MFE end-to-end
Mixed frameworks (React + Vue legacy) Yes Each MFE can use what it wants
Different release cadences per team Yes Deploy independently
Single team, <50k LOC No Refactor and add boundaries
Performance is your only concern No Code splitting + lazy loading is enough
You want to "be like Netflix" No Don't cargo-cult

The cost is real. You give up shared type safety across MFEs. You add a build pipeline per MFE. You introduce runtime integration risk. You need a contract system (typically TypeScript types or JSON schemas) that's less ergonomic than a single codebase. If you can't articulate the organizational benefit in one sentence, don't do it.

The one-sentence version I use: "Team A's release shouldn't be blocked by Team B's deploy, and vice versa." If that's not your problem, micro-frontends are overkill.

Approaches Compared

Approach Isolation Shared state Complexity Performance
Iframes Complete Hard Low Poor (each is a full page)
Server-side composition (SSR includes) None Easy Medium Good
Build-time NPM packages None Easy Low Best (bundled)
Single-spa (runtime) Medium Medium High Medium
Webpack Module Federation Medium Medium Medium Good

Module Federation wins for most new projects because it's runtime composition (so teams deploy independently) without the iframe tax, and it's built into Webpack 5 (and now also supported by Vite via vite-plugin-federation). Single-spa is more flexible but requires more boilerplate. Iframes are still the answer for true third-party isolation (e.g., embedding an untrusted app), but they're awful for your own product.

Prerequisites

  • Node.js 20 LTS. Module Federation works on older versions, but the tooling around it has moved on.
  • Webpack 5 (we'll use it directly) or Vite + vite-plugin-federation.
  • React 18 (the patterns translate to Vue or Solid, but the code here is React).
  • A place to host each MFE's built assets. Static file hosting (S3 + CloudFront, Cloudflare R2, Vercel) is fine.
  • A basic understanding of Webpack config. If you've never written a webpack.config.js, spend an afternoon on the Webpack docs first.

I'll use the host/shell + remote pattern: one "shell" app that owns the page chrome (header, nav, routing) and N "remote" apps that each own a section of the product.

Project Layout

CodeCopy

Enter fullscreen mode Exit fullscreen mode

mfe-example/
shell/ # the host app
src/
App.tsx
bootstrap.tsx # dynamic import entry (required by MF)
router.tsx
webpack.config.js
package.json
remote-catalog/ # team A's MFE
src/
Catalog.tsx
bootstrap.tsx
webpack.config.js
package.json
remote-checkout/ # team B's MFE
src/
Checkout.tsx
bootstrap.tsx
webpack.config.js
package.json
shared/
types/ # shared TypeScript types
events.d.ts
package.json
contracts/
api-schema.json

Enter fullscreen mode Exit fullscreen mode

The shared/types package is important. Without a shared contract package, your MFEs will drift. Treat it like a published library-version it, change it deliberately.

The Shell (Host) App

Here's the trick to Module Federation that took me embarrassingly long to internalize: the entry file can't import the app directly. It has to dynamically import it. This is because the federated remotes need to be available before your app code runs, and the only way to ensure that is to defer the app's execution.

TypeScriptCopy

Enter fullscreen mode Exit fullscreen mode


typescript
// shell/src/index.ts
import("./bootstrap");

Enter fullscreen mode Exit fullscreen mode


plaintext

TypeScriptCopy

Enter fullscreen mode Exit fullscreen mode


tsx
// shell/src/bootstrap.tsx
import React from "react";
import { createRoot } from "react-dom/client";
import App from "./App";

const root = createRoot(document.getElementById("root")!);
root.render();

Enter fullscreen mode Exit fullscreen mode


plaintext

TypeScriptCopy

Enter fullscreen mode Exit fullscreen mode


tsx
// shell/src/App.tsx
import React, { Suspense } from "react";
import { BrowserRouter, Routes, Route, Link } from "react-router-dom";

const Catalog = React.lazy(() => import("remote-catalog/Catalog"));
const Checkout = React.lazy(() => import("remote-checkout/Checkout"));

function Loading() {
return

Loading…;
}

export default function App() {
return (


Home | Catalog |{" "}
Checkout



}>
} />
}>
} />
Home} />



);
}
Enter fullscreen mode Exit fullscreen mode


plaintext

The import("remote-catalog/Catalog") syntax looks like a normal dynamic import, but remote-catalog isn't a node_modules package. It's a federated remote that Webpack resolves at runtime. We declare it in the Webpack config.

JavaScriptCopy

Enter fullscreen mode Exit fullscreen mode


javascript
// shell/webpack.config.js
const { ModuleFederationPlugin } = require("webpack").container;
const deps = require("./package.json").dependencies;
const HtmlWebpackPlugin = require("html-webpack-plugin");
const path = require("path");

module.exports = {
mode: "development",
entry: "./src/index.ts",
output: {
publicPath: "auto", // critical for MF
},
resolve: {
extensions: [".ts", ".tsx", ".js"],
},
module: {
rules: [
{ test: /.tsx?$/, loader: "ts-loader", exclude: /node_modules/ },
],
},
plugins: [
new ModuleFederationPlugin({
name: "shell",
remotes: {
"remote-catalog": "remote_catalog@http://localhost:3001/remoteEntry.js",
"remote-checkout": "remote_checkout@http://localhost:3002/remoteEntry.js",
},
shared: {
react: { singleton: true, requiredVersion: deps.react },
"react-dom": { singleton: true, requiredVersion: deps["react-dom"] },
"react-router-dom": {
singleton: true,
requiredVersion: deps["react-router-dom"],
},
},
}),
new HtmlWebpackPlugin({ template: "./public/index.html" }),
],
devServer: {
port: 3000,
historyApiFallback: true,
},
};

Enter fullscreen mode Exit fullscreen mode


markdown

The interesting parts:

  • publicPath: "auto". Without this, the remote's chunks won't load correctly. It tells Webpack to figure out where the bundle is being served from at runtime. Always use this.
  • remotes map. Each entry is localName: globalName@url. The global name (remote_catalog) is the global variable the remote's remoteEntry.js exposes. They have to match across host and remote configs.
  • shared with singleton: true for React. This is non-negotiable. React's hooks break if you load two copies. Singleton forces everyone to share one instance of React.

The Remote (Catalog) App

TypeScriptCopy

Enter fullscreen mode Exit fullscreen mode


typescript
// remote-catalog/src/index.ts
import("./bootstrap");

Enter fullscreen mode Exit fullscreen mode


plaintext

TypeScriptCopy

Enter fullscreen mode Exit fullscreen mode


tsx
// remote-catalog/src/bootstrap.tsx
import React from "react";
import { createRoot } from "react-dom/client";

// Only used for standalone dev; in production, this file is loaded by the shell.
import Catalog from "./Catalog";

const root = createRoot(document.getElementById("root")!);
root.render();

Enter fullscreen mode Exit fullscreen mode


plaintext

TypeScriptCopy

Enter fullscreen mode Exit fullscreen mode


tsx
// remote-catalog/src/Catalog.tsx
import React, { useEffect, useState } from "react";

type Product = { id: string; name: string; price: number };

export default function Catalog() {
const [products, setProducts] = useState([]);

useEffect(() => {
fetch("/api/products")
.then((r) => r.json())
.then(setProducts)
.catch((e) => console.error("Catalog fetch failed", e));
}, []);

return (


Catalog


    {products.map((p) => (
  • {p.name} - ${p.price}
  • ))}


);
}
Enter fullscreen mode Exit fullscreen mode


plaintext

JavaScriptCopy

Enter fullscreen mode Exit fullscreen mode


javascript
// remote-catalog/webpack.config.js
const { ModuleFederationPlugin } = require("webpack").container;
const HtmlWebpackPlugin = require("html-webpack-plugin");
const deps = require("./package.json").dependencies;

module.exports = {
mode: "development",
entry: "./src/index.ts",
output: { publicPath: "auto" },
resolve: { extensions: [".ts", ".tsx", ".js"] },
module: {
rules: [
{ test: /.tsx?$/, loader: "ts-loader", exclude: /node_modules/ },
],
},
plugins: [
new ModuleFederationPlugin({
name: "remote_catalog", // matches the globalName in shell config
filename: "remoteEntry.js",
exposes: {
"./Catalog": "./src/Catalog",
},
shared: {
react: { singleton: true, requiredVersion: deps.react },
"react-dom": { singleton: true, requiredVersion: deps["react-dom"] },
},
}),
new HtmlWebpackPlugin({ template: "./public/index.html" }),
],
devServer: {
port: 3001,
historyApiFallback: true,
headers: {
"Access-Control-Allow-Origin": "*", // so shell can fetch remoteEntry.js
},
},
};

Enter fullscreen mode Exit fullscreen mode


markdown

The exposes map says "I export ./Catalog, which lives at ./src/Catalog." When the shell does import("remote-catalog/Catalog"), Webpack loads http://localhost:3001/remoteEntry.js, then asks it for ./Catalog, which loads the chunk containing the component.

CORS headers on the dev server are essential. The shell (port 3000) needs to fetch from the remote (port 3001). Browsers will block cross-origin script loads otherwise.

The Second Remote (Checkout)

Identical pattern. Different port, different exposed component.

TypeScriptCopy

Enter fullscreen mode Exit fullscreen mode


tsx
// remote-checkout/src/Checkout.tsx
import React, { useState } from "react";

export default function Checkout() {
const [items, setItems] = useState(2);
const total = items * 19.99;

return (


Checkout


{items} items in cart


Total: ${total.toFixed(2)}


setItems((n) => n + 1)}>Add item

);
}
Enter fullscreen mode Exit fullscreen mode


plaintext

JavaScriptCopy

Enter fullscreen mode Exit fullscreen mode


javascript
// remote-checkout/webpack.config.js
const { ModuleFederationPlugin } = require("webpack").container;
const HtmlWebpackPlugin = require("html-webpack-plugin");
const deps = require("./package.json").dependencies;

module.exports = {
mode: "development",
entry: "./src/index.ts",
output: { publicPath: "auto" },
resolve: { extensions: [".ts", ".tsx", ".js"] },
module: {
rules: [{ test: /.tsx?$/, loader: "ts-loader", exclude: /node_modules/ }],
},
plugins: [
new ModuleFederationPlugin({
name: "remote_checkout",
filename: "remoteEntry.js",
exposes: { "./Checkout": "./src/Checkout" },
shared: {
react: { singleton: true, requiredVersion: deps.react },
"react-dom": { singleton: true, requiredVersion: deps["react-dom"] },
},
}),
new HtmlWebpackPlugin({ template: "./public/index.html" }),
],
devServer: {
port: 3002,
historyApiFallback: true,
headers: { "Access-Control-Allow-Origin": "*" },
},
};

Enter fullscreen mode Exit fullscreen mode


markdown

Run all three: cd shell && npm start, cd remote-catalog && npm start, cd remote-checkout && npm start. Open http://localhost:3000, navigate around. Each route lazy-loads the appropriate remote.

Sharing State Across MFEs

This is where people get into trouble. You can't share a Redux store by importing it across MFEs (well, you can, but it couples them at build time, which defeats the point). The pattern I've settled on:

  1. Shell owns global state. Authentication, user profile, theme. The shell exposes these via a context or a custom event bus.
  2. Remotes own local state. Each MFE has its own state for its own UI. Don't reach across.
  3. Communication goes through a contract. Use CustomEvents, a tiny event emitter, or a shared state library exposed as a federated module.

Here's the event bus pattern:

TypeScriptCopy

Enter fullscreen mode Exit fullscreen mode


typescript
// shared/src/eventBus.ts
type Handler = (payload: unknown) => void;

class EventBus {
private handlers: Map> = new Map();

on(event: string, handler: Handler): () => void {
if (!this.handlers.has(event)) {
this.handlers.set(event, new Set());
}
this.handlers.get(event)!.add(handler);
return () => this.handlers.get(event)?.delete(handler);
}

emit(event: string, payload: unknown): void {
this.handlers.get(event)?.forEach((h) => {
try {
h(payload);
} catch (e) {
console.error(EventBus handler error for ${event}, e);
}
});
}
}

export const eventBus = new EventBus();

Enter fullscreen mode Exit fullscreen mode


plaintext

TypeScriptCopy

Enter fullscreen mode Exit fullscreen mode


typescript
// shared/src/types/events.d.ts
export interface AppEvents {
"cart:add-item": { productId: string; quantity: number };
"cart:updated": { itemCount: number; total: number };
"user:logged-out": undefined;
}

Enter fullscreen mode Exit fullscreen mode


plaintext

The shell exposes the event bus as a federated shared module:

JavaScriptCopy

Enter fullscreen mode Exit fullscreen mode


javascript
// shell/webpack.config.js (additions to ModuleFederationPlugin)
shared: {
react: { singleton: true, requiredVersion: deps.react },
"react-dom": { singleton: true, requiredVersion: deps["react-dom"] },
"react-router-dom": { singleton: true, requiredVersion: deps["react-router-dom"] },
"@my-org/shared": { // the event bus package
singleton: true,
requiredVersion: deps["@my-org/shared"],
},
},

Enter fullscreen mode Exit fullscreen mode


plaintext

Each remote also declares @my-org/shared as shared with singleton: true. Webpack ensures only one copy is loaded. Both shell and remotes import from @my-org/shared and use the same eventBus instance.

TypeScriptCopy

Enter fullscreen mode Exit fullscreen mode


tsx
// remote-catalog/src/Catalog.tsx (updated)
import React, { useEffect, useState } from "react";
import { eventBus } from "@my-org/shared";

type Product = { id: string; name: string; price: number };

export default function Catalog() {
const [products, setProducts] = useState([]);

useEffect(() => {
fetch("/api/products").then((r) => r.json()).then(setProducts);
}, []);

const addToCart = (p: Product) => {
eventBus.emit("cart:add-item", { productId: p.id, quantity: 1 });
};

return (


Catalog


    {products.map((p) => (
  • {p.name} - ${p.price}{" "} addToCart(p)}>Add
  • ))}


);
}
Enter fullscreen mode Exit fullscreen mode


plaintext

TypeScriptCopy

Enter fullscreen mode Exit fullscreen mode


tsx
// remote-checkout/src/Checkout.tsx (updated)
import React, { useEffect, useState } from "react";
import { eventBus } from "@my-org/shared";

export default function Checkout() {
const [items, setItems] = useState(0);

useEffect(() => {
return eventBus.on("cart:add-item", () => {
setItems((n) => n + 1);
});
}, []);

return (


Checkout


{items} items in cart



);
}
Enter fullscreen mode Exit fullscreen mode


markdown

Now: user clicks "Add" in the catalog MFE, the event fires, the checkout MFE's count updates. No shared store, no tight coupling, just a typed contract.

Routing Across MFEs

Routing is the second-most-confusing area. The shell owns the top-level routes, but each remote might want its own nested routes. The pattern:

  1. Shell uses react-router-dom with top-level routes.
  2. Each remote renders its own <Routes> inside the shell's route.
TypeScriptCopy

Enter fullscreen mode Exit fullscreen mode


tsx
// remote-catalog/src/Catalog.tsx (with internal routing)
import React from "react";
import { Routes, Route, Link } from "react-router-dom";

const ProductList = React.lazy(() => import("./ProductList"));
const ProductDetail = React.lazy(() => import("./ProductDetail"));

export default function Catalog() {
return (


Catalog


All

} />
} />


);
}
Enter fullscreen mode Exit fullscreen mode


markdown

This works because react-router-dom is shared as a singleton. The remote's <Routes> operates on the same router context as the shell's. The shell's route is /catalog/*, which leaves the * part for the remote's nested routes. So /catalog/123 shows the catalog MFE with ProductDetail for product 123.

The /* on the shell's route is critical. Without it, the shell's route matching consumes the entire path and the remote never sees the nested part.

Deployment: Independent Releases

The deployment story is the whole point. Each MFE has its own CI/CD pipeline, builds its own assets, and uploads them to static hosting.

CodeCopy

Enter fullscreen mode Exit fullscreen mode


plaintext
┌────────────────┐ ┌──────────────────┐
│ Shell build │ │ Catalog build │
│ (CI pipeline) │ │ (CI pipeline) │
└────────┬───────┘ └────────┬─────────┘
│ │
▼ ▼
┌─────────────────────────────────────────┐
│ Static hosting │
│ /shell/* → shell assets │
│ /catalog/* → catalog remoteEntry.js │
│ /checkout/* → checkout remoteEntry.js │
└─────────────────────────────────────────┘

Enter fullscreen mode Exit fullscreen mode


plaintext

The tricky bit: the shell needs to know where to find the remotes. In dev, that's hardcoded URLs. In prod, you have options:

  1. Hardcoded production URLs. https://cdn.example.com/catalog/remoteEntry.js. Simple, works, but shell rebuild required to update remote URL.
  2. Manifest file. A JSON file the shell fetches at runtime with remote URLs. Allows remotes to be redeployed without rebuilding the shell.
  3. Environment-injected URLs. Shell fetches URLs from a config endpoint at startup.

I use the manifest pattern for any non-trivial deployment.

TypeScriptCopy

Enter fullscreen mode Exit fullscreen mode


typescript
// shell/src/loadRemotes.ts
import type { RemoteEntry } from "@my-org/shared";

declare global {
interface Window {
REMOTES?: Record;
}
}

export async function loadRemoteManifest(url: string): Promise> {
// Cache the manifest so re-fetches don't happen on HMR.
if (window.REMOTES) return window.REMOTES;
const res = await fetch(url);
if (!res.ok) throw new Error(Failed to load remote manifest: ${res.status});
const manifest = await res.json();
window.REMOTES = manifest;
return manifest;
}

Enter fullscreen mode Exit fullscreen mode


plaintext

JSONCopy

Enter fullscreen mode Exit fullscreen mode


json
// manifests/production.json
{
"remote-catalog": "https://cdn.example.com/catalog/v1.4.2/remoteEntry.js",
"remote-checkout": "https://cdn.example.com/checkout/v2.1.0/remoteEntry.js"
}

Enter fullscreen mode Exit fullscreen mode


plaintext

But here's the catch: Module Federation's remotes are resolved at build time. To make them runtime-configurable, you need a small plugin. The pattern is to use promise-based remotes:

JavaScriptCopy

Enter fullscreen mode Exit fullscreen mode


javascript
// shell/webpack.config.js (promise-based remotes)
new ModuleFederationPlugin({
name: "shell",
remotes: {
"remote-catalog": promise new Promise((resolve, reject) => {
fetch("/manifests/production.json")
.then(r => r.json())
.then(m => {
const script = document.createElement("script");
script.src = m["remote-catalog"];
script.onload = () => {
const proxy = {
get: (request) => window.remote_catalog.get(request),
init: (arg) => {
try { return window.remote_catalog.init(arg); }
catch(e) { console.log("remote container already initialized"); }
}
};
resolve(proxy);
};
script.onerror = () => reject(new Error("Failed to load remote-catalog"));
document.head.appendChild(script);
})
.catch(reject);
})
,
},
// ... shared as before
}),

Enter fullscreen mode Exit fullscreen mode


markdown

This is ugly but it works. The shell fetches the manifest at runtime, then loads each remote's remoteEntry.js based on the manifest's URL. Remotes can be redeployed independently-the shell doesn't need a rebuild.

Production Considerations

Caching. Each remote's remoteEntry.js should be served with a long cache TTL and a hashed filename for content-addressing. But the manifest must be served with a short TTL (or no cache) so the shell picks up new remote URLs. Without this, users get stale remotes that don't match the new shell.

Version compatibility. What happens when the shell expects remote-catalog/Catalog to take a prop theme, but the catalog MFE was just redeployed with a different prop API? Your contract package (@my-org/shared) needs versioned types. Bump the major version when the API breaks, and the shell should refuse to load a remote with an incompatible major.

Error boundaries. When a remote fails to load (network error, deploy in progress), the shell shouldn't crash. Wrap each remote in a React error boundary that shows a friendly fallback.

TypeScriptCopy

Enter fullscreen mode Exit fullscreen mode


tsx
// shell/src/RemoteBoundary.tsx
import React, { Component, ErrorInfo, ReactNode } from "react";

interface Props { children: ReactNode; name: string; }
interface State { hasError: boolean; }

export class RemoteBoundary extends Component {
state: State = { hasError: false };

static getDerivedStateFromError(): State {
return { hasError: true };
}

componentDidCatch(error: Error, info: ErrorInfo) {
console.error(Remote ${this.props.name} failed, error, info);
// Report to Sentry, Datadog, etc.
}

render() {
if (this.state.hasError) {
return (


Something went wrong loading {this.props.name}.


location.reload()}>Reload

);
}
return this.props.children;
}
}
Enter fullscreen mode Exit fullscreen mode


markdown

Use it: <RemoteBoundary name="catalog"><Catalog /></RemoteBoundary>.

Performance: shared chunks. The shared config controls which dependencies are deduplicated. Too few, and you load React twice. Too many, and the Webpack runtime negotiation overhead grows. My rule: singleton for React, ReactDOM, router, and any state library. Eager: false (the default) for everything else.

Performance: preloading. Lazy-load by default, but preload the remote for the route the user is likely to navigate to next. A <link rel="modulepreload"> for the next remote cuts perceived latency significantly.

Common Mistakes

Mistake: Forgetting the bootstrap indirection. Your entry file imports App directly. Module Federation fails to initialize shared deps before your code runs. Detect: "Cannot read properties of undefined" or hooks complaining about multiple Reacts. Fix: entry file does import("./bootstrap"). Always.

Mistake: Two copies of React. Remotes don't declare React as shared singleton. Hooks crash with "Invalid hook call." Fix: every MFE's Webpack config must list react and react-dom as singleton: true.

Mistake: Building all MFEs in one repo. Defeats the purpose. Teams can't deploy independently if the build is coupled. Fix: separate repos, or a monorepo with per-package CI that builds only the changed package.

Mistake: Sharing too much state. Remotes reach into the shell's Redux store directly. You've rebuilt the monolith. Fix: event bus or context, with a typed contract.

Mistake: publicPath not set to auto. Remote assets fail to load because Webpack uses the wrong base URL. Detect: 404s for chunk files in the network tab, with URLs pointing to the shell's domain instead of the remote's. Fix: output.publicPath: "auto" in every MFE config.

Mistake: Tight version coupling. Shell requires react@^18.2.0, remote has react@18.3.1. Webpack refuses to load the remote. Fix: use requiredVersion: false for non-critical deps, or align versions via the shared types package.

Troubleshooting

"Shared module is not available for eager consumption." You skipped the bootstrap indirection. Entry file must dynamically import the app.

Remote loads but component is undefined. Check the exposes path in the remote's config matches the import path the shell uses. Case sensitivity matters on Linux, not on macOS-CI catches what dev doesn't.

Module not found: 'react' in remote. The remote doesn't declare React as shared. Add it to shared.

Slow first load. Each remote loads its own remoteEntry.js, then chunks. Preload critical remotes. Reduce shared dep negotiation by being explicit about versions.

HMR broken with multiple remotes. Webpack DevServer's HMR doesn't always play well with federated modules across origins. Use live reloading instead of HMR for cross-MFE changes, or accept that you'll reload after remote changes.

TypeScript can't find remote-catalog/Catalog. Add a d.ts file with the module declaration:

TypeScriptCopy

Enter fullscreen mode Exit fullscreen mode


typescript
// shell/src/types/remotes.d.ts
declare module "remote-catalog/Catalog" {
const Component: React.ComponentType;
export default Component;
}
declare module "remote-checkout/Checkout" {
const Component: React.ComponentType;
export default Component;
}

Enter fullscreen mode Exit fullscreen mode


markdown

Testing Micro-Frontends

Each MFE has its own unit tests (Jest/Vitest) and its own component tests (Testing Library). The interesting part is integration testing-the shell with all remotes loaded.

Use Playwright for end-to-end tests. Run the full shell + remotes in CI (or against a staging environment) and exercise the user flows that cross MFE boundaries.

TypeScriptCopy

Enter fullscreen mode Exit fullscreen mode


typescript
// e2e/catalog-add-to-cart.spec.ts
import { test, expect } from "@playwright/test";

test("user can add product to cart from catalog", async ({ page }) => {
await page.goto("http://localhost:3000/catalog");
await page.click("text=Add");
await page.click("text=Checkout");
await expect(page.locator("text=1 items in cart")).toBeVisible();
});

Enter fullscreen mode Exit fullscreen mode


plaintext

For unit tests that import from a remote, mock the import:

TypeScriptCopy

Enter fullscreen mode Exit fullscreen mode


tsx
// shell/src/tests/App.test.tsx
jest.mock("remote-catalog/Catalog", () => ({
__esModule: true,
default: () =>

,
}));

Contract tests are worth their weight in gold. Use the shared types package as the source of truth, and have a CI check that verifies each remote's exposed components match the expected props.

Cost Considerations

  • CI compute: Each MFE has its own build pipeline. 3 MFEs × $50/month CI = $150/month. Scale linearly with team count.
  • Static hosting: Trivial. CloudFront + S3 for a few GB of assets is <$10/month total.
  • Developer time: The real cost. Onboarding new devs to a federated codebase takes 2x longer than a monolith. Document the architecture.

The economics flip at team scale. One team: monolith is cheaper. Five teams each shipping weekly: MFEs save you the integration tax.

Alternatives

  • Single-spa. Framework-agnostic, more flexible, more boilerplate. Good if you have legacy Angular + new React that need to coexist.
  • Vite Module Federation (vite-plugin-federation). Same concept, faster dev server. Less mature than Webpack MF as of late 2024, but improving fast.
  • Import maps + esm.sh. Native browser ES modules with import maps. No bundler needed. Still experimental for production use.
  • Iframes. Still the right choice for true third-party isolation (embedded marketplace, untrusted widget). Accept the UX cost.
  • Server-side composition (Edge-side includes, Next.js multi-zones). Each team's app is a full Next.js app; the edge stitches them together. Increasingly popular for content-heavy sites.

Real-World Use Cases I've Shipped

  • E-commerce platform. Three MFEs (catalog, cart, account) owned by three teams. Shell owned by a fourth "platform" team. Each team shipped independently, sometimes 10x per day.
  • Internal admin tool. Five MFEs, each owned by the team that owned the corresponding backend service. The platform team provided the shell and auth. New teams could add an MFE without touching anyone else's code.
  • Marketing site + app. Marketing site (Next.js) and application (separate React SPA) composed via Module Federation. Marketing team could ship content changes without involving the app team.

Wrapping Up

Micro-frontends are an architectural pattern with real costs. They solve a specific problem-independent deploys across multiple teams-and they introduce real complexity in routing, state, and contracts. Used for the wrong problem, they're a tax. Used for the right problem, they unblock teams that were stepping on each other.

If you take one thing from this: start with the contract. Define the props, events, and routes your MFEs will share before you write any code. The shared types package is the load-bearing wall of the whole architecture. Get it right, and everything else falls into place. Get it wrong, and you'll spend months untangling the resulting mess.

Module Federation itself is mature and well-documented. The hard parts are the organizational decisions: which teams own what, how you version the contract, how you handle deploy ordering. Those are conversations, not config files.


Originally published on Mango Developer.

Top comments (0)