Skip to content

@ogygia/federation

Mounting apps

mount(peer) is one route-table entry that serves a whole peer app under your layouts, with its status, head, redirects and form posts carried through. Stream it, canary it with a flag, or mount it from a plain SvelteKit route with mount.kit().

On this page

A remote region is a slot your page owns. A mount is a route the peer owns: every URL under it is the peer’s page, rendered inside your layouts. One entry in a server router table does it:

sessions.claims() stands for your own code that turns a session cookie into { sub, … }, or undefined for an anonymous visitor. The peer is the cms app, which exposes its table with base: '/cms'.

import { routes, layout } from '@ogygia/router';
import { mount } from '@ogygia/federation';
import { cms } from '$lib/server/peers';
import { sessions } from '$lib/server/sessions';
import Chrome from '$lib/Chrome.svelte';
import ChromeError from '$lib/ChromeError.svelte';

const chrome = layout('chrome', Chrome, { error: ChromeError });

export const router = routes(
  { ...chrome({ '/cms/[...rest]': mount(cms) }) },
  { visitor: (c) => sessions.claims(c.cookies?.get('session')) }
);

Paths

A mount reads the catch-all param, which must be named rest, and asks the peer for /<rest> with the request’s query string. The peer renders it at its base plus that path. So /cms/posts/1 on your app is the peer’s /posts/1, which it serves at /cms/posts/1.

Mount under the same prefix as the peer’s base. Links and form actions in the peer’s HTML are written in the peer’s own address space, /cms/…, and stay as they are, since your app owns the address space they resolve in. Its redirects name the same addresses. Mounted under another prefix, the first page renders but its links lead elsewhere.

Documents

A GET loads the peer’s page document, and the mount renders it in your layout. Three things come with it besides the body:

  • The status. The peer’s own 404 or 500 page renders under your layouts, and your app answers with that status, since a 200 around an error page misleads caches and search engines.
  • The head. The peer page’s <title>, its stylesheets, and its SEO and social tags (description, og:*, a canonical link) join your head. charset, viewport, http-equiv and ogygia’s own ogygia-* metas stay yours.
  • Redirects. A redirect from the peer is thrown again as your redirect, with the same status and location.

A peer that’s down, or slower than its timeout, fails the load with a 502, 503 or 504, and your nearest error boundary renders, as with any failed load. Another team’s outage can’t hang your page.

Forms

A POST to a mounted page forwards the form body and its content type to the peer, which runs its own default action. When the action redirects, as a post-redirect-get action does, your app answers with a 303 to the same location. A POST never goes to a replica, and it clears the peer’s whole document cache. It’s sent with the peer’s first origin as its Origin header, which the peer’s Kit must accept as its own: when the peer runs with a different public ORIGIN, add that first origin to its csrf.trustedOrigins, or every mounted form gets a 403 (#2312).

Only the peer’s default action can be reached. A form that names an action (action="?/save") gets a 404 from your app, because the mount has only a default action of its own (#2311, item 5).

Stored pages

A mounted page isn’t filed under the peer’s thaw tags today, so a publish or a deploy on the peer never clears a copy postrender stored (#2311, item 11). Only the in-memory document cache is dropped. Keep mounted routes out of the store, or clear them yourself when the peer changes, such as with postrender.invalidateWhere({ prefix: '/cms/' }) on your app.

Streamed mounts

mount(cms, { stream: true }) sends your layout straight away with a placeholder in the slot, and swaps the peer’s page in down the same response when it answers. A slow team then can’t hold back your first byte. stream: { fallback } takes an HTML string or a component for the placeholder:

Streaming changes what can arrive late. The status and headers are sent before the peer answers, so a peer’s error status can’t reach the response: the slot shows the “This section is temporarily unavailable.” card instead, as it does for a peer that fails. A redirect shows a “This page moved.” link to the new address. No Server-Timing or x-og-trace for the peer is sent (#2311, item 14). Only GET streams; a POST goes through the same action as an unstreamed mount.

import { routes } from '@ogygia/router';
import { mount } from '@ogygia/federation';
import { cms } from '$lib/server/peers';
import Skeleton from '$lib/Skeleton.svelte';

export const router = routes({
  '/cms/[...rest]': mount(cms, {
    stream: { fallback: Skeleton }
  })
});

Canaries and rollouts

In place of a peer, mount() takes a choice made per request. A flag’s pick() chooses between two peers, which is a canary or blue-green deploy of another team’s app, sticky per visitor:

when(gate, mount(peer)) makes the route exist only for the visitors the gate lets through (Conditional routes). A plain function works too, mount((c) => peer). Each peer keeps its own cache and shared fetches; the choice only picks between handles federate() already made. A function or pick that returns something other than a peer throws federation_mount_no_peer.

import { routes, when } from '@ogygia/router';
import { flag } from '@ogygia/flags';
import { mount } from '@ogygia/federation';
import { cmsV1, cmsV2 } from '$lib/server/peers';

const cmsV2On = flag('cms-v2', 10);
const cmsBeta = flag('cms-beta');

export const router = routes({
  '/cms/[...rest]': mount(
    cmsV2On.pick({ off: cmsV1, on: cmsV2 })
  ),
  '/beta/[...rest]': when(cmsBeta, mount(cmsV2))
});

Identity

A mount signs the visitor into each call: the router’s c.visitor, with every flag decision the request has made so far added under experiments. federate({ visitor }) isn’t used here, so a table without its own visitor sends anonymous calls. The user option replaces c.visitor for one mount, and the flag decisions are still added:

Visitor identity has what each kind of call carries.

import { routes } from '@ogygia/router';
import { mount } from '@ogygia/federation';
import { cms } from '$lib/server/peers';

export const router = routes({
  '/cms/[...rest]': mount(cms, {
     user: (c) =>
      c.visitor ? { sub: c.visitor.sub } : undefined 
  })
});

Response headers

Each mounted response, unless it’s streamed, gets Server-Timing entries for the peer: <label>;dur= for the call as your app saw it, and <label>-render;dur= for the peer’s own render, where the label is the peer’s label, its name by default. x-og-trace carries the trace id of the peer’s render (Tracing).

Plain SvelteKit

A shell doesn’t need the server router. mount.kit(peer, options) mounts a peer from an ordinary Kit catch-all route, here src/routes/cms/[...rest]/. It returns a load and a default action:

user gets the load’s event, typed with only params, url, request and setHeaders, so sessions.fromRequest() stands for code that reads your session cookie from the request’s headers. The page prints the document itself:

It uses the same peer, signing, cache and timeouts, with these differences:

  • Identity comes from the user option alone, read from the event: there’s no c.visitor outside the router, and flag decisions aren’t added.
  • Errors from the peer’s page become Kit’s error(status): the status is right, but your error page renders, not the peer’s. A peer that’s down or too slow throws the router’s own error, which Kit doesn’t know, so it answers 500 (#2311, item 6).
  • param names the catch-all param when it isn’t rest: mount.kit(cms, { param: 'path' }) for [...path].
  • No streaming. mount.kit() takes no stream option.

{@html} prints the peer’s HTML as it came, so mount only peers you trust with your page.

import { mount } from '@ogygia/federation';
import { cms } from '$lib/server/peers';
import { sessions } from '$lib/server/sessions';

const m = mount.kit(cms, {
  user: (e) => sessions.fromRequest(e.request)
});

export const load = m.load;
export const actions = m.actions;
<script lang="ts">
  import type { PageProps } from './$types';

  let { data }: PageProps = $props();
</script>

<svelte:head>
  {#if data.doc.title}<title>{data.doc.title}</title>{/if}
  {@html data.doc.css.join('') + (data.doc.head ?? '')}
</svelte:head>

{@html data.doc.body}