This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
frontendcritical PriorityID: vite-6-mfe-style-cascade-dedup-guardrail

Vite 6 Micro-Frontend Style Cascade Precedence and Runtime Deduplication

Enforces strict document.head style insertion boundaries, CSSOM link tag deduplication, and deterministic cascade layering across dynamic Module Federation mounts in Vite 6. Prevents asynchronous micro-app chunk injections from trampling host design system tokens, altering specificity hierarchies, or bloating the CSSOM with duplicate vendor sheets.

Prohibited Anti-Pattern: Uncoordinated Head Injections and Non-Deterministic Asynchronous Remote CSS Mounting

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Vite 6 Micro-Frontend Style Cascade Precedence and Runtime Deduplication - Enforces strict document.head style insertion boundaries, CSSOM link tag deduplication, and deterministic cascade layering across dynamic Module Federation mounts in Vite 6. Prevents asynchronous micro-app chunk injections from trampling host design system tokens, altering specificity hierarchies, or bloating the CSSOM with duplicate vendor sheets.
globs: src/**/*.{ts,tsx}, vite.config.{ts,js}, src/federation/**/*.{ts,tsx}, src/bootstrap/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/vite-6-mfe-style-cascade-dedup-guardrail"
---

# Vite 6 Micro-Frontend Style Cascade Precedence and Runtime Deduplication

> **Severity**: CRITICAL | **Category**: frontend
> **Anti-Pattern Warning**: Uncoordinated Head Injections and Non-Deterministic Asynchronous Remote CSS Mounting

## System Constraints
You are a Principal Architect specializing in modern enterprise frontend runtimes and micro-frontends under Vite 6. Your task is to enforce strict CSS cascade ordering, prevent CSSOM bloat, and guarantee deterministic style tag placement across dynamically mounted asynchronous remotes. Reject any code pattern where dynamic imports or federation plugins inject stylesheet link tags indiscriminately into document.head without deterministic slot anchoring, hash-based deduplication, or cascade layer (CSS @layer) isolation.

## Strict Guidelines
- Engineers MUST ALWAYS anchor micro-frontend style insertions relative to predefined DOM sentinel markers (e.g., data-style-boundary='mfe-styles') rather than blindly executing document.head.appendChild().
- Engineers MUST ALWAYS implement SHA-256 or content-hash-based link deduplication across host and remote micro-applications before inserting any CSS stylesheet link or style element into the DOM.
- Engineers MUST encapsulate shared and remote micro-frontend styles within explicit CSS @layer declarations (e.g., @layer base, framework, remote-app, overrides) to enforce cascade predictability independent of remote mount timings.
- Engineers MUST NOT rely on default Vite asset injection plugins for asynchronous remote federation chunks without intercepting and routing remote CSS assets through a centralized Style Cascade Registry.
- Services MUST evict or reference-count micro-app scoped style tags upon remote unmounting to avoid persistent CSSOM memory leaks in long-running single-page application hosts.

## Bad vs Good Implementations
### Deterministic CSS Link Deduplication and Cascade Boundary Injection

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Directly appending link tags to document.head without deduplication causes identical stylesheets to be parsed multiple times. Worse, asynchronous remote mounts will append their styles after the host application's overrides, destroying the intended CSS cascade precedence and introducing race conditions.
```typescript
export async function mountRemoteApp(remoteUrl: string, container: HTMLElement): Promise<void> {
  // Anti-pattern: Blindly dynamic-injecting style tags into head on remote mount.
  // This causes out-of-order cascade overrides and duplicate bundle loading on multiple mounts.
  const link = document.createElement('link');
  link.rel = 'stylesheet';
  link.href = `${remoteUrl}/assets/remote-entry.css`;
  document.head.appendChild(link);

  const { mount } = await import(/* @vite-ignore */ `${remoteUrl}/remote-entry.js`);
  mount(container);
}
```

#### Production Standard (Correct)
> **Standard**: Implements an idempotent Style Cascade Registry using reference counting and a deterministic DOM sentinel (`meta#mfe-cascade-sentinel`). Styles are de-duplicated by unique identifier/href, placed strictly before host-level overrides regardless of remote network arrival order, and cleanly removed from the CSSOM upon unmount.
```typescript
interface MfeStyleRegistry {
  registerAndInject(id: string, href: string): Promise<HTMLLinkElement>;
  unregister(id: string): void;
}

class RuntimeStyleCascadeRegistry implements MfeStyleRegistry {
  private static instance: RuntimeStyleCascadeRegistry;
  private activeSheets = new Map<string, { refCount: number; element: HTMLLinkElement }>();
  private readonly boundaryAnchorId = 'mfe-cascade-sentinel';

  private constructor() {
    this.ensureSentinel();
  }

  public static getInstance(): RuntimeStyleCascadeRegistry {
    if (!this.instance) {
      this.instance = new RuntimeStyleCascadeRegistry();
    }
    return this.instance;
  }

  private ensureSentinel(): HTMLElement {
    let sentinel = document.getElementById(this.boundaryAnchorId);
    if (!sentinel) {
      sentinel = document.createElement('meta');
      sentinel.id = this.boundaryAnchorId;
      sentinel.setAttribute('data-cascade-order', 'remotes-boundary');
      // Enforce insertion before custom host overrides
      const hostOverrides = document.querySelector('[data-cascade="host-overrides"]');
      document.head.insertBefore(sentinel, hostOverrides);
    }
    return sentinel;
  }

  public async registerAndInject(sheetId: string, href: string): Promise<HTMLLinkElement> {
    const existing = this.activeSheets.get(sheetId);
    if (existing) {
      existing.refCount += 1;
      return existing.element;
    }

    // Verify non-existence in global CSSOM by canonical href
    const domNode = document.querySelector<HTMLLinkElement>(`link[data-mfe-css-id="${sheetId}"]`);
    if (domNode) {
      this.activeSheets.set(sheetId, { refCount: 1, element: domNode });
      return domNode;
    }

    return new Promise((resolve, reject) => {
      const link = document.createElement('link');
      link.rel = 'stylesheet';
      link.href = href;
      link.setAttribute('data-mfe-css-id', sheetId);
      link.onload = () => resolve(link);
      link.onerror = () => {
        this.activeSheets.delete(sheetId);
        link.remove();
        reject(new Error(`Failed to mount remote CSS: ${href}`));
      };

      const sentinel = this.ensureSentinel();
      document.head.insertBefore(link, sentinel);
      this.activeSheets.set(sheetId, { refCount: 1, element: link });
    });
  }

  public unregister(sheetId: string): void {
    const sheet = this.activeSheets.get(sheetId);
    if (!sheet) return;

    sheet.refCount -= 1;
    if (sheet.refCount <= 0) {
      sheet.element.remove();
      this.activeSheets.delete(sheetId);
    }
  }
}

export async function mountRemoteApp(appId: string, remoteUrl: string, container: HTMLElement): Promise<() => void> {
  const registry = RuntimeStyleCascadeRegistry.getInstance();
  const cssId = `mfe-style-${appId}`;
  const cssUrl = `${remoteUrl}/assets/remote-entry.css`;

  await registry.registerAndInject(cssId, cssUrl);
  const { mount, unmount } = await import(/* @vite-ignore */ `${remoteUrl}/remote-entry.js`);
  
  mount(container);

  return () => {
    unmount(container);
    registry.unregister(cssId);
  };
}
```

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: Vite 6 Micro-Frontend Style Cascade Precedence and Runtime Deduplication

Vite 6 Micro-Frontend Style Cascade Precedence and Runtime Deduplication defines an industrial-grade behavioral standard for frontend engineering. Enforces strict document.head style insertion boundaries, CSSOM link tag deduplication, and deterministic cascade layering across dynamic Module Federation mounts in Vite 6. Prevents asynchronous micro-app chunk injections from trampling host design system tokens, altering specificity hierarchies, or bloating the CSSOM with duplicate vendor sheets. 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: Uncoordinated Head Injections and Non-Deterministic Asynchronous Remote CSS Mounting 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 DriftUncoordinated Head Injections and Non-Deterministic Asynchronous Remote CSS MountingCritical
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 anchor micro-frontend style insertions relative to predefined DOM sentinel markers (e.g., data-style-boundary='mfe-styles') rather than blindly executing document.head.appendChild().

Engineers MUST ALWAYS anchor micro-frontend style insertions relative to predefined DOM sentinel markers (e.g., data-style-boundary='mfe-styles') rather than blindly executing document.head.appendChild().

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 ALWAYS implement SHA-256 or content-hash-based link deduplication across host and remote micro-applications before inserting any CSS stylesheet link or style element into the DOM.

Engineers MUST ALWAYS implement SHA-256 or content-hash-based link deduplication across host and remote micro-applications before inserting any CSS stylesheet link or style element into the DOM.

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

Engineers MUST encapsulate shared and remote micro-frontend styles within explicit CSS @layer declarations (e.g., @layer base, framework, remote-app, overrides) to enforce cascade predictability independent of remote mount timings.

Engineers MUST encapsulate shared and remote micro-frontend styles within explicit CSS @layer declarations (e.g., @layer base, framework, remote-app, overrides) to enforce cascade predictability independent of remote mount timings.

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

Engineers MUST NOT rely on default Vite asset injection plugins for asynchronous remote federation chunks without intercepting and routing remote CSS assets through a centralized Style Cascade Registry.

Engineers MUST NOT rely on default Vite asset injection plugins for asynchronous remote federation chunks without intercepting and routing remote CSS assets through a centralized Style Cascade Registry.

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

Services MUST evict or reference-count micro-app scoped style tags upon remote unmounting to avoid persistent CSSOM memory leaks in long-running single-page application hosts.

Services MUST evict or reference-count micro-app scoped style tags upon remote unmounting to avoid persistent CSSOM memory leaks in long-running single-page application hosts.

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 Vite 6 Micro-Frontend Style Cascade Precedence and Runtime Deduplication critical for AI coding assistants?

Enforces strict document.head style insertion boundaries, CSSOM link tag deduplication, and deterministic cascade layering across dynamic Module Federation mounts in Vite 6. Prevents asynchronous micro-app chunk injections from trampling host design system tokens, altering specificity hierarchies, or bloating the CSSOM with duplicate vendor sheets. 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 (Uncoordinated Head Injections and Non-Deterministic Asynchronous Remote CSS Mounting) 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

Vite