🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Micro-Frontends with Module Federation and single-spa

React ArchitectuređŸŸĸ Free Lesson

What You'll Learn

  • 1State the organisational conditions under which micro-frontends pay for themselves
  • 2Configure runtime module sharing so React is a singleton rather than a duplicate
  • 3Assign route ownership and handle a remote failing to load
  • 4Share authentication and state across independently deployed applications

Micro-frontends are an organisational decision disguised as a technical one. The reason to split a frontend is rarely performance or bundle size — a monolith with code splitting usually ships less code — and almost always that three teams cannot release independently, or that a two-year-old section of the application blocks every other change because nobody dares touch it. Once that is true, runtime integration lets each slice be built, tested and deployed on its own schedule, and the cost is a set of problems that simply do not exist in a single application: version drift, duplicated dependencies, route ownership, shared authentication, and debugging across a boundary you do not control.

Three ways to compose applications

Before choosing a tool, choose the integration style, because each one has a different blast radius when it goes wrong. Iframes give perfect isolation — styles, globals and failures cannot leak — at the cost of awkward routing, sizing and accessibility. Build-time composition means each application is a package consumed by a shell built once, which keeps deployment simple but means nothing is truly independent: one build still ships everything. Runtime composition loads each application's bundle when it is needed, which is where independence actually lives, and it is the model that module federation and single-spa implement.

StyleIsolationIndependent deployRoutingTypical cost
IframesCompleteYesManual synchronisationAccessibility, sizing, popups
Build-time packagesNoneNo, one build ships allSimpleCoupled release trains
Runtime federationShared runtimeYesShared router contractVersion and state coordination
Server-side includesNoneYesServer owns routesBackend complexity

Whatever you pick, agree on a contract before code: which routes each application owns, who renders navigation and layout, how a component signals an error, and what happens when a remote is unavailable. Teams that skip this end up with two applications both believing they own the header.

The shell owns routing, remotes own screens

The host application — the shell — is responsible for the document, the router, global providers, authentication and the frame the user sees. Each remote owns a route prefix and renders its own pages inside the frame. That split is what keeps the integration honest: a remote never manipulates the shell's DOM directly, never registers its own router history entry without telling the shell, and communicates through a documented interface of props and events.

Runtime federation in webpack 5 expresses this as configuration. The shell declares what it consumes; each remote declares what it exposes and what it expects to share.

javascript
// shell webpack.config.js
const { ModuleFederationPlugin } = require('webpack').container;

module.exports = {
  plugins: [
    new ModuleFederationPlugin({
      name: 'shell',
      remotes: {
        shop: 'shop@https://shop.example.com/remoteEntry.js',
        account: 'account@https://account.example.com/remoteEntry.js',
      },
      shared: {
        react: { singleton: true, requiredVersion: '^18.0.0' },
        'react-dom': { singleton: true, requiredVersion: '^18.0.0' },
        'react-router-dom': { singleton: true },
      },
    }),
  ],
};

// shop webpack.config.js
module.exports = {
  plugins: [
    new ModuleFederationPlugin({
      name: 'shop',
      filename: 'remoteEntry.js',
      exposes: {
        './ProductGrid': './src/ProductGrid',
        './routes': './src/routes',
      },
      shared: {
        react: { singleton: true, requiredVersion: '^18.0.0' },
        'react-dom': { singleton: true, requiredVersion: '^18.0.0' },
      },
    }),
  ],
};

The singleton flag is the setting people underestimate. Without it, the remote downloads its own copy of React, and two Reacts in one page produce duplicated contexts: the shell's theme provider is invisible to the remote, the remote's state provider is invisible to the shell, and hooks fail in ways that look like logic bugs. Required versions turn silent duplication into a visible negotiation failure at load time, which is far easier to debug.

Loading a remote without taking down the shell

Runtime composition means a remote can be slow, broken or incompatible at the moment a user navigates. Treat that as a normal condition rather than an exception: render a skeleton while the chunk loads, fall back to an error state that still lets the user reach other parts of the application, and never let a failed import unmount the shell itself.

import { Suspense, lazy, useEffect, useState } from 'react';

const ShopGrid = lazy(() => import('shop/ProductGrid'));

function RemoteBoundary({ name, children }) {
  const [failed, setFailed] = useState(false);

  useEffect(() => {
    const onError = (event) => {
      if (event.message && event.message.includes('Loading chunk')) setFailed(true);
    };
    window.addEventListener('error', onError);
    return () => window.removeEventListener('error', onError);
  }, []);

  if (failed) {
    return (
      <section role="alert">
        <h2>{name} is temporarily unavailable</h2>
        <button type="button" onClick={() => window.location.reload()}>
          Reload
        </button>
      </section>
    );
  }

  return <Suspense fallback={<div className="skeleton" aria-busy="true" />}>{children}</Suspense>;
}

export function App() {
  return (
    <main>
      <RemoteBoundary name="Shop">
        <ShopGrid />
      </RemoteBoundary>
    </main>
  );
}

Two operational habits belong here. Chunk loading can fail when a deploy replaces files while a user is mid-session, so a retry that refetches the entry point before declaring failure saves a reload. And the error state must be inside the shell's layout, because a full-page error from a remote reads as an outage of the whole product.

Versions, providers and the shared context problem

Sharing React is only the beginning. Anything passed across the boundary — a router, a design system, a query client, an analytics wrapper — has to be a singleton with an agreed version range, or the boundary becomes a place where behaviour silently differs. The discipline that keeps this manageable is a shared dependency manifest maintained centrally: remotes declare versions from it, a build check fails when a remote drifts, and upgrades happen as a coordinated release of the manifest rather than whenever one team bumps a package.

Context is the second trap. Even with a single React, a provider mounted in the shell is only visible to remotes that are rendered inside it, which is usually what you want for theme and authentication but not for a remote's private state. The rule of thumb is that the shell owns cross-application context and each remote owns its own, with an explicit prop contract for anything that crosses.

Authentication and navigation across boundaries

Authentication is the hardest shared concern because it is simultaneously global — one session for the user — and sensitive — no remote should see a token it does not need. The usual shape is a shell that holds the session, exposes the current user through context or a small handshake on load, and handles login and logout centrally so a remote never redirects the user to a login page the shell also renders.

Routing needs the same centralisation. If each remote pushes history entries independently, back-button behaviour becomes unpredictable and scroll restoration breaks. Prefer a shell-owned router where remotes export route definitions rather than calling navigation APIs, and agree on how query parameters are shared when two remotes both need a filter value from the URL.

Observability and testing across the seam

Debugging one application is a stack trace; debugging four is a timeline. Every remote should tag its logs and errors with its name and version, so a failure during navigation can be attributed to the shell or to the incoming chunk rather than guessed at. A single error tracking client configured by the shell and shared as a singleton keeps reports correlated.

Testing follows the same split. Unit tests live with each remote. Contract tests assert that a remote still exports the modules the shell imports and still renders inside a placeholder without throwing. A small end-to-end suite covers the seams — navigation between remotes, authentication hand-off, a remote failing to load — which is where the risk actually sits and where hand-written mocks would hide the real failure.

When the monolith is the right answer

Splitting costs coordination that a single team does not need. Every shared dependency becomes a negotiation, every cross-application feature becomes an interface, and a user-visible bug now requires reading logs from three repositories. If one team deploys once a week and the codebase fits in one head, code splitting plus a modular folder structure gives most of the architectural benefit at none of the integration cost.

The signal to split is repeated collision: two teams blocking each other on the same files, release trains that must be synchronised by calendar, or a legacy section that cannot be upgraded because it is welded to everything else. When that appears, split along the seam where the collisions happen, not along the shape of the current folders.

Common Mistakes

Sharing React without the singleton flag so two copies run on one page

Fix: Mark shared dependencies as singletons with explicit required versions

Letting a remote own global navigation and history

Fix: Keep routing in the shell and have remotes export route definitions

Rendering a remote failure as a full-page error

Fix: Contain it inside the shell layout with a retry and a way to keep navigating

Splitting because the pattern is fashionable rather than because teams are blocked

Fix: Split along organisational collision points and stay modular otherwise

Best Practices

  • Maintain one shared dependency manifest and fail the build when a remote drifts
  • Let the shell own session, theme and navigation providers
  • Tag logs and errors with the owning application and its version
  • Write contract tests for exported modules plus a few end-to-end seam tests
  • Prefer route-level code splitting before reaching for runtime composition

Key Takeaways

  • Micro-frontends buy independent release cadence and cost version, state and routing coordination
  • Runtime federation requires singletons for React and anything that carries context
  • The shell owns the document, router and session; remotes own their routes
  • Remote failure is an expected state and must degrade inside the shell layout
  • Split when teams collide repeatedly, not when the folder structure looks tidy
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert React Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement