Skip to content

Angular MFE advanced concepts: sharing, auth, errors

  • How shared dependency negotiation works, and what a remote built with another Angular minor actually does to a running shell.
  • Why every Angular upgrade is a coordinated release, and your options when one team cannot make the date.
  • How to version and test the contract between a shell and a remote.
  • Where authentication, authorization and Content Security Policy belong in a federated frontend.
  • How remotes share state without coupling, and how to attribute and observe failures per remote.

The setup pages get OrdersPortal and orders-mfe working together. Running a federated system for years is mostly a matter of governance and design: one Angular runtime across independently built apps, contracts that change safely, one sign-in, a locked-down list of code origins, little shared state, and errors attributed to the right team. Examples use Native Federation 22.2.5; the ideas apply to webpack Module Federation too.

Independent deployment is the reason micro frontends exist, and every concern on this page pushes against it. Sharing Angular couples upgrade schedules; every contract field becomes something that cannot change freely; shared state is coupling no import graph shows. Choose the smallest amount of coupling that still gives users one coherent product.

Each application’s federation config declares shared packages. The generated Native Federation config uses fromPackageJson({ singleton: true, strictVersion: true, requiredVersion: 'auto' }), which shares everything in package.json:

  • singleton: true: only one version of the package should be loaded. Angular packages, the router and anything holding global state (RxJS is usually included) must be singletons, otherwise the shell and remote get separate injectors and separate router instances.
  • strictVersion: true: the build records that the package must satisfy its requiredVersion. Whether the runtime enforces that at startup depends on runtime options, as the rehearsal below shows.
  • requiredVersion: 'auto': read the semver range from package.json, for example ^22.2.0.

To share only selected packages, use the fluent builder: fromPackageJson({...}).only([...]).override({...}). In 22.2.5 the older share helper is marked deprecated in the package typings in favor of exactly that form. For workspace libraries such as an internal design system, mappingsFromWorkspace shares path-mapped libraries.

At startup the runtime reads every remoteEntry.json listed in the manifest, compares the versions each build was compiled with, and writes an import map that decides which file each application’s @angular/core resolves to.

Semver compatibility is necessary but not sufficient for Angular. Code compiled by the Angular compiler calls internal runtime instructions. Angular’s versioning documentation describes compiler ABI stability across patch versions of the same minor, noting that this unblocks micro frontend use cases, and that ABI stability is not guaranteed across minor versions. The documentation also notes that the Angular team treats breakage as a regression but cannot validate every combination.

The rule: keep the shell and every remote on the same Angular minor and allow patch differences. A ^22.2.0 range in package.json is wider than that; consider ~22.2.0 for the Angular packages so requiredVersion: 'auto' says what you actually support.

To see the real behavior rather than the intended one, we built orders-mfe with Angular 22.1.8 and @angular-architects/native-federation 22.1.3, served it next to the 22.2.6 shell from Host application setup, and opened /orders/ord-1002 in headless Chrome. With the shell’s default initFederation options, nothing was reported at startup. The runtime loaded the remote’s own copy of Angular from the remote’s origin, the remote’s routes loaded, and the first component failed:

[console.error] ERROR T: NG0203
at iN (http://localhost:4201/_angular_core.qsGxg5mhu0.js:107:11)
...
at YS (http://localhost:4200/_angular_core.Wz6rTecDmZ.js:30:27834)
[main] <router-outlet></router-outlet>

Two _angular_core files from two origins appear in one stack, and the orders area renders nothing: not the fallback, because loadChildren succeeded. NG0203 (“inject() must be called from an injection context”) appears because the remote’s code runs on a second copy of Angular that knows nothing about the shell’s injection context. Even with debug logging on, the runtime reported no conflict.

The orchestrator also accepts strict: true in the initFederation options. With it, the same remote is rejected at startup:

[console.error] [NF][3]: [orders-mfe][@angular/common@22.1.8] Is not compatible with requiredRange '~22.1.0' of shared @angular/common@22.2.6.
[console.error] NFError: Could not determine shared externals in scope __GLOBAL__.
[pageerror] Could not determine shared externals in scope __GLOBAL__.

Now initFederation rejects, bootstrap.ts is never imported, and the whole shell is blank. Neither mode protects users: the default degrades one area silently, strict mode lets one team’s build take down the portal. Protection has to happen before deployment, in the remote’s contract check (Azure deployment, where the same 22.1.8 build fails). This is observed runtime behavior, not a documented guarantee; rehearse it again after every federation package upgrade.

Because shell and remotes must share one Angular minor, every Angular minor or major upgrade is a coordinated release across all teams, and the slowest team sets the date. Plan it like one:

  1. The platform team publishes the target versions (Angular, TypeScript, federation adapter, which track Angular’s minor) and a cutover date, and raises the contract check’s agreed minor on a branch.
  2. Each remote upgrades on a branch and runs against a preview shell on the new version, in its own preview environment.
  3. Cutover: all upgraded remotes and the upgraded shell deploy in one short, rehearsed change window; rollback redeploys the previous builds of all of them. With versioned paths and a separately hosted manifest (Azure deployment), remotes can be uploaded in advance and cutover and rollback are one manifest change.

There is only one production shell, so “the late remote stays on the old shell” is not an option. When a remote misses the date, choose explicitly:

Option How Cost
Wait The cutover moves until every remote is ready Every other team’s upgrade (and any feature that needs it) waits for the slowest team
Isolate the late remote Load it temporarily as a web component that bundles its own Angular runtime, outside the shared scope A second Angular download for that area, no shared injectors or router, a separate integration path to build and later remove
Parallel shell Run the old shell at a separate URL for a defined window, linking users to it for the late area Two shells to deploy, monitor and secure; navigation between them is a full page load

Write the chosen option and its end date into an architecture decision record. An exception without an end date becomes a second platform.

The contract between shell and remote is everything one side assumes about the other:

  • The exposed key (./routes) and export name (ORDERS_ROUTES).
  • Providers the remote expects from the shell (HttpClient, withComponentInputBinding(), a session client).
  • Route parameters, query parameters and events the remote reads or emits.
  • The Angular minor, and the CSS custom properties or design-system version the remote relies on.

Treat it like a public API:

  • Write it down in the remote’s README and the shell’s integration guide.
  • Test it where the change happens. The remote’s pipeline checks its build against the shell’s expectations (exposed keys, Angular minor), which the platform team owns; the shell’s pipeline reruns the check against deployed URLs as a smoke test.
  • Expand, then contract. Expose ./routes-v2 next to ./routes, ship the shell on the new key, and remove the old key only after the shell’s release has been live longer than any session. The deploy order is spelled out in Azure deployment.
  • Keep exposed modules self-contained. A provider moved into the remote’s app.config.ts silently disappears in the shell, because that file never runs there.

This is the section’s single full treatment of auth. Sign-in happens once, in the shell; remotes never run their own sign-in flows or hold refresh tokens, because separate token caches drift apart.

A workable split:

  • The shell runs the OpenID Connect flow (or uses platform authentication such as Azure Static Web Apps’ built-in providers) and owns the session.
  • The shell shares a small session client as a shared singleton library (for example @orders-portal/session), with methods like currentUser() and getAccessToken(audience). Remotes inject it; they never read storage directly.
  • Remotes call their own APIs with tokens scoped to those APIs. An HttpClient interceptor in the shell, or one provided in the remote’s routes, attaches them.
// Fragment: a remote route that requires a role, for UX only.
{
path: 'refunds',
canMatch: [() => inject(SessionClient).hasRole('orders-refunds')],
loadComponent: () => import('./refunds').then((m) => m.Refunds),
}

The guard above only hides a page. Angular’s route guard guide states that client-side guards must never be the sole source of access control, because any JavaScript in the browser can be modified by the user, so the Orders API checks the token and permission on every refund request. Static Web Apps role rules are no stronger: they secure only requests the platform serves. Client secrets, write-capable API keys and connection strings belong on servers, never in the browser.

The shell’s Content Security Policy is the list of origins allowed to run code in your users’ browsers. Three directives and one build setting matter, and each was rehearsed against production builds with a CSP header on the shell:

  • script-src must name every remote origin and blob:. In shim mode, es-module-shims runs rewritten modules from blob: URLs; its README offers a nonce or blob:, and static hosting cannot issue per-response nonces. Without blob: the shell never started: Loading the script 'blob:http://localhost:4200/...' violates the following Content Security Policy directive: "script-src 'self' http://localhost:4201".
  • connect-src must name every remote origin, because remoteEntry.json is fetched with fetch(). Without it the shell started but the area fell back: Connecting to 'http://localhost:4201/remoteEntry.json' violates the following Content Security Policy directive: "default-src 'self'", then NFError: Remote 'orders-mfe' is not initialized. Add your API origins here too.
  • style-src needs 'unsafe-inline' (or a nonce through Angular’s CSP_NONCE) because Angular inserts component styles as <style> elements.
  • No inline scripts in index.html. When the shell has global styles, the production build’s critical-CSS inlining adds an inline <script> that switches the stylesheet link from media="print" to all. With one rule in styles.css, Chrome blocked it (Executing inline script violates the following Content Security Policy directive 'script-src ...') and the global styles never applied. Set "optimization": { "styles": { "inlineCritical": false } } for the shell’s production build, as in Azure deployment, Step 2; allowing the script’s sha256 hash also works but must be rechecked after every upgrade.

With critical-CSS inlining off, the policy that rendered the orders pages, global styles included, was default-src 'self'; script-src 'self' http://localhost:4201 blob:; connect-src 'self' http://localhost:4201; style-src 'self' 'unsafe-inline'. On Static Web Apps, set it in the shell’s globalHeaders (Azure deployment, Step 2), with the production remote origins in place of localhost:4201.

Anyone who can deploy to a remote’s origin or edit the manifest can run code with the shell’s session, so a remote is as trusted as the shell. Protect deployment tokens and manifest changes like production credentials, list origins exactly, and remove an origin when its remote leaves the manifest.

The best shared state is none. In order of preference: the URL (route and query parameters are shared, bookmarkable and survive reloads); backend state (two remotes that need the same data both fetch it from the API that owns it); a small shared singleton service for genuinely cross-cutting client state such as the current user or feature flags, published as a versioned library with read-only signals; and browser events for loose notifications between remotes that must not depend on each other:

// Fragment: typed custom events through the window.
export interface CartUpdatedDetail { itemCount: number }
window.dispatchEvent(new CustomEvent<CartUpdatedDetail>('orders:cart-updated', { detail: { itemCount: 3 } }));
window.addEventListener('orders:cart-updated', (e) => {
const { itemCount } = (e as CustomEvent<CartUpdatedDetail>).detail;
console.log(itemCount);
});

Remove listeners in DestroyRef.onDestroy, and avoid a global store that every remote writes to: it recreates a monolith’s coupling without its compiler checks.

Angular 21 and later create zoneless applications by default, and the shell’s bootstrap decides change detection for every remote component it renders. A remote that relies on Zone.js to notice setTimeout or third-party callbacks can stop updating inside a zoneless shell. Make remotes zoneless-compatible (signals, OnPush, async pipe or toSignal) and test them inside the real shell.

Three hooks see federated failures, and each should report which remote and which build was involved:

  • Remote load failures reach the .catch on the shell’s loadChildren (Host application setup, Step 2).
  • Lazy-file failures inside a loaded remote reach withNavigationErrorHandler (Host application setup, Step 3); a spike after a release means old files are not being kept.
  • Runtime errors reach Angular’s ErrorHandler.

To attribute a runtime error, take the first stack frame that is not a shared package and see whose folder it comes from. Shared files must be skipped because the runtime may serve @angular/core or rxjs from any build’s folder, so an _angular_core.<hash>.js frame on the remote’s origin says nothing about the cause. Each remoteEntry.json lists its shared bundles (shared[].entries) and their chunks (every chunks group except mapping-or-exposed):

// Which remote does an error belong to? The first stack frame outside shared packages decides.
// Shared files are skipped: the runtime may serve @angular/core or rxjs from any build's folder.
import { readFileSync } from 'node:fs';
// Shared bundles and their chunks, as listed in a remoteEntry.json.
export function sharedFiles(entry) {
const files = entry.shared.flatMap((s) => Object.values(s.entries ?? {}));
for (const [bundle, list] of Object.entries(entry.chunks ?? {})) {
if (bundle !== 'mapping-or-exposed') files.push(...list);
}
return files;
}
export function remoteFromStack(stack, manifest, shared) {
const folders = Object.entries(manifest).map(([name, url]) => [name, new URL('.', url).href]);
for (const line of stack?.split('\n') ?? []) {
const url = line.match(/https?:\/\/[^\s)]+?(?=:\d+:\d+)/)?.[0];
if (!url || shared.has(url.split('/').pop())) continue;
return folders.find(([, folder]) => url.startsWith(folder))?.[0] ?? 'shell';
}
return 'shell';
}
const manifest = { 'orders-mfe': 'http://localhost:4201/remoteEntry.json' };
const shared = new Set(
['orders-mfe', 'orders-portal'].flatMap((n) => sharedFiles(JSON.parse(readFileSync(`${n}.remoteEntry.json`, 'utf8')))),
);
console.log(remoteFromStack(`TypeError: Cannot read properties of undefined (reading 'total')
at OrderDetail_Template (http://localhost:4201/order-detail-G5LQHHY2.js:1:412)
at Xs (http://localhost:4201/chunk-64CAAZOI.js:7:1022)`, manifest, shared));
console.log(remoteFromStack(`TypeError: x is not a function
at a (http://localhost:4201/_angular_core.Wz6rTecDmZ.js:30:100)
at b (http://localhost:4200/main-B7XZPPUS.js:1:200)`, manifest, shared));

Saved as attribute.mjs next to copies of the remote’s and shell’s production remoteEntry.json (as orders-mfe.remoteEntry.json and orders-portal.remoteEntry.json) and run with Node.js 22, it prints the owners. chunk-64CAAZOI.js is listed under browser-angular_core, so it is skipped although its name looks like application code:

orders-mfe
shell

In the browser, the shell fetches those remoteEntry.json files once after startup. A custom ErrorHandler then reports with the owner attached; the fragment uses @microsoft/applicationinsights-web 3.4.6, whose trackException(exception, customProperties) takes extra properties (@opentelemetry/sdk-trace-web 2.12.0 is the vendor-neutral alternative):

// Fragment: shell-wide ErrorHandler that tags errors with the remote and its build.
@Injectable()
export class RemoteAwareErrorHandler implements ErrorHandler {
private readonly manifest = inject(FEDERATION_MANIFEST); // the parsed manifest, provided at bootstrap
private readonly shared = inject(SHARED_FILES); // Set of shared file names from every remoteEntry.json
handleError(error: unknown): void {
const remote = remoteFromStack(error instanceof Error ? error.stack : undefined, this.manifest, this.shared);
appInsights.trackException({ exception: error as Error }, { remote, build: buildIdOf(remote) });
console.error(error);
}
}

For buildIdOf, each remote’s pipeline writes a version.json (commit SHA, build time) next to remoteEntry.json with no-cache, read once per remote. Initialize telemetry once, in the shell: Microsoft Learn warns that several versions of the Application Insights JavaScript SDK on one page can fail during initialization. A rise in load or lazy-file failures right after a remote release is the rollback signal.

Remotes should cost nothing until their route is visited, beyond their remoteEntry.json. Use the preloadRemoteModule function returned by initFederation only for likely next steps (for example when the user hovers the Orders link), and treat two _angular_core files from different origins in the Network panel as a failed share, as in the skew rehearsal.

Decision Option A Option B Choose A when
Expose shape Routes Single component The remote owns a whole area
Angular sharing Singleton, same minor everywhere Web component with its own runtime You can coordinate upgrades (almost always)
Remote URL Stable root URL, rollback by redeploying Immutable versioned paths, rollback by manifest edit Your host replaces files on deploy (Static Web Apps) and simplicity matters more than instant pinning
Runtime strictness Default, plus a contract check in CI strict: true at startup Always A: strict mode turns one bad remote into a full outage
Cross-remote state URL and backend Shared singleton service The data has an owning API
Auth Shell signs in, shared session client Each remote signs in Always A
Federation tool Native Federation webpack Module Federation New Angular 22 system on esbuild
  • Version skew and deployments under open tabs are covered above and in Azure deployment.
  • A provider moves. The remote moved a service from route providers to its app.config.ts, which never runs in the shell. The shell’s end-to-end tests against a preview environment catch this.
  • The manifest or CSP is wrong in one environment. Treat both as reviewed configuration and smoke-test each environment after changing them.
  • Ownership gaps. Nobody owns the shared design system or the federation upgrade. Fund a platform team before adding the third remote.

For one shell and one remote owned by the same team, skip versioned storage, contract tests and a shared session library; a lazy-loaded library in one application is cheaper. Do not use web components with separate runtimes to dodge upgrade coordination unless you have measured the extra download.

“One remote needs Angular 22.3 for a feature; the others are on 22.2.” ABI stability is promised only across patches, so the shell and all remotes move to 22.3 together, or the eager remote waits. The platform team sets a cutover date, every remote validates against a 22.3 preview shell, and the contract check’s agreed minor changes on the cutover day. If one remote cannot make it, choose openly between waiting, isolating it as a web component with its own runtime, or a time-boxed parallel shell, and record the end date.

“After a release, errors only come from tabs that were left open over lunch.” Those tabs hold the previous remoteEntry.json and request hashed files the deployment deleted; Static Web Apps keeps nothing from the previous deployment. Fix the host side by carrying the previous release’s files into the upload (or moving to storage that keeps releases), and the client side by reloading once when a lazy file fails to fetch. Verify with a rehearsal that deploys under an open tab.

“The orders remote broke in production at 10:02. What happens next?” The shell rendered its fallback for /orders (or, for errors inside loaded pages, the error handler tagged them orders-mfe with the build ID). Monitoring showed the spike against the new build, and the on-call engineer rolled back by running the remote’s workflow manually with the last good release tag; the shell was not redeployed. With versioned paths and a separately hosted manifest, the rollback would instead be a reviewed one-line manifest change.

“A team proposes turning on strict version checking at runtime to be safe.” In our rehearsal strict mode refused the mismatched remote at startup and left the entire shell blank. That trades a degraded area for a full outage. Keep runtime defaults, enforce the agreed minor in the remote’s pipeline, and alert on duplicated Angular files.

  • Keep Angular on one minor across shell and remotes; a skewed remote fails at runtime, silently by default and for everyone with strict: true.
  • Every Angular upgrade is a coordinated release gated by the slowest team; decide in advance what happens to a team that misses the date.
  • Enforce the contract in the remote’s pipeline and change it with expand-then-contract.
  • Sign in once in the shell; enforce authorization on the server, never in guards alone.
  • The shell’s CSP is the list of origins allowed to run code; it needs each remote origin and blob:.
  • Tag every error with the remote and its build, and initialize telemetry once in the shell.