# Pure Native Micro-Frontends

For decades, we were told we needed heavy third-party framework compilation layers just to slice code layout efficiently — we were told wrong.

This article introduces the **Remote Module Definition (RMD)** pattern, which removes this bottleneck natively inside the browser’s raw engine. By returning to first principles, the RMD pattern has turned the web into an open plugin architecture and set the baseline for entirely new web architectures and new web markets.

## A Brief History of Native Includes

The challenge of native component inclusion is not new; the web development community has been trying to solve this bottleneck for over thirty years. This persistent dilemma dates back to early server-side architectures and client-side hacks of the 1990s and 2000s, including Apache Server Side Includes (SSI), the highly controversial frameset era, and primitive patterns involving hidden iframes.

By the early 2010s, the conversation shifted to community Q&A forums, where developers frequently sought clean patterns for template injection. A notable milestone occurred around 2013 when the W3C introduced the HTML Imports specification — arguably the industry's most coordinated attempt at a native solution. Despite initial enthusiasm and widespread documentation across community hubs, the specification failed to gain universal browser consensus and was officially deprecated in 2023.

The RMD pattern is something you can apply today that scales for tomorrow as it cleanly solves this problem for us.

## The RMD Predecessor: A Custom Element

The RMD pattern itself went through several important iterations — the latest being this custom element.

### Custom Element Definition

```javascript
const TAGNAME = 'nwf-partial';
const defined = !!customElements.get(TAGNAME);

if (!defined) customElements.define(TAGNAME, class NativeWebFederationIncludeElement extends HTMLIFrameElement {
    
    #handleLoad = (e) => {
        const { contentDocument } = this;
        const content = contentDocument.querySelector('.partial.content');  // expects there to be an element such as *[class="partial content"]
        this.outerHTML = content.outerHTML;  // effectively replaces this node with the content of the .partial.content element
    };
    
    connectedCallback() {
        this.addEventListener('load', this.#handleLoad, true);
    }
    
    disconnectedCallback() {
        this.removeEventListener('load', this.#handleLoad, true);
    }
    
}, { extends: 'iframe' });
```

### Importing The Partial

```html
<div id="container">
    <!-- use [is="nwf-partial"] to extend iframe with our custom element -->
    <iframe src="./partial.rmd.html" is="nwf-partial"></iframe>
</div>
```

> *After the Custom Element is pulled in and defined, we can extend an iframe and point it to any partial we want to include.*

### The Partial

```html
<body>
    <div class="partial content">
        <h2>Custom Element Partial</h2>
    </div>
</body>
```

> *Defines* `./partial.rmd.html` *using a conventional* `[class="partial content"]` *element, as required by the custom element.*

### Output

```html
<div id="container">
    <!-- use [is="nwf-partial"] to extend iframe with our custom element -->
    <div class="partial content">
        <h2>Custom Element Partial</h2>
    </div>
</div>
```

---

## Deconstructing The Custom Element Solution

### The Breakdown

The `NativeWebFederationIncludeElement` simply extends the `HTMLIFrameElement` class so that every instance (`iframe[is="nwf-partial"]`) handles its own scope, as opposed to tracking & mapping everything in a top-down system fashion. When the child frame loads, the Custom Element simply queries its own document for the conventional `.content.partial` target before replacing itself with the content, similar to using `this.replaceWith(content)`.

### Limitations

This approach arguably packages the old, top-down 'hidden iframes' approach into a single, small system so that there is no complicated mapping & handling between the content source and outlet, largely reducing the chance for errors. But this approach has some issues; while it is no longer a top-down system, it is still a stepwise system in the RMD's outer scope, so the Custom Element must make all kinds of assumptions about the target RMD's inner structure and intentions – essentially, *Content/Pathological Coupling*. In addition to that, the small amount of boilerplate overhead — alongside the aforementioned assumptions — makes this implementation less portable across different codebases without additional tooling (*compounding those assumptions*). What if we used a bottom-up system instead?

---

## The RMD Pattern

Essentially, we leverage a type of IoC (Inversion of Control) on the Custom Element solution by converting the Custom Element into a simplified pattern that flips the system on its head and delegates all assumptions to the partial, itself. Better yet, as you'll see below, we naturally get a fully native *Single File Component (SFC)* syntax, as seen in frameworks like Svelte and Vue. This natural syntax, however, can be jailbroken if the developer decides to separate code into their own files and import them in the RMD using `script[src]` and `link[href][rel="stylesheet"]` instead. In fact, the RMD pattern even allows you to import `<template>`s, themselves. Here is a basic RMD and its usage in its simplest form, suited for static partials, without any need for a Custom Element or *any* additional infrastructure.

### Importing The Partial

```html
<div id="container">
    <iframe src="./partial.rmd.html"></iframe>
</div>
```

> *No overhead of defining a custom element or extending the iframe with an* `[is]` *attribute.*

### The Partial

```html
<body>
    <template>
        <style>
            .my.heading {
                color: blue;
            }
        </style>
        <h2 class="my heading">Native Partial</h2>
    </template>
    <script>  // this can even be a reusable script
        const { content } = document.querySelector('template');
        frameElement.replaceWith(content);
    </script>
</body>
```

> *No Content Coupling. Nothing assumes internal behavior of the RMD. The RMD dictates all of its own conventions.*

### Output

```html
<div id="container">
    <style>
        .my.heading {
            color: blue;
        }
    </style>
    <h2 class="my heading">Native Partial</h2>
</div>
```

---

## Deconstructing The RMD Solution

### The Breakdown

We delegate all responsibilities & assumptions to the RMD, itself, allowing it to become an *HTML Service* simply governed by the iframe interface and its own mechanisms. By the time the browser reaches the `<script>`, the RMD simply queries its own document for a target `<template>`, destructures the `DocumentFragment` that is its `content` property, and simply swaps the `iframe` in the *parent frame* by calling `frameElement.replaceWith` and passing in the document fragment node.

### Limitations

We have yet to come up with many limitations to this pattern at Native Web Federation. It seems to scale in just about every direction you need it to. We've prototyped many variants and plan to explore even more. The Native Web Federation has brought this pattern to scale all the way into entire websites that load quickly and categorically brand new types of web architectures. Other variants we've explored for the pattern include *Native Skeleton UIs* where either the host element simply targets the iframes (perhaps using a `.rmd` class) with styles before the frame is replaced — or the RMD, itself, does this on its own `<body>` element; each method provides benefit for two different intentions and phases of the RMD's loading process. These variants and many more have already been pioneered in our alpha architecture, proving its mechanical viability.

### Fallback Solutions to Usual Edge-Cases

The strength of the RMD pattern lies in its architectural minimalism. Rather than manufacturing a brittle abstraction layer to police usual edge-cases, the pattern offloads these foundational requirements directly onto the native browser runtime. The RMD baseline can still be further extended with Custom Elements that drive behavior to solve more specific needs. One of the RMD variants from Native Web Federation even allows CORS-enabled RMD Web Components to be normalized for cross-domain Micro-Frontends.

#### Error Handling

Network and execution failures trigger standard error lifecycle events automatically. This can be handled cleanly by unmounting the node from the Document Object Model (DOM) or executing a fallback strategy using a standard inline handler.

```html
<iframe onerror="e => this.remove()">
```

```html
<iframe onerror="e => this.src='404.rmd.html'">
```

#### Skeleton UIs

Ensuring a fluid user experience when your RMD naturally takes time to hydrate is easy using a Skeleton UI — simply apply a background animation to the RMD `<body>`; when the RMD finishes executing to swap the frame, the animation naturally disappears without any additional effort.

```html
<body>
    <style>
        body {
            min-height: 120px;
            background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
            background-size: 200% 100%;
            animation: rmd-shimmer 1.5s infinite;
        }

        @keyframes rmd-shimmer {
            0% { background-position: 200% 0; }
            100% { background-position: -200% 0; }
        }
    </style>
    <template>...</template>
    <script>...</script>
</body>
```

> *The RMD body automatically receives these styles as soon as it loads, which can even be configured via data-attributes on the* `frameElement.dataset`*. Consumers can even provide their own* `link[rel="stylesheet"]` *source for their own animations via frame-element configurations.*

#### CSS Scoping

Style encapsulation naturally follows standard browser nesting models. Components behave as if authored directly in place, ensuring an intuitive layout flow, and can be complemented by native primitives such as CSS `@scope` rules or *The CDC Pattern* (as specified in the book "MagazineJS - Demystifying Frontend Toolchains and Industry Myths").

#### I18n/L10n (Internationalization/Localization)

Various subpatterns can be used for any configuration needs, such as fully-scoped localization.

```html
<body>
    <template>
        <h2>${title}</h2>
    </template>
    <script type="application/json" id="en">
        { "title": "Hello RMD" }
    </script>
    <script type="application/json" id="es">
        { "title": "Hola RMD" }
    </script>
    <script type="module">
        import { interpolate } from '/core/utilities/interpolate.js';
        
        const { dataset } = frameElement;
        const { lang } = dataset;  // targets iframe[data-lang]
        const { innerText: jsonEN } = document.querySelector('script[type="application/json"][id="en"]');
        const { innerText: jsonES } = document.querySelector('script[type="application/json"][id="es"]');
        // ... parse JSON, interpolate into template, replace frameElement.
    </script>
</body>
```

> *Solution is truncated for simplicity. Localization can even be driven by looking at window.top.location.search, for instance.*

### Flexibility & Scalability

One of the many wonderful things about the RMD pattern is that, if you prefer a slightly \[or largely\] different approach or syntax — *ever* — **it is completely adaptive to your needs and preferences**.

---

## Modernization, Normalization, and Innovation

The Native Web Federation has scaled the foundational RMD pattern and many variants to work with other aspects of modern web development, new types of websites, and web architectures.

- **Native Micro-frontends:** RMD complements Custom Elements fluidly to enable native micro-frontend architectures with Web Components. Normalization techniques can even be leveraged to import CORS-enabled cross-domain components.
- **Frameworks & SDKs:** Frameworks and SDKs can be built on top of RMD to import subsets of a library such as buttons, icons, or entire sets.
- **Content Delivery Networks:** RMD can be used to redirect stable URLs to return any component in that "WebSlot"; WebSlot RMDs can inspect their frame's URL structure to be used for versioning, reliability, localization, and virtually any other need.

### The "Dead Internet" Dilemma and CAPTCHA

The RMD pattern naturally works as an active signal-jammer to unwanted bots and crawlers, standing as a defense against the "Dead Internet dilemma" and protecting content authors & creators while leveraging targeted assets in a `robots.txt` to bolster SEO purposes.

RMDs successfully mitigate automated network scavenging as it delivers critical operational, legal, and security protections to both individuals and enterprise organizations:

- **Prevention of Personal Data Loss**: It prevents the automated mining and exposure of sensitive credentials, safeguarding individual digital identity, Personally Identifiable Information (PII), and Protected Health Information (PHI) under strict compliance frameworks like **HIPAA**.
- **Regulatory Readiness**: It introduces an infrastructure-level barrier against automated exfiltration, significantly streamlining organizational compliance reports and audits for frameworks such as **GDPR, SOC2, ISO/IEC 27001**, and the **EU AI Act**.
- **Intellectual Property Protection**: It defends digital assets against unconsented, uncompensated scraping loops used to train proprietary, centralized generative models, securing the sovereign distribution rights of authors and creators.
- **Overhead and Cost Reduction**: It blocks relentless, non-human traffic cycles before they hit centralized infrastructure, drastically lowering compounding bandwidth costs and server processing bills.
- **Secure Layout Handshakes**: To add an unprecedented layer of trust, the architecture facilitates secure, lightweight validation directly at the layout frame layer. By leveraging native interfaces, the system can parse dynamic inputs passed via **URL parameters, iframe attributes, or iframe inner text (structured as raw JSON)**. These payload-driven inputs can securely verify a mutual handshake to handle multi-tiered authentication and context-aware authorization. Because these handshakes process natively rather than relying on interceptable session tokens, they eliminate traditional single points of failure — making the entire web experience safer while potentially making intrusive human/bot tests like **CAPTCHA a thing of the past**.

---

## A Quick Comparison of RMD against Modern Frontend Approaches

Our modest team at Native Web Federation speculates that other existing and new Micro-Frontend frameworks will target RMD implementations to minimize internal & external framework complexity.

| Feature / Metric | Traditional SPA (React / Vue) | Micro-Frontends (Module Federation) | RMD Pattern (Native RMD) |
| --- | --- | --- | --- |
| **Build-Time Tooling** | Required (Babel, Vite, Webpack) | Heavy (Custom Webpack plugins) | **None** (Vanilla Browser Standards) |
| **Runtime Overhead** | Heavy (Virtual DOM + Runtime Libs) | Moderate-High (Shared Runtime Wrappers) | **Zero** (Native Engine Primitives) |
| **Node.js Dependency Tree** | Hundreds of MBs (`node_modules`) | Complex shared dependency matrices | **Zero External Dependencies** |
| **Component Syntax** | Non-standard JSX / `.vue` files | Standard JS / Framework-specific | **Native HTML / CSS / JS** |
| **Dynamic Origin Loading** | Complex CORS / Bundle Splitting | Complex Remote Entry Configuration | **Native** `<iframe src="...">` **Primitives** |
| **Debugging Experience** | Requires Source Maps & DevTools | Complex Cross-Bundle Stack Traces | **Direct Browser DOM Inspection** |

---

## Back the Indiegogo Campaign to Turn the RMD Pattern into a Core W3C Tag-Name

<https://www.indiegogo.com/en/projects/tiebacktechnologies/nwf>

We need the community's help on exploring more variants, creating Reference Implementations, building specifications & documentation, and testing & benchmarking the pattern's early phases alongside each upcoming milestone.
