Skip to content

Angular MFE host setup: build the shell application

You will turn orders-portal into the shell of the OrdersPortal system. It initializes Native Federation from a runtime manifest, passes the federation loader into a standalone bootstrapApplication call, mounts the orders-mfe routes under /orders with loadChildren, shows a fallback with a reload button if the remote cannot be reached, and reloads once when a remote was redeployed under an open tab. You will also set up per-environment manifests and decide what the shell (and only the shell) is responsible for.

The remote side is on Remote configuration. This page assumes orders-mfe already exposes ./routes.

How to run the samples: files go in projects/orders-portal/src/ (or src/ if the shell is the workspace’s root project). Run the remote with npx ng serve orders-mfe and the shell with npx ng serve orders-portal, then open http://localhost:4200/orders. Every sample on this page was built with Angular 22.2 and @angular-architects/native-federation 22.2.5 and rendered in headless Chrome (driven by Playwright) against production builds of both apps.

Before writing code, agree on what belongs in the shell. A shell that grows business features becomes the monolith you were trying to leave.

The shell owns:

  • The frame: header, navigation, footer, global error and “not found” pages.
  • Top-level routing: which URL prefix belongs to which remote.
  • Sign-in and the session: obtaining tokens and making the current user available to remotes through a small, documented contract.
  • Cross-cutting providers: HttpClient with interceptors, router features the remotes rely on (such as component input binding), global error listeners.
  • The remote manifest: which remote build each environment uses.

The shell does not own business pages, business state or remote-specific services. Those live in remotes.

Step 1: Initialize federation, then bootstrap

Section titled “Step 1: Initialize federation, then bootstrap”

The schematic generated a main.ts that initializes federation and then imports bootstrap.ts. Change it so the result of initFederation is passed to the bootstrap function:

src/main.ts
import { initFederation } from '@angular-architects/native-federation';
initFederation('federation.manifest.json', {
hostRemoteEntry: { url: './remoteEntry.json' },
})
.then((federation) => import('./bootstrap').then((m) => m.bootstrap(federation)))
.catch((err) => console.error(err));
src/bootstrap.ts
import { bootstrapApplication } from '@angular/platform-browser';
import type { NativeFederationResult } from '@angular-architects/native-federation';
import { createAppConfig } from './app/app.config';
import { App } from './app/app';
export function bootstrap(federation: NativeFederationResult) {
return bootstrapApplication(App, createAppConfig(federation.loadRemoteModule));
}

Why pass the loader instead of importing loadRemoteModule directly? In version 22.2.5 the package still exports a top-level loadRemoteModule, but its typings mark it deprecated: it relies on a module-scoped federation instance and resolves only against the most recent initFederation call, which the maintainers describe as brittle in tests and multi-host setups. The recommended form is the loadRemoteModule returned by initFederation. Passing it in as a function also makes the route table trivially testable, as Local testing shows.

The two-file split matters: initFederation must finish before any file that imports @angular/core is evaluated, because Angular is itself a shared package whose version is negotiated during initialization.

Verify: grep -c "@angular/core" projects/orders-portal/src/main.ts prints 0: nothing in main.ts loads Angular before federation is initialized. The files bootstrap.ts imports are created in Steps 2 and 3; build after Step 3.

Step 2: Build the route table from the loader

Section titled “Step 2: Build the route table from the loader”
src/app/app.routes.ts
import { Routes } from '@angular/router';
import type { LoadRemoteModule } from '@softarc/native-federation-orchestrator';
import { RemoteUnavailable } from './remote-unavailable';
export function createRoutes(loadRemoteModule: LoadRemoteModule): Routes {
return [
{ path: '', pathMatch: 'full', redirectTo: 'orders' },
{
path: 'orders',
loadChildren: () =>
loadRemoteModule<{ ORDERS_ROUTES: Routes }>('orders-mfe', './routes')
.then((m) => m.ORDERS_ROUTES)
.catch((err) => {
console.error('orders-mfe failed to load', err);
return [{ path: '**', component: RemoteUnavailable }];
}),
},
];
}
src/app/remote-unavailable.ts
import { ChangeDetectionStrategy, Component } from '@angular/core';
@Component({
selector: 'app-remote-unavailable',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<p role="alert">This area is temporarily unavailable.</p>
<button type="button" (click)="reload()">Reload the page</button>
`,
})
export class RemoteUnavailable {
// The router caches this fallback for the session; only a full reload retries the remote.
protected reload(): void {
location.reload();
}
}

@softarc/native-federation-orchestrator is the runtime the schematic added to package.json; importing its LoadRemoteModule type keeps the routes file free of any federation state.

How the pieces fit:

  • 'orders-mfe' is the key in federation.manifest.json and the name in the remote’s federation config. './routes' is the key in the remote’s exposes.
  • The generic type { ORDERS_ROUTES: Routes } documents the contract. It is not checked against the remote’s real code, because the remote is built separately; treat it as documentation plus a compile-time hint for the shell.
  • The .catch turns a failed remote into a route that renders RemoteUnavailable for any path under /orders. The URL stays as the user typed it.
  • The router caches what loadChildren resolves to for the rest of the session. Once the fallback routes are resolved, later in-app navigations to /orders keep showing the fallback, even if the remote comes back. Recovery needs a full page load, which is why the fallback offers a reload button instead of retrying automatically (no request storms against a failing host). This is the one place in the section that explains this behavior; other pages link here.
  • The same .catch also handles a tab that was opened before a remote deployment and navigates to /orders for the first time afterward: its in-memory remoteEntry.json names an exposed file (routes-<hash>.js) that may no longer exist.

Verify: npx tsc --noEmit -p projects/orders-portal/tsconfig.app.json exits without errors once Step 3 is in place; the fallback path itself is unit-tested in Local testing.

src/app/app.config.ts
import { ApplicationConfig, provideBrowserGlobalErrorListeners } from '@angular/core';
import { provideRouter, withComponentInputBinding, withNavigationErrorHandler } from '@angular/router';
import type { LoadRemoteModule } from '@softarc/native-federation-orchestrator';
import { createRoutes } from './app.routes';
import { reloadOnStaleChunk } from './stale-build';
export function createAppConfig(loadRemoteModule: LoadRemoteModule): ApplicationConfig {
return {
providers: [
provideBrowserGlobalErrorListeners(),
provideRouter(
createRoutes(loadRemoteModule),
withComponentInputBinding(),
withNavigationErrorHandler(reloadOnStaleChunk),
),
],
};
}
src/app/stale-build.ts
import { NavigationError } from '@angular/router';
const RELOADED_FOR = 'orders-portal:reloaded-for';
// A lazy file could not be fetched. After a deployment this usually means the tab
// still holds an older remoteEntry.json whose hashed files are gone.
export function isChunkLoadError(error: unknown): boolean {
return error instanceof TypeError && /fetch|not found|import/i.test(error.message);
}
export function reloadOnStaleChunk(event: NavigationError): void {
if (!isChunkLoadError(event.error)) return;
// Reload at most once per target URL, so a remote that is really down cannot cause a loop.
if (sessionStorage.getItem(RELOADED_FOR) === event.url) return;
sessionStorage.setItem(RELOADED_FOR, event.url);
location.assign(event.url);
}

What each provider is for:

  • withComponentInputBinding() is here because the orders remote’s detail page binds :orderId to an input. Every provider a remote expects from the shell is part of the shell–remote contract; list them in the remote’s README.
  • withNavigationErrorHandler(reloadOnStaleChunk) handles the case the route’s .catch cannot see: the remote’s routes are already loaded, the remote is redeployed, and the user then opens a page whose lazy file (order-detail-<hash>.js) was removed. That navigation fails inside the remote’s own loadComponent. The handler turns it into one full page load of the target URL, which fetches the new remoteEntry.json. Native dynamic import() failures and the es-module-shims loader (used in shim mode by Native Federation) both reject with a TypeError; in our rehearsal the message was 404 Not Found http://localhost:4201/order-detail-G5LQHHY2.js, and after the handler ran the new detail page rendered. Hosting that keeps the previous release’s files (see Azure deployment) avoids the reload entirely; the handler is the safety net.
  • In a real shell you would also add provideHttpClient(withInterceptors([...])) with an interceptor that attaches the access token to calls to your own APIs, and an ErrorHandler that tags errors with the remote they came from (Advanced concepts).

Verify: npx ng build orders-portal ends with “Application bundle generation complete.”

src/app/app.ts
import { Component } from '@angular/core';
import { RouterLink, RouterOutlet } from '@angular/router';
@Component({
selector: 'app-root',
imports: [RouterOutlet, RouterLink],
templateUrl: './app.html',
styleUrl: './app.css',
})
export class App {}
src/app/app.html
<header><a routerLink="/orders">Orders</a></header>
<main><router-outlet /></main>

Verify: with both apps running, http://localhost:4200/orders renders the order list from orders-mfe inside the shell’s <main>, and http://localhost:4200/orders/ord-1002 renders “Order ord-1002”. In the browser’s Network panel you see federation.manifest.json, then http://localhost:4201/remoteEntry.json, then the remote’s routes-*.js chunk only when you first navigate to /orders.

Stop the remote and reload /orders: the shell still loads and shows “This area is temporarily unavailable.” with the reload button. With version 22.2.5, an unreachable remote at startup did not prevent the shell from bootstrapping in our test; the console showed NFError: Remote 'orders-mfe' is not initialized. when the route tried to load it. The runtime does not retry a remote that failed during initFederation, which is one more reason the fallback asks for a full reload.

The generated src/app/app.spec.ts now fails: it renders App without a router (NG0201: No provider found for `ActivatedRoute`. Source: DynamicTestModule.) and expects a heading the frame no longer has. Replace it with a test of the frame, and do the same in the remote, whose root template is now <router-outlet />:

src/app/app.spec.ts
import { TestBed } from '@angular/core/testing';
import { provideRouter } from '@angular/router';
import { App } from './app';
describe('App', () => {
it('renders the frame with a link to the orders area', async () => {
TestBed.configureTestingModule({ imports: [App], providers: [provideRouter([])] });
const fixture = TestBed.createComponent(App);
await fixture.whenStable();
const link = (fixture.nativeElement as HTMLElement).querySelector('header a');
expect(link?.getAttribute('href')).toBe('/orders');
});
});

Run it once the test target is fixed as in Local testing. At this point it is the shell’s only spec file:

Terminal window
npx ng test orders-portal --watch=false --include=projects/orders-portal/src/app/app.spec.ts
Test Files 1 passed (1)
Tests 1 passed (1)

public/federation.manifest.json is copied verbatim into the build output, so the same shell build can point at different remotes in each environment. Keep one file per environment in the repository and copy the right one during deployment:

deploy/manifests/
dev.json { "orders-mfe": "https://orders-dev.example.test/remoteEntry.json" }
staging.json { "orders-mfe": "https://orders-staging.example.test/remoteEntry.json" }
prod.json { "orders-mfe": "https://orders.example.test/remoteEntry.json" }
Terminal window
cp deploy/manifests/prod.json dist/orders-portal/browser/federation.manifest.json

Each entry is the remote’s stable root URL. A normal remote release changes the files behind that URL, not the manifest, so the shell is not involved. A rollback is a redeployment of the previous remote build. This is the release model used throughout the section; Azure deployment explains it and describes the alternative (immutable versioned paths with a manifest hosted separately from the shell), which needs storage that keeps old releases.

Rules that keep this safe:

  • Build once, configure per environment. Never rebuild the shell just to change a remote URL; redeploy the same build with a different manifest.
  • Revalidate the manifest on every load. The caching rule (no-cache for fixed names, immutable for hashed files) is stated once, in Azure deployment.
  • Treat the manifest as configuration under change control. Whoever can edit it decides what code runs in your users’ browsers. Do not let it be supplied by query string or user input, and keep the shell’s Content Security Policy in step with it.

Verify: after npx ng build orders-portal and the copy command, cat dist/orders-portal/browser/federation.manifest.json prints the production entry.

The shell signs the user in and offers remotes a small session API (the current user and a way to get an access token for a given API); remotes never run their own sign-in flow. Route guards in the shell, such as a canMatch that hides /orders from users without an orders role, are user experience only: Angular’s route guard guide says client-side guards must never be the sole source of access control, so every API the remotes call validates the token and the user’s permission on the server. Never put secrets in the shell, a remote or the manifest; everything shipped to the browser is public. The full design (session client as a shared singleton, token scoping, where guards fit) is in Advanced concepts.

Verify: search the shell and remote build output for anything secret before the first deployment, for example grep -ril "client_secret\|apikey" dist/ returns nothing.

The shell’s src/ contains main.ts, bootstrap.ts, app/app.config.ts, app/app.routes.ts, app/stale-build.ts, app/remote-unavailable.ts, app/app.ts, app/app.html and the rewritten app/app.spec.ts exactly as shown. Production builds of both applications, served on ports 4200 and 4201, render the orders pages inside the shell, render the fallback with a reload button when the remote is stopped, and recover with one reload when the remote is redeployed under an open tab.

  • Blank page or shared-dependency errors right after editing main.ts. Check that main.ts imports nothing from @angular/* and reaches application code only through import('./bootstrap') after initFederation resolves. Restore the two-file structure.
  • /orders shows the fallback even though the remote is running. Open the manifest URL and the remoteEntry.json URL in the browser. A typo in the remote name, a wrong port or a CORS error (visible in the console) are the usual causes.
  • Deep links such as /orders/ord-1002 return 404 from the server after deployment. The shell’s host needs a single-page application fallback to index.html, while remoteEntry.json and .js files must not fall back. See Azure deployment.
  • The remote’s styles leak into the shell or vice versa. Use component-scoped styles and a shared design system; avoid global stylesheets in remotes.
  • TypeScript warns that loadRemoteModule is deprecated. You imported the top-level function. Use the one returned by initFederation, as in Step 1.
  • ng test fails with NG0201: No provider found for `ActivatedRoute` . The generated app.spec.ts renders App without a router. Replace it as shown after Step 4.
  • The page reloads once after a deployment and then works. That is reloadOnStaleChunk doing its job. If it happens after every remote release, the previous release’s files are not being kept; see Azure deployment.

Run both apps together and add tests in Local testing, then deploy in Azure deployment.