When do micro frontends make sense?
Related reading: DDD in frontend, Monorepo vs Multirepo.
Choose boundaries around business capabilities, not component types. Catalog and orders can have separate domain owners, unit and integration test suites, and delivery pipelines. Buttons, headers and form fields typically belong in a shared design system. A monorepo can support independent releases; multiple repositories do not guarantee autonomy. [1][2]
If one team frequently changes all features together, a modular monolith is a simpler starting point. Measure release waiting time, coordinated changes and operational costs. The split should solve an actual organizational bottleneck rather than simply increase the number of applications.
Micro frontends versus a modular monolith
| Criterion | Modular monolith | Micro frontends |
|---|---|---|
| Deployment | One deployment unit | Separate releases subject to contracts |
| Team autonomy | Shared release, separate domain modules | Independent release cadence and domain ownership |
| Performance | Easier whole-bundle optimization | Risk of duplicate dependencies and request waterfalls |
| Testing | Integration of one application version | Additional compatibility matrix and contract tests |
| UI and accessibility | One shell and shared components | Coordinated navigation, focus and design system required |
| Resilience | One deployment unit; module-level error isolation possible | Fault containment depends on execution boundaries |
| Maintenance | Lower initial operational overhead | More artifacts, pipelines and monitoring |
| Security | Shared application trust boundary | Code in one document still shares privileges |
| Potential benefit | What micro frontends do not guarantee |
|---|---|
| Independent releases | Compatibility of every version combination |
| Team autonomy | Absence of cross-domain dependencies |
| Incremental modernization | Migration without integration costs |
| Technology choice | Faster performance or smaller transfers |
| Domain ownership | Correct domain boundaries without modeling |
| Fault containment | Security isolation or whole-product resilience |
| Parallel development | Lower total maintenance costs |
The comparison concerns frontend architecture, not the backend topology or repository count. A modular monolith can use microservices and independent domain modules. The table describes typical trade-offs, not measured guarantees. [22][23]
How can independently delivered applications be integrated?
Route-level integration lets a server send different paths to separate applications. Navigation may reload the document, but shared state and dependencies are easier to constrain. Server composition assembles HTML before delivery and needs a coherent strategy for CSS, data, caching and possible hydration. Build-time npm packages require rebuilding the consumer. [1][2]
Browser composition with ESM, Module Federation or an orchestrator can change selected regions without rebuilding the host if contracts and version selection remain compatible. An iframe can provide a separate document or different trust boundaries, but complicates routing, accessibility and communication. [3][4][5]
The host and remote contract
contract.ts
export const CONTRACT_VERSION = 1;
export type Dispose = () => void;
export interface RemoteModule {
readonly contractVersion: typeof CONTRACT_VERSION;
mount(outlet: HTMLElement): Dispose;
}
catalog/v1/entry.ts
import type { RemoteModule } from "../../contract.js";
const remote: RemoteModule = {
contractVersion: 1,
mount(outlet) {
const heading = document.createElement("h2");
heading.textContent = "Catalog";
const button = document.createElement("button");
button.type = "button";
button.textContent = "Show availability";
const message = document.createElement("p");
message.setAttribute("role", "status");
const listeners = new AbortController();
button.addEventListener(
"click",
() => {
message.textContent = "Demo item available";
},
{ signal: listeners.signal },
);
outlet.append(heading, button, message);
return () => {
listeners.abort();
outlet.replaceChildren();
};
},
};
export const { contractVersion, mount } = remote;
orders/v1/entry.ts
import type { RemoteModule } from "../../contract.js";
const remote: RemoteModule = {
contractVersion: 1,
mount(outlet) {
const heading = document.createElement("h2");
heading.textContent = "Orders";
const message = document.createElement("p");
message.textContent = "No demo orders.";
outlet.append(heading, message);
return () => {
outlet.replaceChildren();
};
},
};
export const { contractVersion, mount } = remote;
The host owns navigation and an outlet; the remote owns its feature. Contract v1 requires a version export and a synchronous mount returning a cleanup function. TypeScript types are erased at runtime, so the host also checks the namespace shape. Checking that a function exists does not prove its behavior or safety. [6]
The module mounts into a detached element and must not assume layout measurements are available. It must not change global DOM or register irreversible module-level effects. If mount throws, the remote is responsible for cleaning partially acquired resources. The interface does not permit synchronous reentrant navigation. A real product may add a separate activation contract after DOM insertion.
Dynamic imports and failure handling
shell/remote-loader.ts
import { CONTRACT_VERSION } from "../contract.js";
import type { RemoteModule } from "../contract.js";
export type RemoteName = "catalog" | "orders";
export type RemoteLoader = (name: RemoteName) => Promise<unknown>;
function isObject(value: unknown): value is object {
if (value === null) {
return false;
}
return typeof value === "object";
}
export function isRemoteModule(value: unknown): value is RemoteModule {
if (!isObject(value)) {
return false;
}
if (!("contractVersion" in value)) {
return false;
}
if (value.contractVersion !== CONTRACT_VERSION) {
return false;
}
if (!("mount" in value)) {
return false;
}
return typeof value.mount === "function";
}
export async function withTimeout<T>(
work: Promise<T>,
timeoutMs: number,
): Promise<T> {
let timer: ReturnType<typeof setTimeout> | undefined;
const deadline = new Promise<never>((_, reject) => {
timer = setTimeout(() => {
reject(new Error("Module loading timed out."));
}, timeoutMs);
});
try {
return await Promise.race([work, deadline]);
} finally {
clearTimeout(timer);
}
}
shell/native-loader.ts
import type { RemoteName } from "./remote-loader.js";
const entries: Record<RemoteName, URL> = {
catalog: new URL("../catalog/v1/entry.js", import.meta.url),
orders: new URL("../orders/v1/entry.js", import.meta.url),
};
export function loadRemote(name: RemoteName): Promise<unknown> {
return import(entries[name].href);
}
shell/host.ts
import type { Dispose } from "../contract.js";
import { isRemoteModule, withTimeout } from "./remote-loader.js";
import type { RemoteLoader, RemoteName } from "./remote-loader.js";
export interface Surface {
createOutlet(): HTMLElement;
show(outlet: HTMLElement): void;
status(message: string): void;
}
const DEFAULT_TIMEOUT_MS = 10_000;
export class MicroFrontendHost {
private revision = 0;
private cleanup: Dispose | undefined;
constructor(
private readonly surface: Surface,
private readonly load: RemoteLoader,
private readonly report: (error: unknown) => void,
private readonly timeoutMs = DEFAULT_TIMEOUT_MS,
) {}
private reportFailure(error: unknown): void {
try {
this.report(error);
} catch {
// A telemetry failure must not break navigation or cleanup.
}
}
private release(): void {
const cleanup = this.cleanup;
this.cleanup = undefined;
try {
cleanup?.();
} catch (error) {
this.reportFailure(error);
}
}
async navigate(name: RemoteName): Promise<void> {
const revision = ++this.revision;
this.release();
this.surface.show(this.surface.createOutlet());
this.surface.status("Loading module…");
try {
const module = await withTimeout(this.load(name), this.timeoutMs);
if (revision !== this.revision) {
return;
}
if (!isRemoteModule(module)) {
throw new TypeError("Incompatible remote module.");
}
const outlet = this.surface.createOutlet();
const cleanup = module.mount(outlet);
if (typeof cleanup !== "function") {
throw new TypeError("Remote must return a cleanup function.");
}
this.cleanup = cleanup;
this.surface.show(outlet);
this.surface.status("");
} catch (error) {
if (revision !== this.revision) {
return;
}
this.release();
this.surface.show(this.surface.createOutlet());
this.surface.status("Module unavailable. Reload section to retry.");
this.reportFailure(error);
}
}
dispose(): void {
this.revision += 1;
this.release();
this.surface.show(this.surface.createOutlet());
this.surface.status("");
}
}
shell/main.ts
import { MicroFrontendHost } from "./host.js";
import { createManifestLoader } from "./release-manifest.js";
import type { RemoteName } from "./remote-loader.js";
function requireElement(id: string): HTMLElement {
const element = document.getElementById(id);
if (!element) {
throw new Error(`Missing element: ${id}`);
}
return element;
}
const outlet = requireElement("outlet");
const status = requireElement("status");
const retry = requireElement("retry");
const heading = requireElement("page-heading");
const links = document.querySelectorAll<HTMLAnchorElement>("nav a");
const host = new MicroFrontendHost(
{
createOutlet: () => document.createElement("section"),
show: (element) => outlet.replaceChildren(element),
status: (message) => {
status.textContent = message;
},
},
createManifestLoader(),
(error) => console.error("Micro frontend failed", error),
);
function route(): RemoteName {
if (location.hash === "#orders") {
return "orders";
}
return "catalog";
}
function renderRoute(moveFocus = false): void {
const name = route();
const title = name === "catalog" ? "Catalog" : "Orders";
document.title = `${title} | Shop`;
heading.textContent = title;
for (const link of links) {
if (link.hash === `#${name}`) {
link.setAttribute("aria-current", "page");
} else {
link.removeAttribute("aria-current");
}
}
if (moveFocus) {
heading.focus();
}
void host.navigate(name);
}
window.addEventListener("hashchange", () => renderRoute(true));
retry.addEventListener("click", () => renderRoute());
renderRoute();
index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Micro frontend example</title>
<link rel="stylesheet" href="/en/shell.css" />
<script type="module" src="dist/shell/main.js"></script>
</head>
<body>
<header>
<nav aria-label="Sections">
<a href="#catalog">Catalog</a>
<a href="#orders">Orders</a>
</nav>
</header>
<main>
<h1 id="page-heading" tabindex="-1">Shop</h1>
<p id="status" role="status"></p>
<button id="retry" type="button">Reload section</button>
<div id="outlet"></div>
</main>
</body>
</html>
shell.css
body {
font-family: system-ui, sans-serif;
margin: 2rem;
line-height: 1.5;
}
nav {
display: flex;
gap: 1rem;
}
:focus-visible {
outline: 2px solid currentColor;
outline-offset: 3px;
}
The example uses native ES modules, not Module Federation. Entry URLs come from trusted host configuration; user URL parameters do not select arbitrary scripts. A revision counter prevents outdated navigation results from mounting. A timeout bounds how long the host waits, but does not abort the import or its execution. [6][7]
A load failure, incompatible version or mount error displays a message while leaving navigation available. Retrying does not guarantee re-evaluation at the same URL, especially after an evaluation error. Removing DOM does not release global subscriptions; call the returned cleanup. Errors in later event handlers are outside the try/catch around mount.
Module Federation and dependencies
federation/webpack.config.cjs
const path = require("node:path");
const { ModuleFederationPlugin } = require("webpack").container;
const root = path.resolve(__dirname, "..");
const catalog = {
name: "catalog",
mode: "production",
entry: {},
output: {
path: path.join(root, "federated-dist/catalog/v1"),
publicPath: "auto",
uniqueName: "catalog",
},
plugins: [
new ModuleFederationPlugin({
name: "catalog",
filename: "remoteEntry.js",
exposes: {
"./feature": path.join(root, "dist/catalog/v1/entry.js"),
},
}),
],
};
const host = {
name: "shop",
mode: "production",
entry: path.join(__dirname, "host.js"),
output: {
path: path.join(root, "federated-dist/shop"),
filename: "main.js",
publicPath: "auto",
uniqueName: "shop",
},
plugins: [
new ModuleFederationPlugin({
name: "shop",
remotes: {
catalog: "catalog@../catalog/v1/remoteEntry.js",
},
}),
],
};
module.exports = [catalog, host];
federation/host.js
import { MicroFrontendHost } from "../dist/shell/host.js";
const container = document.getElementById("outlet");
const status = document.getElementById("status");
if (!container) {
throw new Error("Missing outlet.");
}
if (!status) {
throw new Error("Missing status.");
}
const host = new MicroFrontendHost(
{
createOutlet: () => document.createElement("section"),
show: (element) => container.replaceChildren(element),
status: (message) => {
status.textContent = message;
},
},
() => import("catalog/feature"),
(error) => console.error("Federated module failed", error),
);
void host.navigate("catalog");
federation/index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Federated catalog example</title>
<script defer src="main.js"></script>
</head>
<body>
<main>
<h1>Federated catalog</h1>
<p id="status" role="status"></p>
<div id="outlet"></div>
</main>
</body>
</html>
Webpack Module Federation combines separately built modules using containers and dependency sharing. A remote exposes selected modules and a host points at the container. remoteEntry.js is an entry that may load additional chunks. publicPath sets their base URL. [3][8]
Options such as singleton and requiredVersion control sharing but cannot solve all incompatibilities. Version mismatches can warn or fail depending on configuration, for example strictVersion. Shared UI libraries need stable contracts; a global state singleton often forces coordinated releases. Test the current host with supported remote versions, not only each build in isolation.
The alternative webpack example requires compiled TypeScript modules, webpack 5 and webpack-cli. Build the catalog and shop configurations separately; put the host page at /shop/index.html. It is separate from the ESM example and was not executed in this validation.
Routing, data, styles and security
Related reading: JavaScript event propagation and delegation.
The host should own top-level routes, locale context and navigation chrome. Modules exchange data through explicit properties, callbacks or versioned events carrying minimal information. The backend enforces authorization. Do not broadcast tokens in global events. CSS Modules, prefixes or Shadow DOM limit style collisions; shared tokens improve visual consistency. [1]
Code executing in the same document generally has access to its JavaScript environment and DOM; neither Shadow DOM nor Module Federation is a security boundary. For less trusted code consider a separate origin and a restricted iframe sandbox. With postMessage validate origin, source and payload; use an exact targetOrigin when known. CSP and SRI mitigate specific threats but do not isolate a trusted script after execution. [4][5][9][10]
Independent releases, caching and observability
Related article: Service Workers: Caching, Offline and Updates.
Publish immutable assets at versioned paths, upload all assets first, then atomically update a controlled manifest or host configuration. Retain previous assets for the supported lifetime of active sessions and allow rolling back the version pointer. Do not overwrite long-cached files at the same URL. Check Service Worker and CDN behavior. [1][7][8]
The example selects releases from a validated manifest and pins them for the document lifetime; separate build targets do not replace a delivery pipeline. Measure import latency, errors by release, JS size and INP. Duplicated frameworks and request waterfalls may degrade results.
The example v1 asset path is a release identifier, while contractVersion denotes interface compatibility; in production they change independently. On route changes, manage document titles and meaningful focus movement. Use short freshness or revalidation for manifests, long caching for immutable assets. [7]
Contract testing and migration
host.test.mjs
import assert from "node:assert/strict";
import { test } from "node:test";
import { MicroFrontendHost } from "./dist/shell/host.js";
import { isRemoteModule } from "./dist/shell/remote-loader.js";
function fixture(load, timeoutMs = 1000) {
const state = { outlet: {}, status: "", errors: [] };
const host = new MicroFrontendHost(
{
createOutlet: () => ({}),
show: (outlet) => {
state.outlet = outlet;
},
status: (message) => {
state.status = message;
},
},
load,
(error) => state.errors.push(error),
timeoutMs,
);
return { host, state };
}
function remote(name, cleanup = () => {}) {
return {
contractVersion: 1,
mount(outlet) {
outlet.name = name;
return cleanup;
},
};
}
function deferred() {
let resolve;
const promise = new Promise((done) => {
resolve = done;
});
return { promise, resolve };
}
test("rejects malformed and incompatible module namespaces", () => {
// Given
const invalid = [
null,
4,
{},
{ contractVersion: 2, mount() {} },
{ contractVersion: 1, mount: false },
];
// When / Then
for (const value of invalid) {
assert.equal(isRemoteModule(value), false);
}
assert.equal(isRemoteModule(remote("catalog")), true);
});
test("mounts and releases modules on navigation", async () => {
// Given
let released = 0;
const { host, state } = fixture(async (name) =>
remote(name, () => {
released += 1;
}),
);
await host.navigate("catalog");
// When
await host.navigate("orders");
// Then
assert.equal(state.outlet.name, "orders");
assert.equal(released, 1);
host.dispose();
host.dispose();
assert.equal(released, 2);
});
test("late imports do not replace a newer route", async () => {
// Given
const slow = deferred();
const { host, state } = fixture((name) => {
if (name === "catalog") {
return slow.promise;
}
return Promise.resolve(remote(name));
});
const pending = host.navigate("catalog");
// When
await host.navigate("orders");
slow.resolve(remote("catalog"));
await pending;
// Then
assert.equal(state.outlet.name, "orders");
assert.equal(state.errors.length, 0);
});
test("a failure leaves the shell usable and can be retried", async () => {
// Given
let attempts = 0;
const { host, state } = fixture(async (name) => {
attempts += 1;
if (attempts === 1) {
throw new Error("Unavailable");
}
return remote(name);
});
// When
await host.navigate("catalog");
assert.match(state.status, /unavailable/);
await host.navigate("catalog");
// Then
assert.equal(state.status, "");
assert.equal(state.outlet.name, "catalog");
assert.equal(state.errors.length, 1);
});
test("an incompatible module never mounts", async () => {
let mounted = false;
const { host, state } = fixture(async () => ({
contractVersion: 2,
mount() {
mounted = true;
},
}));
await host.navigate("catalog");
assert.equal(mounted, false);
assert.match(state.status, /unavailable/);
});
test("timeout ignores the result of a late import", async () => {
const slow = deferred();
const { host, state } = fixture(() => slow.promise, 5);
await host.navigate("catalog");
slow.resolve(remote("catalog"));
await slow.promise;
assert.match(state.status, /unavailable/);
assert.equal(state.outlet.name, undefined);
});
test("dispose invalidates an in-flight navigation", async () => {
const slow = deferred();
const { host, state } = fixture(() => slow.promise);
const pending = host.navigate("orders");
host.dispose();
slow.resolve(remote("orders"));
await pending;
assert.equal(state.status, "");
assert.equal(state.outlet.name, undefined);
});
test("failed cleanup is reported and the next module can mount", async () => {
const { host, state } = fixture(async (name) =>
remote(name, () => {
throw new Error("Cleanup failed");
}),
);
await host.navigate("catalog");
await host.navigate("orders");
assert.equal(state.outlet.name, "orders");
assert.equal(state.errors.length, 1);
});
test("a mount exception is reported and leaves an empty outlet", async () => {
const { host, state } = fixture(async () => ({
contractVersion: 1,
mount(outlet) {
outlet.name = "partial";
throw new Error("Mount failed");
},
}));
await host.navigate("catalog");
assert.match(state.status, /unavailable/);
assert.equal(state.outlet.name, undefined);
});
test("compiled catalog and orders satisfy the runtime contract", async () => {
// Given
const names = ["catalog", "orders"];
// When / Then
for (const name of names) {
const module = await import(`./dist/${name}/v1/entry.js`);
assert.equal(isRemoteModule(module), true);
}
});
test("native loader returns the expected compiled module", async () => {
const { loadRemote } = await import("./dist/shell/native-loader.js");
const module = await loadRemote("catalog");
assert.equal(isRemoteModule(module), true);
});
test("a failing telemetry sink cannot prevent recovery", async () => {
// Given
let status = "";
const host = new MicroFrontendHost(
{
createOutlet: () => ({}),
show: () => {},
status: (message) => {
status = message;
},
},
async () => {
throw new Error("Remote failed");
},
() => {
throw new Error("Telemetry failed");
},
);
// When
await host.navigate("catalog");
// Then
assert.match(status, /unavailable/);
});
Host unit tests inject the loader and rendering surface, letting you verify response order, incompatible contracts, timeouts, cleanup and failures independently. Given-When-Then separates the initial state, action and expected result. Contract tests should also import built remote artifacts. E2E tests cover navigation, focus, network failures and version compatibility after deployment. [1]
Start by extracting one capability, measure the outcome and keep a path back to a modular monolith. Expand only once the team can deploy and monitor its feature independently. Assign contract owners, performance budgets and a policy for retiring old releases.
Release manifest and runtime compatibility
releases.json
{
"contractVersion": 1,
"catalog": "v1",
"orders": "v1"
}
shell/release-manifest.ts
import { CONTRACT_VERSION } from "../contract.js";
import type { RemoteLoader, RemoteName } from "./remote-loader.js";
const RELEASE_PATTERN = /^v[1-9]\d{0,8}$/u;
const MANIFEST_TIMEOUT_MS = 5_000;
type Releases = Readonly<Record<RemoteName, string>>;
type ImportModule = (url: string) => Promise<unknown>;
function readRecord(value: unknown): Record<string, unknown> {
if (value === null) {
throw new TypeError("Expected a manifest object.");
}
if (typeof value !== "object") {
throw new TypeError("Expected a manifest object.");
}
if (Array.isArray(value)) {
throw new TypeError("Expected a manifest object.");
}
return value as Record<string, unknown>;
}
function readRelease(value: unknown): string {
if (typeof value !== "string") {
throw new TypeError("Expected a release identifier.");
}
const match = value.match(RELEASE_PATTERN);
if (match?.[0] !== value) {
throw new TypeError("Invalid release identifier.");
}
return value;
}
export function parseManifest(value: unknown): Releases {
const manifest = readRecord(value);
if (manifest.contractVersion !== CONTRACT_VERSION) {
throw new TypeError("Incompatible release manifest.");
}
return Object.freeze({
catalog: readRelease(manifest.catalog),
orders: readRelease(manifest.orders),
});
}
export function createManifestLoader(
fetcher: typeof fetch = fetch,
importModule: ImportModule = (url) => import(url),
): RemoteLoader {
const manifestUrl = new URL("../../releases.json", import.meta.url);
let snapshot: Promise<Releases> | undefined;
async function fetchReleases(): Promise<Releases> {
const response = await fetcher(manifestUrl, {
cache: "no-cache",
redirect: "error",
signal: AbortSignal.timeout(MANIFEST_TIMEOUT_MS),
});
if (!response.ok) {
throw new Error(`Manifest HTTP ${response.status}.`);
}
const data: unknown = await response.json();
return parseManifest(data);
}
function getSnapshot(): Promise<Releases> {
snapshot ??= fetchReleases().catch((error: unknown) => {
snapshot = undefined;
throw error;
});
return snapshot;
}
return async (name) => {
const releases = await getSnapshot();
const path = `../${name}/${releases[name]}/entry.js`;
const url = new URL(path, import.meta.url);
return importModule(url.href);
};
}
manifest.test.mjs
import assert from "node:assert/strict";
import { test } from "node:test";
import {
createManifestLoader,
parseManifest,
} from "./dist/shell/release-manifest.js";
const release = { contractVersion: 1, catalog: "v1", orders: "v2" };
function respond(data) {
return new Response(JSON.stringify(data));
}
test("accepts a compatible manifest and freezes its snapshot", () => {
// Given / When
const snapshot = parseManifest(release);
// Then
assert.deepEqual(snapshot, { catalog: "v1", orders: "v2" });
assert.equal(Object.isFrozen(snapshot), true);
});
for (const invalid of [null, [], {}, { ...release, contractVersion: 2 }]) {
test(`rejects invalid manifest ${JSON.stringify(invalid)}`, () => {
assert.throws(() => parseManifest(invalid), TypeError);
});
}
for (const value of ["../bad", "https://bad.test/a", "v1\n", "v0", 1]) {
test(`rejects unsafe release ${JSON.stringify(value)}`, () => {
assert.throws(() => parseManifest({ ...release, catalog: value }));
});
}
test("shares one snapshot across concurrent and later imports", async () => {
// Given
let calls = 0;
const loader = createManifestLoader(async () => {
calls += 1;
return respond(release);
}, async (url) => new URL(url).pathname);
// When
const paths = await Promise.all([loader("catalog"), loader("orders")]);
await loader("catalog");
// Then
assert.equal(calls, 1);
assert.match(paths[0], /catalog\/v1\/entry\.js$/);
assert.match(paths[1], /orders\/v2\/entry\.js$/);
});
test("a failed manifest can be fetched again", async () => {
// Given
let calls = 0;
const loader = createManifestLoader(async () => {
calls += 1;
if (calls === 1) {
return new Response(null, { status: 503 });
}
return respond(release);
}, async (url) => url);
// When / Then
await assert.rejects(loader("catalog"), /503/);
assert.match(await loader("catalog"), /catalog\/v1\/entry\.js$/);
assert.equal(calls, 2);
});
test("invalid manifest is rejected before importing a module", async () => {
// Given
let imports = 0;
const loader = createManifestLoader(async () => respond({}), async () => {
imports += 1;
});
// When / Then
await assert.rejects(loader("catalog"), TypeError);
assert.equal(imports, 0);
});
test("manifest loader imports the actual compiled catalog", async () => {
// Given
const loader = createManifestLoader(async () => respond(release));
// When
const module = await loader("catalog");
// Then
assert.equal(module.contractVersion, 1);
assert.equal(typeof module.mount, "function");
});
In this demo releases.json contains the contract version and release identifiers for catalog and orders. The host fetches a fixed URL, requests HTTP revalidation, rejects redirects and bounds the fetch duration. The validator rejects arbitrary URLs and path segments: only identifiers such as v1 or v2 are allowed. Module URLs are constructed from controlled paths. This is not a cryptographic signature or protection against a compromised trusted origin. [6][7]
A shared promise pins the release snapshot for the host lifetime; navigation does not refetch it. A failed fetch can be retried, and a manifest rollback affects new host instances. Retain old artifacts for active documents. Test the current host against all supported remote releases; release identity and contract version are independent.
Tool selection and limitations in 2026
Native import maps resolve module specifiers in documents; they do not orchestrate application lifecycles. Cross-origin ESM requires appropriate CORS. single-spa provides application orchestration; enhanced Module Federation Runtime provides mf-manifest.json, loadRemote and hooks such as errorLoadRemote. Our demo uses its own simplified manifest, not the Module Federation format. Nx helps organize the project graph; Webpack, Rspack and Vite require the appropriate integration and version compatibility checks. [11][12][13][14][15][19][20]
Share only dependencies requiring a common instance or offering a measured benefit; singletons do not replace compatibility tests. For SSR, pin the same release and initial data on server and client, avoid double hydration, and never execute untrusted remote scripts on the server. The nextjs-mf documentation lists App Router as unsupported and Next.js support as ending; do not transfer the webpack configuration to App Router without verification. [3][16][21]
Choosing an architecture and tools in 2026
| Scenario | Preferred approach | Condition or trade-off |
|---|---|---|
| One team, shared releases | Modular monolith | Enforce domain boundaries and dependency direction |
| Multiple teams, distinct product areas | Route-level integration | Acceptable navigation boundaries and consistent shell |
| Independent fragments within one view | Native ESM or Module Federation | Versioned contracts, dependency control and fallback |
| Multiple independent SPAs | single-spa with ESM and import maps | Defined mount and unmount lifecycle |
| Public site with important SSR needs | Server-side composition or route split | Compatible versions, caching and hydration strategy |
| Code with different trust levels | Sandboxed iframe on a separate origin | Least privilege and message validation |
There is no single mandatory micro-frontend implementation standard. In 2026 a modular monolith remains a sensible starting point for new products without an independent deployment requirement. When that requirement exists, consider route-level integration first; use within-view composition where seamless integration is necessary. Choose tools by composition needs rather than framework popularity. [15][23][24]
Before migration, define measurable problems: shared-release wait time, the proportion of coordinated changes, recovery time and performance budgets. Compare a pilot against the baseline. Common CI/CD, contract, accessibility, security and telemetry standards remain necessary across autonomous teams. There is no universal team-count or application-size threshold. [23][25]
Operational standards and acceptance criteria
Assign owners to each domain, contract and manifest. In CI, test the current host against supported module releases, including unavailable assets, incompatible versions, latency and cleanup. Roll out gradually, monitor by release identifier and halt rollout when agreed error or latency thresholds are exceeded. Rolling back the pointer does not undo already executed code or an incompatible backend migration.
Set transfer and module-readiness budgets and monitor whole-page INP. Some cross-origin Resource Timing measurements require Timing-Allow-Origin, independently of CORS. OpenTelemetry can help correlation, but browser instrumentation remains experimental. Do not send tokens or personal data in telemetry. In the example the host updates the title and aria-current, moves focus to the heading on route changes, and keeps recovery independent of the error reporting sink. [17][18]
