Micro-Frontends with Module Federation in Next.js
Micro-frontends are an organisational decision dressed as a technical one. The reason to split a frontend across independently deployed applications is that separate teams need to ship on their own schedule without coordinating releases â not that the bundle was large, and not that the framework was slow. Teams that adopt the pattern for the second-order benefits usually end up with all the operational cost and none of the autonomy, because the coordination they were trying to escape simply moves from release day to build configuration.
This lesson covers the honest trade, how module federation loads code at runtime, what must be shared as singletons, and the questions you have to answer before the first remote goes up.
Prerequisites
- !Webpack configuration basics
- !React component and module boundaries
- !How a Next.js build produces chunks
What You'll Learn
- 1Argue for or against a split with concrete criteria
- 2Configure a host to consume remote entry points at runtime
- 3Share React and its peers as true singletons
- 4Plan routing and state across independently deployed apps
The case for and against
Splitting pays when the boundaries are real: a monorepo where three teams merge into one deployment pipeline, a gradual migration where a legacy application must be replaced one route at a time, or an acquisition where two codebases cannot be rewritten. It costs in ways that only appear later â every shared component becomes a versioning problem, debugging crosses process boundaries, and performance work has to consider several independently loaded bundles.
| Approach | Team autonomy | Runtime complexity | Best fit |
|---|---|---|---|
| Single app, modular monorepo | Low to medium | None added | One team, cohesive domain |
| Module federation | High | Runtime loading, shared versions | Independent teams on one surface |
| Server-side composition | Medium | Edge logic, careful caching | Personalised shells, SEO |
| iframe composition | High | Isolation is total | Truly legacy or third-party UI |
The test worth applying before committing: can you name two teams today whose deploy cadence is blocked by each other? If not, a well-factored single application with clear module boundaries gives you most of the benefit for none of the infrastructure.
Loading a remote at runtime
Module federation turns an import into a network request resolved when the module is needed. The host declares where the remote's entry file lives, and the bundler rewrites import('shop/ProductGrid') into a lookup against that entry rather than a static inclusion in the host bundle.
// host/next.config.js â webpack container plugin
const { ModuleFederationPlugin } = require('webpack').container;
module.exports = {
webpack(config, { isServer }) {
config.plugins.push(
new ModuleFederationPlugin({
name: 'host',
remotes: {
shop: 'shop@https://shop.example.com/_next/static/chunks/remoteEntry.js',
cart: 'cart@https://cart.example.com/_next/static/chunks/remoteEntry.js',
},
shared: {
react: { singleton: true, requiredVersion: '^18.0.0' },
'react-dom': { singleton: true, requiredVersion: '^18.0.0' },
},
})
);
// The server build cannot fetch browser chunks the same way.
if (!isServer) {
config.output.publicPath = 'auto';
}
return config;
},
};
Once configured, consuming a remote is an ordinary dynamic import wrapped in a boundary that can fail:
// host/app/shop/page.js
import { Suspense, lazy } from 'react';
const ShopApp = lazy(() => import('shop/ShopApp'));
export default function ShopPage() {
return (
<Suspense fallback={<div className="h-64 animate-pulse rounded bg-slate-100" />}>
<ShopApp />
</Suspense>
);
}
The failure path deserves as much thought as the happy one. A remote that is deployed, rolled back, or simply slow will reject that import, and an unhandled rejection renders a blank region with no explanation. A dedicated error boundary that names the affected area and offers a retry is the difference between a partial outage and a perceived total one.
Singletons: the versions that must match
If the host and a remote each ship their own copy of React, two React instances exist in one page: separate hook state, separate contexts, and a Context.Provider in the host that is invisible to the remote. Declaring React a singleton forces one copy, negotiated by version range at load time, and it is not optional â it is the difference between a working composition and an unexplainable blank component.
shared: {
react: { singleton: true, requiredVersion: '^18.2.0', eager: false },
'react-dom': { singleton: true, requiredVersion: '^18.2.0' },
'next/router': { singleton: true },
'@acme/design-system': { singleton: true, requiredVersion: '2.4.1' },
}
The corollary is that everything crossing an app boundary must be serialisable and version-compatible. A design system shared as a singleton means a remote cannot be deployed against a major version the host does not have yet, so the shared package needs a versioning policy with at least a compatibility range â which is the point where an npm registry and a release process become part of your frontend architecture.
Routing across two applications
Each federated app believes it owns its routes, so someone has to decide who wins. Three arrangements are common: the host owns all navigation and the remotes are mounted as components, the remotes own disjoint path prefixes and the host only dispatches, or each app has its own router and the host synthesises navigation between them. The first is simplest and covers most cases; the third is where teams accumulate subtle bugs around history state and scroll restoration.
Whichever you choose, one invariant must hold: a single URL has exactly one owner. Two remotes answering /checkout produce a race that resolves differently depending on load order. Publish the route ownership table as a document the teams agree on, and enforce it with a build check if you can, because the failure mode is a silent one.
State follows the same discipline. Do not try to share a global store object across the boundary â share events and small serialised snapshots instead: an auth state published by the host as a context prop, a cart updated by a custom event or a shared module, a URL as the source of truth for filters. Anything requiring a shared mutable reference will eventually be the thing that pages at 3 a.m.
Deploying a remote without breaking the host
Federation turns a deploy into a runtime contract change. The host fetches the remote's entry file when the route is first needed, and everything that entry file then requests must still exist with compatible exports. Two consequences follow that teams discover exactly once each.
First, the entry file must never be cached for long. It is the only thing that tells the host which chunk hashes to request next, so a CDN holding an old copy sends the host on a path to assets that a later build has already deleted â the classic white screen that appears only for users who have the cached copy. Serve remoteEntry.js with a short s-maxage or no-cache, and let the hashed chunks behind it carry the long-lived immutable headers, because they are content-addressed and never change meaning.
Second, a breaking change to a shared interface needs an overlap window rather than a flag day. If the host passes a new prop to a remote, ship the remote so it accepts both shapes first, then ship the host, and only afterwards remove the old path. The same applies in reverse when a remote stops exporting something. Treating the interface as a versioned API with a deprecation period is the difference between a controlled rollout and a Saturday spent bisecting deploys.
Watching a composition in production
When three applications render one page, "is it up" stops being a single question. The instrumentation that answers it is small: record which remote version served each request, attach the route name to client errors, and measure the loading time of each lazy boundary separately from the rest of the page.
// host/components/remote-boundary.jsx
'use client';
import { Suspense, lazy } from 'react';
import { ErrorBoundary } from 'react-error-boundary';
export function RemoteBoundary({ name, load, fallback }) {
const Loaded = lazy(load);
return (
<ErrorBoundary
onError={(error) => {
// Name the remote so the alert lands in the owning team's tracker.
report({ component: `remote:${name}`, message: error.message });
}}
fallbackRender={() => (
<div role="alert">
<p>The {name} section is temporarily unavailable.</p>
<button onClick={() => window.location.reload()}>Reload</button>
</div>
)}
>
<Suspense fallback={fallback}>
<Loaded />
</Suspense>
</ErrorBoundary>
);
}
Error boundaries that name the failing remote turn a vague "something on checkout is broken" into a page in the right team's tracker. Add the remote version to that payload and the first question in any incident â which release was live â answers itself.
Common Mistakes
Adopting micro-frontends to reduce bundle size
Fix: Code splitting and dynamic imports solve bundle size without a runtime; save federation for team autonomy you actually need.
Leaving React out of the shared singleton list
Fix: Two React copies mean two hook states and contexts that do not connect â always share it as a singleton.
Letting two remotes answer the same path
Fix: Assign each URL an owner in a published table and check it in the build.
Swallowing a failed remote import
Fix: Wrap lazy remotes in an error boundary with a retry so a deploy failure degrades visibly instead of silently.
Best Practices
- Start with one host and one remote; add splits only when a second team needs the autonomy
- Version shared packages with an explicit compatibility range and a release process
- Keep the auth and shell concerns in the host so remotes receive identity as props
- Log which remote version served each request â the first question in any incident
Interview Questions
Q1: What problem do micro-frontends actually solve?
They let independently owned teams build and deploy parts of one user-facing surface without coordinating releases. They do not inherently improve performance or code quality.
Q2: Why must React be a singleton in the federation config?
Otherwise two React instances load in the same page, producing separate hook state and contexts, so a provider in the host is invisible to the remote.
Q3: What is the biggest routing risk with federated apps?
Two remotes claiming the same URL, which makes the rendered result depend on load order and produces hard-to-reproduce navigation bugs.
Key Takeaways
- Split for team autonomy, not for bundle size or fashion; the costs appear after the first split.
- Module federation resolves an import against a remote entry file at runtime, so failures are possible and need boundaries.
- React, the router, and your design system must be shared singletons with agreed version ranges.
- Give every URL exactly one owner and pass cross-app state as serialised values or events.
- Version discipline and observability are part of the architecture, not optional extras.