Catalog My learning Blog
Micro-Frontends Course: React, Import Maps and Teams · Phase 2 · Lesson 6 · 6 min read

Micro-Frontend Shell and Routing

On this page
  1. What the shell owns
  2. Map URL prefixes to micro-frontends
  3. Load, mount and swap
  4. Navigation and the back button
  5. Start shared pieces without depending on them
  6. Preload what's likely next
  7. Check yourself

What the shell owns

The shell, also called the host or container, is the first code that runs. It has a short job description:

  • the HTML page and the import map,
  • the shared layout, such as where the header and main content go,
  • top-level routing: which micro-frontend owns which URL prefix,
  • loading, mounting and unmounting micro-frontends,
  • what happens when one of them fails.

Everything else belongs to the teams. A shell with business logic in it is the old monolith wearing a disguise.

Map URL prefixes to micro-frontends

Each micro-frontend owns a URL prefix, and everything under it:

TypeScript
type Route = { prefix: string; app: string };

const routes: Route[] = [
  { prefix: '/cart', app: '@shop/cart' },
  { prefix: '/account', app: '@shop/account' },
  { prefix: '/', app: '@shop/catalog' },            // catch-all goes last
];

function match(pathname: string) {
  return routes.find((r) =>
    r.prefix === '/' || pathname === r.prefix || pathname.startsWith(r.prefix + '/'),
  )!;
}

The shell only knows the first segment. /account/settings and /account/orders/17 both go to the account micro-frontend, which handles its own sub-routes however it likes, with React Router, TanStack Router or plain code. That's two-level routing: the shell routes between teams, and each team routes inside its own area.

The pathname.startsWith(r.prefix + '/') check matters. A plain startsWith('/cart') would also send /cartography to the cart.

Load, mount and swap

TypeScript
const outlet = document.getElementById('outlet')!;
let current: { app: string; unmount: Unmount } | null = null;
let navToken = 0;

async function render() {
  const route = match(location.pathname);
  if (current?.app === route.app) return;     // same team: it handles its own sub-route

  const token = ++navToken;
  current?.unmount();
  current = null;
  outlet.innerHTML = '<p aria-busy="true">Loading…</p>';

  try {
    const mod: { mount: Mount } = await import(route.app);
    if (token !== navToken) return;           // the user navigated again while this loaded
    const el = document.createElement('div');
    outlet.replaceChildren(el);
    current = { app: route.app, unmount: mod.mount(el, props(route.prefix)) };
  } catch (err) {
    if (token !== navToken) return;
    console.error(`[shell] failed to load ${route.app}`, err);
    outlet.innerHTML = '<p role="alert">This section is unavailable right now. Please try again later.</p>';
  }
}

Three details make it robust:

  • Unmount before mount. The old micro-frontend cleans up before the new one starts. In the lab, the catalog's DOM was gone once the cart was shown.
  • The navigation token. Loading takes time. If the user clicks "Cart" and then "Account" before the cart loads, the stale cart load must not mount over the account page. Each render takes a number, and only the latest one may mount.
  • A fallback on failure. If a micro-frontend's file is missing or throws while loading, the shell shows a message in that area only. The header and everything else keep working.

Navigation and the back button

The shell owns history.pushState for top-level changes and listens for popstate, which fires on back and forward:

Shell
export function navigate(to: string) {
  history.pushState(null, '', to);
  render();
}

window.addEventListener('popstate', render);

Micro-frontends get navigate through their props (Day 4) and call it for links that leave their area. For links *inside* their area, like /account/orders, they can use their own router, as long as it also uses the browser's history. Then popstate reaches everyone: the shell sees that the prefix is unchanged and does nothing, and the account micro-frontend's router updates its view.

In the lab, going from / to /cart and pressing back showed the catalog again, and opening /account/settings directly, a deep link, loaded the shell, matched /account and let the account micro-frontend render its "settings" section.

The server must answer every app URL with the shell's HTML, so deep links and reloads work. A catch-all route that returns the page does it, as long as file requests like /cart/cart.3TEMG4IL.js are served first.

Start shared pieces without depending on them

Some micro-frontends run on every page, like the header. The shell starts them at boot. Be careful not to make the whole shell depend on them:

JavaScript
const [header, cart] = await Promise.allSettled([import('@shop/header'), import('@shop/cart')]);
if (header.status === 'fulfilled') header.value.mount(document.getElementById('header')!, props('/'));
else console.error('[shell] header unavailable', header.reason);
if (cart.status === 'fulfilled') cart.value.init?.();
render();

An earlier version of the lab used Promise.all here. Pointing the import map at a missing cart file then broke the *entire* shop, including pages that didn't show the cart. With allSettled, the catalog kept working, and only the /cart page showed the "unavailable" message.

Preload what's likely next

Loading a micro-frontend on first visit costs a round trip. When it's likely the user goes there next, ask the browser to fetch it early:

Code
<link rel="modulepreload" href="/cart/cart.3TEMG4IL.js">

Or preload on intent, such as when the pointer hovers over the cart link, by calling import('@shop/cart') and ignoring the result. The module is then cached and the actual navigation is instant.

TipKeep the route table in configuration served with the import map, not hard-coded in the shell. Then a team can add a new section like /wishlist by deploying their micro-frontend and one config change, without a shell release.

Check yourself

So each team owns everything under its prefix. The account team can add /account/orders or redesign its sub-routes without a shell change, because the shell only decides that /account belongs to them. That's two-level routing: the shell routes between teams, each team routes inside its area.

A slow-loading micro-frontend from an earlier click could finish after a later navigation and mount over the wrong page. The token lets only the latest navigation mount.

The whole shell fails to start, so every page breaks. Use Promise.allSettled so a failed optional piece is logged and the rest of the site still works.

Match the prefix exactly or as a path segment: pathname === '/cart' || pathname.startsWith('/cart/'). That's what the lesson's match function does. Small routing bugs like this send users to the wrong team's code, which then shows a confusing not-found page.

A catch-all that answers every app URL with the shell's HTML. On reload the browser asks the server for /account/settings, and unless the server returns the shell page there, it 404s. Serve real files first, then fall back to the shell for every other GET.