@lib-core-mfe/fragment-frontend
v0.2.0
Published
Experimental server-rendered remote fragments for React: Provider streams HTML, Consumer embeds it, the browser hydrates with the Provider's own React.
Maintainers
Readme
@lib-core-mfe/fragment-frontend
Experimental. Server-rendered remote fragments for React micro-frontends.
The Provider renders a fragment on its own server and streams the HTML. The Consumer's server fetches it (server to server) and embeds it in the page. In the browser the fragment is hydrated by the Provider's own React; the Consumer's React never touches it.
Consumer server --GET /fragments/<name>?params--> Provider server
| (HTML stream + x-fragment-* headers) renders with React
v
page HTML = Consumer markup + fragment markup + serialized props
|
Browser: Consumer hydrates its tree -> <FragmentSlot> loads the Provider bundle
-> registry entry hydrates the fragment with the Provider's ReactProvider
// server
import { createFragmentHandler } from "@lib-core-mfe/fragment-frontend/server";
app.use(createFragmentHandler({
appName: "shop", // same as registerFragment
fragments: {
cart: {
Component: Cart,
clientScript: "/assets/cart.client.js",
getProps: ({ params }) => ({ entityId: params.get("entityId") ?? "" }),
},
},
}));
// client bundle (served from clientScript)
import { registerFragment } from "@lib-core-mfe/fragment-frontend/provider";
registerFragment("cart", Cart, { appName: "shop" });Props must be JSON-serializable: the same values render on the server and hydrate in the browser.
Consumer
// server: per request
import { fetchFragment } from "@lib-core-mfe/fragment-frontend/server";
const fragment = await fetchFragment({
host: "https://provider.example.com",
name: "cart",
params: { entityId: "42" },
allowedHosts: ["https://provider.example.com"], // required
});
const html = await fragment.html(); // or stream fragment.body
const { body, html: _h, ...info } = fragment; // `info` is small and JSON-safe
// page (server render passes `html`; the client passes only `info`)
import { FragmentSlot } from "@lib-core-mfe/fragment-frontend/consumer";
<FragmentSlot fragment={info} html={html} allowedHosts={["https://provider.example.com"]} />Interactivity, failures and client rendering
- Not clickable before it works. The Provider emits the fragment root with
inert,aria-busy="true"anddata-fragment-state="pending".FragmentSlotlifts them once the Provider's React has hydrated (data-fragment-state="ready"), so a form in server markup cannot be submitted natively before it is interactive. Opt out withcreateFragmentHandler({ inertUntilHydrated: false }). - Client-render fallback. With no server markup on the page,
FragmentSlotrenders the fragment in the browser through the bundle'smount, using thepropsyou pass (the same shapegetPropsreturns). A Consumer without a server, or one whose server could not reach the Provider, still shows the fragment. - Fallback and retry. A fatal error (script blocked or not registered, contract mismatch,
nothing to render) or no attachment within
timeoutMs(default 10 s,0disables) callsonErrorand, whenfallbackis set, renders it.retrystarts a new attempt: it hydrates server markup if present, otherwise client-renders frompropsor the props read from the server markup. Recoverable hydration errors only reachonError: React already recovers. - Lifecycle.
onHydratedfires after hydration;onReady(mode)fires after hydration ("hydrated") or a client render ("mounted"). Changingfragment.idtears down the old root and attaches the new fragment. - Styles. A fragment definition may set
styles(URL relative to the Provider). It travels inx-fragment-styles,fetchFragmentresolves it against the allowlist, andFragmentSlotplaces a<link rel="stylesheet">before the markup, so server HTML is styled before the bundle runs.
<FragmentSlot
fragment={info}
html={html}
props={{ entityId: "42" }}
allowedHosts={["https://provider.example.com"]}
timeoutMs={8000}
fallback={({ retry }) => <button onClick={retry}>Try again</button>}
onReady={(mode) => console.log("ready via", mode)}
/>Status
Walking skeleton. Covered by tests: streaming with metadata headers, script-safe props, failures before streaming (500), allowlist, no redirects, contract check, timeout, and hydration without warnings (including StrictMode); inert markup until hydration, client-render fallback, fallback with retry and attach timeout, remount when the fragment changes, and stylesheet delivery inside the allowlist.
Not done: independent React across real bundles, Declarative Shadow DOM isolation, SRI enforcement, event bus, benchmark. See ADR 0001.
Security
A Provider script runs with the page's privileges, and its HTML is injected into the Consumer
page. allowedHosts is a trust decision, not a sandbox. The Consumer's server-side fetch never
follows redirects and refuses hosts outside the allowlist (SSRF).
