Architect a cross-app shell with federated routing, deep link normalization, and…
- User
Architect a cross-app shell with federated routing, deep link normalization, and telemetry.
Assistant
Architect a cross-app shell with federated routing, deep link normalization, and telemetry.
The user wants to architect a "cross-app shell." Key requirements:
app-a/page maps correctly to the specific logic within App A, regardless of the host environment.Target Audience/Context: Senior Frontend Engineer or Architect. Tone: Professional, technical, structured, and practical.
Core Components to Design:
Step-by-Step Architecture Plan:
High-Level Diagram (Mental Model):
Federated Routing (The "Hard" Part):
React Router (assuming React as a default, but keep it slightly agnostic if possible, or explicitly state the stack) or a framework-agnostic router like single-spa or a custom solution using the History API.Deep Link Normalization:
host.com/app-a/details/123.app-a, load the federated module, pass /details/123 to it.Telemetry:
correlationId or sessionId from Shell to Remote.Drafting the Code Structure (Mental or Scratchpad):
App.tsx: Layout.Router.tsx: Main switch.RemoteLoader.tsx: Wrapper to load MF modules.track(event, payload)parse(url) -> { app, path, params }Refining the Architecture (Adding specific technologies):
Writing the Response - Structure:
Self-Correction/Review during drafting:
React.lazy isn't enough for federated routing. I need to show how to handle the unknown routes until they are registered.Final Polish: Ensure terminology (Host, Remote, Dynamic Remote, Scope, Module) is consistent with Module Federation.
(Self-Correction during output generation): Make sure to emphasize Dynamic vs Static federation. Dynamic is better for "Cross-App" shells where the shell doesn't necessarily hard-code the remote URLs at build time (though usually, it knows the name).
Let's build the solution using Module Federation + React (as the implementation vehicle) + Custom Routing Logic.
useDeepLink() or a utility UrlNormalizer.TelemetryProvider context.Let's write it out.
shell/bootstrap.tsxshared/RouterServiceshared/TelemetryClientOkay, ready to generate. This architecture defines a modern Micro-Frontend (MFE) Shell. This pattern decouples the "Shell" (the container, authentication, and navigation) from the "Apps" (feature logic), allowing independent deployment and technology agnosticism.
We will assume a web-based stack (React/TypeScript) using Webpack Module Federation or similar native import maps, but the architectural patterns apply broadly.
graph TD
User --> Browser
Browser --> Shell[Shell Container]
subgraph "Shell Layer (Orchestrator)"
Router[Federated Router] --> RouteRegistry[Route Registry]
DeepLink[Deep Link Normalizer]
TelemetrySDK[Telemetry SDK]
EventBus[Cross-App Event Bus]
end
subgraph "Remote Apps (Federated Modules)"
AppA[App A: Dashboard]
AppB[App B: Settings]
AppC[App C: Commerce]
end
Shell -->|Dynamic Import| AppA
Shell -->|Dynamic Import| AppB
Shell -->|Dynamic Import| AppC
AppA -->|Publish Events| EventBus
AppB -->|Emit Metrics| TelemetrySDK
DeepLink -->|Rewrites URL| Router
The Shell is minimal. It should contain no business logic. Its primary jobs are bootstrapping the runtime, providing the DOM anchor, and handling the top-level navigation chrome.
Core Interface Definition (shell.types.ts)
// A standard interface all Remote Apps must implement
export interface RemoteApplication {
id: string;
route: string; // e.g., '/settings'
load: () => Promise<void>;
mount: (el: HTMLElement, props: RootProps) => void;
unmount: (el: HTMLElement) => void;
}
// Context provided by Shell to Remotes
export interface ShellContext {
telemetry: TelemetryClient;
router: RouterProxy;
linkNormalizer: LinkNormalizer;
sharedState: SharedStateProxy;
}
In a standard SPA, the router knows all routes beforehand. In a Federated app, the Shell is unaware of the internal routes of the Remote Apps (e.g., /settings/profile vs /settings/account).
We use a Dynamic Route Registry.
The Registry (RouteRegistry.ts)
type RouteConfig = {
path: string;
remoteId: string;
exact?: boolean;
};
class RouteRegistry {
private routes: RouteConfig[] = [];
// Remotes call this on boot to register their sub-routes
register(config: RouteConfig) {
this.routes.push(config);
}
// The Shell Router uses this to find which bundle to load
match(pathname: string): RouteConfig | null {
return this.routes.find(r => pathname.startsWith(r.path)); // Simplified matching
}
}
The Router Implementation (ShellRouter.tsx)
Instead of static <Route /> components, the Shell uses a wildcard catcher that lazy-loads the bundle.
import React, { Suspense, lazy, useEffect } from 'react';
const RemoteLoader = ({ match }) => {
const { remoteId } = match.params;
// 1. Dynamic Import based on URL (Webpack Module Federation)
const RemoteApp = React.lazy(() =>
import(`${remoteId}/App`).catch(() =>
() => <div>Error: App not found</div>
)
);
return (
<Suspense fallback={<div>Loading System...</div>}>
<RemoteApp />
</Suspense>
);
};
// In the Shell's main Layout
<Routes>
<Route path="/" element={<Home />} />
<Route path="/auth/callback" element={<AuthHandler />} />
{/* The Federated Catch-All */}
<Route path="/:remoteId/*" element={<RemoteLoader />} />
</Routes>
Deep links often come from external sources (emails, push notifications) with legacy formats, marketing parameters (UTM), or specific IDs that map to different UI states based on user permissions.
The Logic:
Implementation (DeepLinkService.ts)
interface LinkRule {
match: RegExp;
resolve: (matches: RegExpMatchArray) => Promise<string>;
}
class DeepLinkNormalizer {
private rules: LinkRule[] = [];
registerRule(rule: LinkRule) {
this.rules.push(rule);
}
async normalize(rawPath: string): Promise<string> {
for (const rule of this.rules) {
const match = rawPath.match(rule.match);
if (match) {
const newPath = await rule.resolve(match);
console.log(`Normalized ${rawPath} -> ${newPath}`);
return newPath; // Return the clean internal path
}
}
return rawPath; // Return original if no rules match
}
}
// Usage Example in App A (Commerce)
// Input: /promo/item/v1?id=55
// Output: /store/products/55/details
normalizer.registerRule({
match: /\/promo\/item\/v1\?id=(\d+)/,
resolve: async (m) => {
const productId = m[1];
// Optional check: API call to check if product is active
return `/store/products/${productId}/details`;
}
});
Telemetry in a federated app must be hierarchical. The Shell provides the "Root" context (User ID, Session ID), and the Remotes provide the "Span" context (Feature interaction).
Architecture:
The Telemetry Facade (Telemetry.ts)
class TelemetryClient {
private context: Record<string, any> = {};
constructor(userInfo) {
this.context = { userId: userInfo.id, environment: 'prod' };
}
// Remotes call this to track feature usage
track(event: string, payload?: any) {
console.log(`[Telemetry]: ${event}`, { ...this.context, ...payload });
// Send to API / Analytics provider
}
// Specifically for federated performance
startSpan(name: string) {
const start = performance.now();
return {
end: () => {
const duration = performance.now() - start;
this.track('federation.performance', { name, duration });
}
};
}
}
// How Remote App uses it (without importing heavy SDKs)
// The Shell injects 'telemetry' into the Remote mount props
const RemoteApp = ({ telemetry }) => {
const handleCheckout = () => {
telemetry.track('checkout_initiated');
// ...
}
}
Here is how these pieces fit together when the application starts.
Shell Boot:
TelemetryClient.DeepLinkNormalizer.Route Activation:
/settings.settings Remote Bundle.TelemetryClient and LinkNormalizer as props.Remote Lifecycle:
react, react-dom, and the router library are singleton shared modules in your Webpack configuration to avoid "multiple react instances" errors./user/id to /profile/id, the normalizer handles the mapping so old links (emails sent a year ago) don't break.