This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
frontendcritical PriorityID: module-federation-2-dynamic-remote-abi-versioning

Module Federation 2.0 Dynamic Remote ABI Versioning and Singleton Integrity Guardrail

Enforces strict singleton resolution and explicit ABI runtime contract negotiation across Module Federation 2.0 dynamic remotes. Eliminates catastrophic cross-container failures caused by multiple shared instance initialization (e.g., React contexts, design systems, state managers) and semantic contract drift across independently deployed micro-frontends.

Prohibited Anti-Pattern: Permissive Shared Scope Resolution and Unchecked Dynamic Remote Invocations Causing Split-Brain Singletons and Silent Runtime ABI Desynchronization

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Module Federation 2.0 Dynamic Remote ABI Versioning and Singleton Integrity Guardrail - Enforces strict singleton resolution and explicit ABI runtime contract negotiation across Module Federation 2.0 dynamic remotes. Eliminates catastrophic cross-container failures caused by multiple shared instance initialization (e.g., React contexts, design systems, state managers) and semantic contract drift across independently deployed micro-frontends.
globs: **/module-federation.config.{ts,js}, **/rspack.config.{ts,js}, **/webpack.config.{ts,js}, src/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/module-federation-2-dynamic-remote-abi-versioning"
---

# Module Federation 2.0 Dynamic Remote ABI Versioning and Singleton Integrity Guardrail

> **Severity**: CRITICAL | **Category**: frontend
> **Anti-Pattern Warning**: Permissive Shared Scope Resolution and Unchecked Dynamic Remote Invocations Causing Split-Brain Singletons and Silent Runtime ABI Desynchronization

## System Constraints
You are a Principal Software Architect enforcing Module Federation 2.0 Dynamic Remote ABI Versioning and Singleton Integrity. Your mission is to prevent runtime execution of incompatible micro-frontend remotes and enforce deterministic singleton sharing for critical core dependencies (e.g., React, React-DOM, state containers, design systems). Mandate strict version bounds, dynamic runtime contract handshakes, and explicit error boundary encapsulation.

## Strict Guidelines
- Engineers MUST ALWAYS configure critical shared packages (react, react-dom, react-router, zustand, @tanstack/react-query, etc.) with 'singleton: true', 'strictVersion: true', and an explicit 'requiredVersion' sourced directly from package.json.
- Engineers MUST NOT dynamically load remote entries via raw <script> injection or untyped window accesses; all dynamic remote resolutions MUST pass through the official Module Federation 2.0 Runtime API ('@module-federation/runtime' or '@module-federation/enhanced').
- Dynamic remote consumers MUST execute an explicit runtime ABI contract validation (e.g., version handshake, semver range check, or runtime schema validation like Zod) before mounting remote micro-frontend components.
- Federated remote containers MUST explicitly declare and export their ABI manifest and semantic contract version via a dedicated meta-export (e.g., '__abi_version__', 'contractVersion').
- Components consuming dynamic federated remotes MUST ALWAYS be wrapped in dedicated, resilient Error Boundaries and Suspense boundaries with typed fallback states to prevent remote failures from cascading to the host container.

## Bad vs Good Implementations
### Module Federation Shared Config and Dynamic Loading Guard

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Omitting 'strictVersion: true' and 'requiredVersion' allows the host and remote to resolve different versions of React, triggering the dreaded 'Invalid hook call' or context loss. Loading dynamic remotes via raw URL imports completely bypasses Module Federation's shared scope resolution and ABI compatibility checks.
```typescript
// module-federation.config.ts (Unsafe: Permissive shared config allows duplicate instances)
export default {
  name: 'host_app',
  remotes: {},
  shared: {
    react: { singleton: true }, // Missing strictVersion and requiredVersion
    'react-dom': { singleton: true },
  },
};

// src/RemoteLoader.tsx (Unsafe: Raw dynamic consumption without ABI validation)
import React, { useEffect, useState } from 'react';

export const RemoteComponentLoader = ({ remoteUrl }: { remoteUrl: string }) => {
  const [Component, setComponent] = useState<any>(null);

  useEffect(() => {
    // Raw load without version check, fallback, or error boundary
    import(/* webpackIgnore: true */ remoteUrl).then((module) => {
      setComponent(() => module.default);
    });
  }, [remoteUrl]);

  return Component ? <Component /> : <div>Loading...</div>;
};
```

#### Production Standard (Correct)
> **Standard**: Configures strict singleton versions backed by the authoritative package manifest to guarantee single instances of core runtimes. Loads dynamic remotes using the official Module Federation 2.0 runtime API, strictly verifies the remote ABI contract using Zod prior to rendering, and isolates failures using typed error boundaries.
```typescript
// module-federation.config.ts (Safe: Strict singleton pinning with package.json dependencies)
import packageJson from './package.json' assert { type: 'json' };
import { createModuleFederationConfig } from '@module-federation/enhanced/rspack';

export default createModuleFederationConfig({
  name: 'host_app',
  shared: {
    react: {
      singleton: true,
      strictVersion: true,
      requiredVersion: packageJson.dependencies.react,
    },
    'react-dom': {
      singleton: true,
      strictVersion: true,
      requiredVersion: packageJson.dependencies['react-dom'],
    },
  },
});

// src/RemoteLoader.tsx (Safe: Module Federation 2.0 Runtime with ABI Contract Guard)
import React, { Suspense } from 'react';
import { init, loadRemote } from '@module-federation/runtime';
import { z } from 'zod';
import { RemoteErrorBoundary } from './RemoteErrorBoundary';

const RemoteABISchema = z.object({
  abiVersion: z.literal('2.1.0'),
  Component: z.custom<React.ComponentType<{ userId: string }>>((val) => typeof val === 'function'),
});

export interface RemoteLoaderProps {
  remoteName: string;
  remoteEntry: string;
  userId: string;
}

async function fetchAndVerifyRemote(remoteName: string, remoteEntry: string) {
  init({
    name: 'host_app',
    remotes: [{ name: remoteName, entry: remoteEntry }],
  });

  const remoteModule = await loadRemote<unknown>(`${remoteName}/ExportedWidget`);
  const parsed = RemoteABISchema.safeParse(remoteModule);

  if (!parsed.success) {
    throw new Error(`Remote ABI drift detected in ${remoteName}: ${parsed.error.message}`);
  }

  return { default: parsed.data.Component };
}

export const SafeRemoteWidget: React.FC<RemoteLoaderProps> = ({ remoteName, remoteEntry, userId }) => {
  const LazyComponent = React.lazy(() => fetchAndVerifyRemote(remoteName, remoteEntry));

  return (
    <RemoteErrorBoundary fallback={<div>Remote widget unavailable or incompatible.</div>}>
      <Suspense fallback={<div>Loading remote micro-frontend...</div>}>
        <LazyComponent userId={userId} />
      </Suspense>
    </RemoteErrorBoundary>
  );
};
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Module Federation 2.0 Dynamic Remote ABI Versioning and Singleton Integrity Guardrail

Module Federation 2.0 Dynamic Remote ABI Versioning and Singleton Integrity Guardrail defines an industrial-grade behavioral standard for frontend engineering. Enforces strict singleton resolution and explicit ABI runtime contract negotiation across Module Federation 2.0 dynamic remotes. Eliminates catastrophic cross-container failures caused by multiple shared instance initialization (e.g., React contexts, design systems, state managers) and semantic contract drift across independently deployed micro-frontends. Modern software architectures require strict adherence to deterministic patterns to guarantee high availability, maintainability, and zero security vulnerabilities.

Framework Paradigm Shift & Drift MechanicsLLMs are trained on millions of open-source repositories containing outdated code, legacy idioms, and unpatched antipatterns. When coding assistants generate implementations for this stack, they default to common statistical tokens: Permissive Shared Scope Resolution and Unchecked Dynamic Remote Invocations Causing Split-Brain Singletons and Silent Runtime ABI Desynchronization Without an explicit system instruction file, developers spend hours debugging silent failures.
Failure Modes & Production Blast Radius

Hazard Analysis: What Breaks Without This Rule

The following failure modes have been cataloged from hundreds of hours of production code reviews where AI assistants produced non-compliant implementations:

Failure ModeAI Symptom (The Anti-Pattern)SeverityProduction Impact & Remedy
AI Hallucination & Deprecation DriftPermissive Shared Scope Resolution and Unchecked Dynamic Remote Invocations Causing Split-Brain Singletons and Silent Runtime ABI DesynchronizationCritical
Violating this industrial standard introduces regression bugs, security risks, and unexpected runtime failures in production.
Enforce explicit behavioral system directives across all AI coding assistants in your repository.
Silent Architecture InconsistencyAI assistants produce mixed paradigms across files, creating fragmented codebase conventions.Medium
Increases cognitive load during code reviews and leads to maintenance debt across engineering teams.
Pin project conventions in .cursor/rules, CLAUDE.md, and AGENTS.md so all team agents follow identical guardrails.
Architectural Directives in Detail

Step-by-Step Production Directives

Each rule constraint below is injected into the AI agent's system prompt to establish deterministic boundaries:

1

Engineers MUST ALWAYS configure critical shared packages (react, react-dom, react-router, zustand, @tanstack/react-query, etc.) with 'singleton

Engineers MUST ALWAYS configure critical shared packages (react, react-dom, react-router, zustand, @tanstack/react-query, etc.) with 'singleton: true', 'strictVersion: true', and an explicit 'requiredVersion' sourced directly from package.json.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
2

Engineers MUST NOT dynamically load remote entries via raw <script> injection or untyped window accesses

Engineers MUST NOT dynamically load remote entries via raw <script> injection or untyped window accesses; all dynamic remote resolutions MUST pass through the official Module Federation 2.0 Runtime API ('@module-federation/runtime' or '@module-federation/enhanced').

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
3

Dynamic remote consumers MUST execute an explicit runtime ABI contract validation (e.g., version handshake, semver range check, or runtime schema validation like Zod) before mounting remote micro-frontend components.

Dynamic remote consumers MUST execute an explicit runtime ABI contract validation (e.g., version handshake, semver range check, or runtime schema validation like Zod) before mounting remote micro-frontend components.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
4

Federated remote containers MUST explicitly declare and export their ABI manifest and semantic contract version via a dedicated meta-export (e.g., '__abi_version__', 'contractVersion').

Federated remote containers MUST explicitly declare and export their ABI manifest and semantic contract version via a dedicated meta-export (e.g., '__abi_version__', 'contractVersion').

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
5

Components consuming dynamic federated remotes MUST ALWAYS be wrapped in dedicated, resilient Error Boundaries and Suspense boundaries with typed fallback states to prevent remote failures from cascading to the host container.

Components consuming dynamic federated remotes MUST ALWAYS be wrapped in dedicated, resilient Error Boundaries and Suspense boundaries with typed fallback states to prevent remote failures from cascading to the host container.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is Module Federation 2.0 Dynamic Remote ABI Versioning and Singleton Integrity Guardrail critical for AI coding assistants?

Enforces strict singleton resolution and explicit ABI runtime contract negotiation across Module Federation 2.0 dynamic remotes. Eliminates catastrophic cross-container failures caused by multiple shared instance initialization (e.g., React contexts, design systems, state managers) and semantic contract drift across independently deployed micro-frontends. Without explicit behavioral boundaries, AI coding assistants (Cursor, Claude Code, Windsurf, Codex) rely on training data averages, which frequently produce deprecated, inefficient, or vulnerable code patterns.

Q:How does adopting this rule prevent AI hallucinations?

This rule explicitly declares what the AI must avoid (Permissive Shared Scope Resolution and Unchecked Dynamic Remote Invocations Causing Split-Brain Singletons and Silent Runtime ABI Desynchronization) and prescribes verified positive examples. Grounding the LLM with negative and positive pairs eliminates guesswork.

Q:Which AI coding environments are supported?

This specification is multi-platform compatible: Cursor (.cursor/rules/*.mdc & .cursorrules), Anthropic Claude Code (CLAUDE.md), Windsurf (.windsurfrules), Codex / Cline (AGENTS.md), and GitHub Copilot (.github/copilot-instructions.md).

Q:Can I combine this rule with other technology stacks?

Yes. Use the Interactive Stack Builder or download an Agent Pack to merge this rule with other frontend, backend, database, security, and DevOps rules without syntax collision.

Open Specification · CC BY 4.0·Free for Personal, Team & Commercial In-Repo Use

Citation & Open Source Attribution Guidelines

This specification is licensed under Creative Commons Attribution 4.0 International (CC BY 4.0). You are completely free to adapt and share this rule in your workspace. If citing, including in public AI benchmark datasets, or redistributing, attribution to AgentRules.org is required.

Related FRONTEND Rules

View all rules →
frontend
119

SolidStart 1.0 Server Functions & Async Boundaries Production Standard

SolidStart 1.0 relies on the Vinxi bundler to split `server$` closures into independent HTTP POST RPC endpoints. Direct lexical closure over client signals within `server$` scopes or failure to demarcate async boundaries with `<Suspense>` causes silent serialization failures, client-bundle secret leaks, and SSR hydration mismatches. Enforcing strict parameter passing, runtime input validation, and Solid async primitives maintains security and fine-grained reactivity across network boundaries.

frontend
119

Astro 5 Actions & Content Layer Production Standard

Enforces strict type safety and architectural correctness for Astro 5 Server Actions and the zero-waterfall Content Layer API. Prevents runtime contract mismatches, hydration mismatches, and unhandled mutation exceptions across dynamic and prerendered boundaries. Failure to follow these patterns leads to silent data fetching waterfalls, build-time cache corruptions, and unhandled server action exceptions.

frontend
51

Nuxt 4 Nitro Server Engine & Shared Directory Production Standard

Nuxt 4 enforces strict boundary segregation between client UI in the app/ directory, backend endpoints in server/, and universal contracts in shared/. Violating cross-boundary isolation or maintaining module-scoped state in Nitro server handlers causes catastrophic cross-request data corruption and hydration mismatches under concurrent production traffic. Architects must enforce request-isolated H3 event contexts, universal serialization schemas, and strict path-alias boundaries.

1 Rule in Stack

Module