qat

Federation

Several apps, built and deployed on their own, on one page: a shell boots with its remotes, mounts their routes and uses what they expose. There is no federation plugin and no bundler runtime: each app's qat.json says what it exposes and which shared packages it was built against, and the shell turns those into one import map before any module runs. Every app on the page imports qat and gets the same runtime.

A remote

JavaScript5 lines
// payments/qat.federate.js
export default {
  name: 'payments',
  exposes: { './routes': './src/routes.js' },
}
JavaScript7 lines
// payments/src/routes.js: a route table on its own (no router() call)
import { page } from '@qatjs/router'

export default {
  '/': page('./pages/checkout.qx'),
  '/:id': page('./pages/receipt.qx', { load: ({ params }) => api.receipt(params.id) }),
}
shell1 line
qatjs federate payments

writes payments/dist/: the exposes (each a chunk, with its pages split as usual), the shared packages built once into assets/shared/, and qat.json:

JSON9 lines
{
  "name": "payments",
  "framework": "qat",
  "exposes": { "./routes": "assets/routes-C5_aODp4.js" },
  "shared": {
    "qat": { "version": "1.4.2", "imports": { "qat": "assets/shared/qat-qhG62abv.js", "@qatjs/core/deep": "…" } },
    "@qatjs/router": { "version": "1.4.2", "imports": { "@qatjs/router": "assets/shared/qat-router-CrXpoibc.js" } }
  }
}

Serve dist/ with CORS (qatjs preview does): the shell loads these files from its own origin.

A shell

JavaScript5 lines
// shell/qat.federate.js
export default {
  name: 'shop',
  remotes: { payments: 'https://pay.example/qat.json', widgets: 'https://widgets.example/qat.json' },
}
JavaScript10 lines
// shell/src/routes.js
import { layout, page, router } from '@qatjs/router'
import { remote } from '@qatjs/federate'

export default router({
  '/': layout('./layouts/shell.qx', {
    '/': page('./pages/home.qx'),
    '/pay/**': remote('payments', './routes'),
  }),
})

qatjs dev and qatjs compress (or qatjs federate) put the boot inline in index.html, in place of the entry's module script: federate() fetches the remotes' manifests, injects the import map, and then imports the entry. A remote's table is fetched on the first visit below its prefix, after the route's guards (guard(() => isAdmin(), remote('admin', './routes'), { redirect: '/' }) fetches nothing for a visitor the guard turns away); its routes then render in the layout's outlet. Any exposed module loads with expose('payments', './receipt').

A remote that is down does not stop the shell: its routes fail where they are used, through the router's catch.

Env

Each app's import.meta.env is its own: a remote's build inlines its own .env files, and nothing of the shell's env reaches it. What a remote needs from the deployment, the shell passes by name:

JavaScript6 lines
// shell/qat.federate.js
export default {
  name: 'shop',
  remotes: { payments: 'https://pay.example/qat.json' },
  env: ['PUBLIC_API_URL'],
}
JavaScript6 lines
// payments/qat.federate.js
export default {
  name: 'payments',
  exposes: { './routes': './src/routes.js' },
  env: ['PUBLIC_API_URL'], // what it expects from the shell: recorded in its qat.json
}
// payments/src/pages/checkout.qx
import { ShellEnv, type ShellEnvValues } from '@qatjs/federate'

export default function Checkout() {
  const shell = inject<ShellEnvValues>(ShellEnv)
  return <p>API {shell.PUBLIC_API_URL}, key {import.meta.env.PUBLIC_PAYMENTS_KEY}</p>
}
  • env in the shell's qat.federate.js (passed to federate({ env }) by the inline boot) lists the only names its remotes see, as inject(ShellEnv) below a remote() route. A name the shell marks runtime is passed too: the boot reads it from the page's #qat-env (runtime variables).
  • A remote cannot have runtime variables of its own (it has no page; qatjs compress says so).
  • qatjs check on a shell fetches each remote's qat.json and reports a name the remote expects that the shell does not pass (QX-FEDERATION-ENV, an error); a remote it cannot reach is a warning.

Shared packages and versions

  • @qatjs/core and every other @qatjs/* package are singletons, always: all apps' versions must share a major (below 1.0, the minor: semver's caret). The shell's copy is loaded once, for everyone: a remote that claims a newer version does not replace it. A remote built against a newer minor than the shell's runs on the shell's, so deploy the shell first.
  • What a remote can and cannot change. A remote's own modules run in the shell's page: trust a remote as you trust your own code. But a remote cannot remap the shell's packages, nor scope over the shell's own files, and the shell's files are checked by integrity (SRI) in the import map the boot makes. qatjs compress refuses a remote manifest served over plain http://, except from localhost.
  • Different majors: federate() throws QatFederationError naming each app and its version, and the shell does not start (the message is shown on the page): @qatjs/core must have one major version, found shop @qatjs/core@1.4.0, payments @qatjs/core@2.0.0.
  • Other packages listed in shared: ['dayjs'] are shared per major: the shell's major for every app on it; an app on another major keeps its own copy, through import-map scopes. A package marked singleton: true in a manifest conflicts like @qatjs/core does.
  • A Vue or Angular remote that qat builds shares its framework's runtime the same way, as a singleton: one Vue (or Angular) for every remote of that framework on the page, and another major stops the boot, naming each remote (below).

Import-map keys

A federated build imports each shared @qatjs package by a short key, and the import map maps the key. It is derived from the package's name alone, so a shell and its remotes, built apart and on their own schedules, always agree:

specifier key
@qatjs/core #q
@qatjs/core/<entry> (@qatjs/core/deep) #q/<entry> (#q/deep)
@qatjs/<pkg> (@qatjs/router) #<pkg> (#router)
@qatjs/<pkg>/<entry> (@qatjs/load/pages) #<pkg>/<entry> (#load/pages)
any other shared package (vue, dayjs) its name

# begins no package name and no URL, so a key is never some other specifier. A key is shorter than the name it stands for, and every module of a federated page that imports the runtime carries it. qatjs dev uses the same keys: it maps both the key and the name to one URL, so each package is one module, and it serves its modules with keyed imports, as a build writes them. qat.json lists each key it uses with the name, "keys": { "#q": "@qatjs/core", "#router": "@qatjs/router" }, for tools that show names. The boot reads only imports.

Core trimming

qatjs compress keeps only the runtime units an app uses (compress). A shell's core serves every remote, so qatjs federate writes what each party uses into its qat.json ("uses": ["branch", "events.delegated:click", "list", "list.key"]), and a shell's build reads every remote's qat.json at its URL and keeps the union. A remote's own shared copy is the full core. If a remote's manifest cannot be read at build time, the shell keeps the full core and says so (--analyze, dist/core.json).

The shell's shared core then lists what it left out ("trimmed": ["list.index", "transition", …], "events": ["click", "input"]). A remote redeployed later with a unit the shell's core does not have stops the boot with QatFederationError naming the remote and the unit — qat federation: remote payments uses transition, which the shell's core leaves out — the boot calls checkUnits(options.shared, await federate(options)) before any module runs. Rebuild the shell to take it in. When the boot picks another party's copy of the core (a newer version), the shell's trim does not apply.

The shell's state reaches a remote like any context: the shell provides, the remote injects, and since there is one runtime a shell signal is reactive inside the remote.

JavaScript1 line
// shell: provide(Symbol.for('shop.user'), user)   remote: const user = inject(Symbol.for('shop.user'))

React remotes

JavaScript6 lines
// widgets/qat.federate.js
export default {
  name: 'widgets',
  framework: 'react',
  exposes: { './Rating': { file: './src/Rating.jsx', props: ['value', 'max'], events: ['rate'] } },
}

qatjs federate widgets builds each expose with the remote's own React, wrapped by @qatjs/bridge-react/remote; its React is its own (not shared, unlike a Vue or Angular remote qat builds). In the shell (which depends on @qatjs/bridge-react), federate() defines each expose as a Custom Element named <remote>-<expose>:

.qx1 line
<widgets-rating value={stars} max={5} on:rate={(e) => (stars = e.detail)} />

Declared props are properties (any value) and kebab-case attributes; each event is a CustomEvent whose detail is the callback's first argument (rate is the onRate prop on the React side). The React remote keeps its own tooling for development; the bridge re-passes props when the element is defined again.

Angular remotes

JavaScript7 lines
// ngwidgets/qat.federate.js
export default {
  name: 'ngwidgets',
  framework: 'angular',
  build: 'dist/angular/browser', // what `ng build` writes
  exposes: { './Rating': { file: 'main.js', props: ['value', 'max', 'label'], events: ['rate'] } },
}

The Angular CLI builds the remote (ng build); qatjs federate compiles nothing for it — it finds each expose's file in the build (main-G2SHYMVU.js for main.js) and writes qat.json. The expose module exports Angular's own Custom Element behind the same contract as React's:

TypeScript9 lines
// ngwidgets/src/main.ts
import { provideZonelessChangeDetection } from '@angular/core'
import { createApplication } from '@angular/platform-browser'
import { createCustomElement } from '@angular/elements'
import { adapter } from '@qatjs/bridge-angular/remote'
import { RatingComponent } from './rating.component'

const app = await createApplication({ providers: [provideZonelessChangeDetection()] })
export default adapter(createCustomElement(RatingComponent, { injector: app.injector }), 'ngwidgets-rating-ng')

With @qatjs/bridge-angular in the shell, <ngwidgets-rating value={stars} label={user} on:rate={…} /> works like the React one: inputs are properties, outputs are CustomEvents, a shell signal passed as a prop is re-passed when it changes. The remote carries its own Angular (zoneless: 42.1 kB gzip for one component with Angular 22.2.3, its main-*.js as ng build writes it for examples/federation).

Vue and Angular remotes qat builds

Without a build folder, qatjs federate builds a Vue or Angular remote itself. Each expose becomes a small module: the component behind its bridge's adapter (@qatjs/bridge-vue/remote, @qatjs/bridge-angular/mount). The framework's runtime is left out of it: Vue, or @angular/*, rxjs and tslib. That runtime is built once into assets/shared/, with each package's entries the exposes import (and what those import), and qat.json declares it shared, a singleton, with its gzip size:

JavaScript2 lines
// vue-widgets/qat.federate.js: a single-file component, compiled with the remote's own Vue
export default { name: 'vuewidgets', framework: 'vue', exposes: { './Stars': './src/stars.vue' } }
JavaScript2 lines
// ng-orders/qat.federate.js: a standalone component (Angular Material's table here)
export default { name: 'ngorders', framework: 'angular', exposes: { './Table': './src/orders-table.component.ts' } }
  • One runtime per framework. The boot maps each shared package to the highest version among the remotes that declare it. Two Vue remotes on one page load one Vue, and the shell loads its bridge once. The bridge is the remotes' elements alone (@qatjs/bridge-vue, ≈ 0.8 kB): Vue loads when a Vue remote's element connects, never on a page that shows none. Another major is a QatFederationError, as for qat: vue must have one major version, found vuewidgets vue@3.5.44, vuedates vue@4.0.0. A remote built by its own tooling (the Angular CLI above, a React remote) declares no runtime, so it carries its own copy.

  • Props and events come from the component unless qat.federate.js declares them:

    • Vue: defineProps, defineEmits, or the options' props and emits;
    • Angular: input(), input.required(), model() (with its xChange event), @Input (a setter too), output(), @Output. A component from a package has no source to read, so you declare them, as for @vuepic/vue-datepicker in the example. An Angular Material table, a Vue date picker and an SFC with scoped styles all work. An expose's CSS is added by its module.
  • The cost, in --analyze. qatjs federate shell reads its remotes' qat.json and logs each framework's runtime once, with the remotes that share it. --analyze lists it in a table, and report.json has it under bridges:

    3 lines
    remotes: Vue 52.52 kB gzip, one copy shared by vuedates, vuewidgets for vuedates/Picker, vuewidgets/Stars
    remotes: Angular 197.72 kB gzip, one copy shared by ngorders for ngorders/Table
    remotes: Angular (own copy each) carried by each remote (ngwidgets: built by its own tooling) for ngwidgets/Rating

    A shared runtime keeps each package's whole entry, since another remote may use exports this one does not. So Vue shared is 52.5 kB, where one component bundled alone is about 32 kB. Angular's is compiled ahead of time, without its JIT compiler (366.86 kB with it); that build needs typescript and @angular/compiler-cli installed in the remote. (The numbers: examples/federation as node build.js builds it, each package's gzip from its qat.json.)

  • The contract. qatjs federate writes custom-elements.json beside qat.json, typed from the component. qatjs check on the shell reads each remote's manifest and writes remotes.d.ts, which types each element. A prop of the wrong type, an attribute or an event the remote does not declare is then a type error in the shell: <vuewidgets-stars value="3" /> → TS2322 (value is a number).

  • HMR through the host. Run the remote with qatjs dev and point the shell at it (--remote vuewidgets=http://localhost:4305). An edit to its component remounts the element where it is: the shell's state and the props it passes are kept, and the page does not reload. In dev the runtime comes from the remote's dev server, still one copy.

  • Server rendering is fragment only. ssr: 'import' is Qat-only (the shell's server imports a Qat remote's server entry), and qatjs check refuses it for a bridged remote (QX-FEDERATION-SSR). In a server-rendered page, the server writes a bridged remote's element with its attributes, and the browser renders the component in it.

  • A static value on a custom element that is not a string (max={5}, autoApply={true}), or whose name is camelCase, is set as the element's property, typed. Its attribute is written too (kebab-case), for the server's HTML and a bridge's observed attributes. HTML would otherwise lowercase autoApply to an attribute no property reads.

Server rendering

A shell that renders on the server can render its remotes' routes there too, and the browser resumes them like the shell's own: no node is rebuilt, and no load the server ran runs again. The remote declares a server entry; the shell says, per mount, how its server renders it:

JavaScript5 lines
// payments/qat.federate.js
export default {
  name: 'payments',
  exposes: { './routes': { client: './src/routes.js', server: './src/routes.js' } },
}
JavaScript9 lines
// shell/src/routes.js
export default router({
  '/': layout('./layouts/shell.qx', {
    '/': page('./pages/home.qx', { mode: 'server' }),
    '/pay/**': remote('payments', './routes', { ssr: 'import' }),
    '/account/**': remote('account', './routes', { ssr: 'fragment', timeout: 1000 }),
    '/help/**': remote('help', './routes'),
  }),
})
  • ssr: 'import': same process. qatjs federate payments also writes the server entry as one module (server/routes-<hash>.mjs, in qat.json as exposes['./routes'].server). Its qat and @qatjs/* imports are bare. The shell's server fetches it once, binds those imports to its own copies, and renders the remote's routes in its own pass, with its context (provide, ShellEnv). A package of the shell that a remote's server entry imports is shared with share() from @qatjs/server/federate; the server build shares the shell's @qatjs/* dependencies.
  • ssr: 'fragment': the remote's own server, ESI-style. The shell's pass writes <!--qat:remote:account--> where the remote goes and asks the remote's server for that HTML: GET <remote>/__qat/fragment?expose=./routes&path=/7. qatjs federate writes that server as dist/server/entry.mjs; node dist/server/entry.mjs or qatjs preview runs it. The answer ({ $schema, version: 1, html, n, l, d, m, css }) is the outlet's content, rendered with every load settled, plus the remote's state. If it arrives within timeout (default 1000 ms), it replaces the marker. Otherwise the marker stays, and the browser renders the remote: the client path. The fragment is rendered without the shell around it, so only ShellEnv (sent along) reaches it, not the shell's other context. A value that differs in the browser (the signed-in user, say) updates just that node on resume.
  • Without ssr, the remote's routes are 'client' routes: the shell's server sends the shell, and the browser renders them, as before. A remote that is down, or whose server entry fails to load, is rendered by the browser for that request; the next request tries again.

Resume. A remote with a server entry is built resumable: its route numbers carry its name ('payments:0', as HMR keys do), so its modules and route data sit in the page's state next to the shell's. Its component loads are positions in the one pass. When the browser will count them differently (a fragment, a remote it renders itself), the server shifts the positions after the remote, or leaves them to the browser. @qatjs/resume is shared like qat: list it in each party's dependencies. A shared @qatjs/resume does not stop the core from being trimmed.

examples/federation mounts all three below /ssr (e2e/ssr.spec.js): payments imported, account as a fragment (its /slow page outlasts the timeout and falls back to the browser), and account again at /ssr/me without ssr. The React widget on /ssr is client-only by nature: the server writes its element, and React renders inside it.

A remote's newer deploy, in an open page

A shell that imports @qatjs/federate/live switches each remote's newer deploy into the open page. Each remote is handled on its own, as @qatjs/core/version/live handles the shell's own deploys:

JavaScript6 lines
// shell/src/main.js
import '@qatjs/federate/live'
import { render } from '@qatjs/core'
import routes from './routes.js'

render(routes, document.getElementById('app'))
JavaScript5 lines
// payments/src/routes.js: a live build, as an app opts in
import '@qatjs/core/version/live'
import { page } from '@qatjs/router'

export default { '/': page('./pages/checkout.qx') }

qatjs federate writes the remote's build id into its qat.json. When the remote defines elements, it also writes a hash of its custom-elements.json (contract). When the page comes back or navigates, the shell reads each remote's qat.json again. For a newer build:

  • A changed remote switches alone. Its versions.json is checked as the shell's would be: state signatures, routes, qatjs api operations and markup. At a quiet moment its changed components are imported and re-created where they are, with their state, and their loads start from the data they had. The shell and the other remotes are not touched.

  • A contract change blocks only that remote. The shell was checked against the elements it booted with, so that remote keeps its build until the next full load. The others still switch.

  • A pinned remote is never switched. It keeps the build the page booted with:

    JavaScript2 lines
    // shell/qat.federate.js
    export default { name: 'shop', remotes: { payments: 'https://pay.example/qat.json' }, pin: ['payments'] }
  • A React, Vue or Angular remote is not switched in place: the next full load has it.

__qat.explain('remotes') gives each remote's running build, the newest one seen, and its state (running, waiting, switched, kept, pinned) with the reason.

Developing a remote

In dev every app is its own qatjs dev, and HMR crosses apps: the shell page's dev client listens to its own server and to every remote whose manifest is in dev form.

shell2 lines
qatjs dev payments --port 5174
qatjs dev shell --remote payments=http://localhost:5174
  • The dev manifest. A remote's qatjs dev serves qat.json with its exposes pointing at its per-file URLs (no bundle), "dev": true, "hmr": "ws://localhost:5174/__qat/hmr", and its own packages (its import map, minus the shared ones), which federate() scopes to its origin. It sends CORS headers.

  • Updates follow the HMR table unchanged, two hops (remote server → shell page, well under 100 ms): a remote component re-renders in place with its state kept (its HMR keys are prefixed with the remote's name, so two remotes' button.qx never collide); a remote routes.js replaces that table in the shell's router with the current page kept; a change to a remote's qat.federate.js (an expose added, shared versions changed) is a full reload, with the overlay saying why — the import map cannot change in place.

  • Pointing a remote elsewhere, dev only: --remote payments=http://localhost:5174 (a base URL gets /qat.json), or in .env.development:

    .env1 line
    PUBLIC_QAT_REMOTE_PAYMENTS=http://localhost:5174/qat.json

    A floating panel (dev builds only) lists each remote and where it comes from.

Inside the real shell: --shell

shell1 line
qatjs dev payments --shell https://portal.example --token "$PORTAL_OVERRIDE_TOKEN"

opens the deployed shell with payments loaded from your dev server (?__qat_override=<token>&__qat_remote=payments=http://localhost:5173/qat.json). The shell has to opt in:

JavaScript6 lines
// shell/qat.federate.js
export default ({ env }) => ({
  name: 'portal',
  remotes: { payments: 'https://pay.example/qat.json' },
  overrides: { token: env.PUBLIC_QAT_OVERRIDE_TOKEN },
})

The override is accepted only when the token matches; it is then kept for that browser (localStorage) until ?__qat_override=off, and it can only replace remotes the shell already has. A shell without overrides ignores override attempts entirely. The token is a switch, not a secret — it ships in the page — so set it in staging builds, not in builds that must never load code from elsewhere. --token defaults to PUBLIC_QAT_OVERRIDE_TOKEN from the remote's own env; --no-open prints the URL instead of opening it.

Demo

examples/federation: a shell, two Qat remotes (payments, account) and a React remote (widgets). pnpm e2e there runs the built apps (playwright.config.js: singleton merge, major mismatch, React isolation, a shell signal inside a remote) and the dev setup (playwright.dev.config.js: remote component and route edits, a new expose, --shell with and without the token).