Skip to content

Regions

Held regions

A region as a value. The server picks the component and its props in a load or a remote function, and the page renders whatever arrives with <Region of={…} />, without importing the component itself.

On this page

Sometimes the server, not the page, knows which component should appear. A search returns a result card or an empty state. A feed mixes several item types. A CMS decides which blocks make up a page. A server island can’t help here, because it fills a fixed hole with a fixed component.

A held region lets the server choose. region(Component, props) packs a component and its props into a value. You can return that value from a load or a remote function, put it in an array, pass it around, and render it with <Region of={value} />. The props are type-checked against the component. When the region comes from a load or a remote function, the page that renders it never imports the component, so its code isn’t in the page’s bundle.

A region made and rendered in the same server pass, like this one, renders inline as part of the page. The rest of this page is about regions that travel. To send a region again when its data changes, see Live regions.

<script>
  import { region, Region } from 'ogygia';
  import Card from '$lib/Card.svelte';
  let { data } = $props();

  const card = region(Card, { title: data.title });
</script>

<Region of={card} />

Import marks

How you import the component decides what the region can do once it leaves the server:

ImportWhat the region is
import Card from './Card.svelte'HTML only. It can travel when it’s awaited, as its rendered HTML.
import Card from './Card.svelte' with { region: 'raw' }HTML only, with a signed address, so the browser can also fetch it later. No schedule unless the region() call gives one.
import Card from './Card.svelte' with { wake: 'load' }Interactive. It travels with a signed address and hydrates on that schedule.
import Card from './Card.svelte' with { render: 'deferred' }In a .ts module, a server island you can place or hand to region(). Where it’s placed, it shows its fallback and fetches its HTML on its fetch schedule ('load' by default).

A plain import is enough when the region is returned straight from a remote function, because the return awaits it. When a plain-import region ends up somewhere that isn’t awaited (inside an array, say), nothing can fetch it, and it fails with held_region_plain_import. Mark the import region: 'raw' or wake to fix that.

A region: 'raw' component is signed with your server’s key, so region() on it has to run on the server: in a load, a remote function or a component’s server render. In browser code it throws raw_region_on_client. A wake-marked component is a real component in the browser too, and region() there makes an inline region.

In a .ts or .js module, an import takes exactly one marker: region: 'raw', wake, or render: 'deferred' with an optional fetch (held_marker_mixed). fetch without render: 'deferred' fails with held_fetch_without_render. render: 'live' is for .svelte files only, and so is wake: 'none': a .ts module refuses it (wake_strategy_unknown).

In the example, results.ts imports one component of each kind: an interactive card, a raw empty state that can be fetched later, and a plain banner that travels only when awaited.

import PackageCard from '$lib/PackageCard.svelte' with {
  wake: 'load'
};
import EmptyResult from '$lib/EmptyResult.svelte' with {
  region: 'raw'
};
import Banner from '$lib/Banner.svelte';

Remote functions

The common case is a remote function that picks a component. Here the server looks the query up and returns an interactive card for a hit, or a static empty state for a miss. The page calls the remote and renders what comes back.

Two pieces of setup are needed: Kit’s remote functions turned on in your Kit config (kit.experimental.remoteFunctions on Kit 2), and ogygia’s transport hook in src/hooks.ts, which lets Kit send regions from the server to the browser.

Search has to be an island, because its form handler runs in the browser. Mark its import wake where you place it.

import { query } from '$app/server';
import { region } from 'ogygia';
import * as v from 'valibot';
import PackageCard from '$lib/PackageCard.svelte' with {
  wake: 'load'
};
import EmptyResult from '$lib/EmptyResult.svelte' with {
  region: 'raw'
};
import { findPackage } from '$lib/server/packages';

export const search = query(v.string(), async (q) => {
  const hit = await findPackage(q);
  return hit
    ? region(PackageCard, hit)
    : region(EmptyResult, { query: q });
});
<script>
  import { Region } from 'ogygia';
  import { search } from '$lib/search.remote';

  let q = $state('');
  let query = $state('');
</script>

<form onsubmit={(e) => { e.preventDefault(); query = q; }}>
  <input bind:value={q} />
  <button>Search</button>
</form>

{#if query}
  <Region of={search(query)}>
    {#snippet placeholder()}<p>Searching…</p>{/snippet}
  </Region>
{/if}
<script>
  import Search from '$lib/Search.svelte' with {
    wake: 'load'
  };
</script>

<Search />

Demo

The demo below is that search box, as an island on this page. Try svelte, kit, vite or ogygia; anything else returns the empty state. This page never imports either result component.

Held region ready

Search to fetch a component from the server.

each search is a new server round trip · the demo server waits 400ms

The card’s star button works, which shows it hydrated. The empty state ships as HTML only: the page source has no JavaScript for it.

Placeholders

Fetching a held region has two waits that end at different times. First the request runs and the remote call resolves. Then the paint happens: the HTML lands and its stylesheet loads. A loading flag, an {#await} or a boundary next to the call only sees the first wait, so it reports “done” before the card is on screen.

So don’t track the wait yourself. Pass the promise from the remote call straight to of, and give <Region> a placeholder snippet. Children work too: they’re passed to the rendered component as its children, and also shown as the waiting UI when there’s no placeholder. The region shows the waiting UI from the moment you call until the styled card paints. With neither, it sits empty meanwhile, and dev says so (region_promise_no_placeholder).

On a slow connection, from submit:

TimeWhat’s happeningOn screen
0 msrequest in flightthe placeholder
request resolvesHTML is here, its stylesheet is downloadingstill the placeholder
stylesheet loadsthe region paintsthe styled card, in one step

A new query gives of a new promise. The region keeps the previous card on screen until the next one has its styles, then morphs it in place, so there’s no placeholder flash between results.

The wait exists because a held region brings its own CSS: the page never imported PackageCard, so its styles are in none of the page’s stylesheets. A held region rendered during the page’s server pass (a blocks page, say) has no wait at all: its stylesheet links go into the <head> during SSR. The stylesheet wait is capped at 5 seconds, so a broken sheet still paints.

placeholder is for held regions. ogygiaFallback is the reserved slot of a render: 'deferred' server island, which is a fixed hole rather than a value you place.

Don’t await it yourself

With Svelte’s async mode on, you can write of={await search(query)} inside a <svelte:boundary> and let its pending snippet show the wait. Don’t: the boundary stops waiting when the fetch resolves, while the region still has its HTML and stylesheet to land, so your “done” fires early.

The runtime still protects you, since a region never paints without its styles; it keeps its previous content, its placeholder or empty space until the sheet is in. Boundaries, {#await} and loading flags are still the right tools for your own UI around the region.

How a promise renders depends on where it’s rendered. With Svelte’s async mode, it’s awaited during the server render, so the page arrives with the region in it. On a server router page, the placeholder flushes with the document and the region streams in later on the same response. Otherwise, the server renders the placeholder and the browser fills it in after the page loads.

<script>
  import { Region } from 'ogygia';
  import { search } from '$lib/search.remote';
  let { query } = $props();
</script>

<Region of={search(query)}>
  {#snippet placeholder()}<p class="hint">Searching…</p>{/snippet}
</Region>

Per-value schedules

A wake mark on the import bakes one schedule into every region made from it. For a registry of region: 'raw' components where each block decides from its own data, pass a function as the third argument of region(). It gets the props and returns { wake, margin }. Return wake: undefined for HTML only.

The third argument is either this schedule function or { version } (ordering answers), not both.

import { region } from 'ogygia';
import Block from '$lib/Block.svelte' with { region: 'raw' };

export function block(data: {
  interactive: boolean;
  html: string;
}) {
  return region(Block, data, (d) => ({
    wake: d.interactive ? 'visible' : undefined
  }));
}

Marked bindings

A marked import in a .ts file is a real component, not only something to hand to region(). Code that renders components it gets from a list (a page builder, a CMS renderer) can place it with <Component />, and it becomes a region there, with its code loaded only when it’s placed and its schedule fires. The same binding can still travel through region(), so one registry serves both.

A named import from a package takes the same mark and makes the same binding. A region: 'raw' import stays a description only: it renders through region(), not by placing it directly.

To render a whole page-builder tree from a registry, see Blocks, which builds on this.

import Widget from '$lib/Widget.svelte' with {
  wake: 'visible'
};
import { Header } from '@acme/ui' with { wake: 'load' };

export const registry = { widget: Widget, header: Header };
<script>
  import { registry } from '$lib/registry';
  let { blocks } = $props();
</script>

{#each blocks as block}
  {@const Component = registry[block.type]}
  <Component {...block.props} />
{/each}

Batching

Every example so far sends one region. A value can hold any number. The regions in it are the only parts that carry a component; everything else is plain data. So arrays, records and nesting all work, as long as each component in the value is wrapped in a region. The transport walks the value and signs each region it finds, wherever it sits. A region can even be a prop of another region.

What awaiting a region does

await region(…) renders the component on the server and puts that HTML in the value, so the region paints as soon as the response lands, with no extra request. Returning a region from an async remote function does the same, because return awaits it.

Regions nested inside an array or an object aren’t awaited, so they travel as signed addresses, and the browser fetches each one when it’s placed. To bake them too, await them: await Promise.all(items.map(...)).

Keep a returned region lazy

Sometimes you want a returned region to stay an address, so the response carries no rendered HTML and the browser fetches the region only when it’s placed. To do that, spread it. A region’s then isn’t enumerable, so the copy isn’t awaited.

Turn a shape back into markup

When the shape needs interpreting (a tree, a feed with headers, a layout), send an ordinary marked component that takes the shape as props and renders it, with a <Region of={item} /> per leaf. Awaited, the whole composition renders in one server pass, with every leaf’s stylesheet in one payload. This works recursively, so a whole page of blocks can cross as one value.

import { query } from '$app/server';
import { region } from 'ogygia';
import * as v from 'valibot';
import Ad from '$lib/Ad.svelte' with { region: 'raw' };
import Card from '$lib/Card.svelte' with { wake: 'visible' };
import { loadFeed } from '$lib/server/feed';

export const feed = query(v.string(), async (user) => {
  const items = await loadFeed(user);
  return items.map((item) =>
    item.sponsored ? region(Ad, item) : region(Card, item)
  );
});
import { query } from '$app/server';
import { region } from 'ogygia';
import * as v from 'valibot';
import Card from '$lib/Card.svelte' with { region: 'raw' };

// the spread drops the region's `then`, so this returns an address, not baked HTML
export const card = query(v.string(), async (id) => ({
  ...region(Card, { id })
}));
import { query } from '$app/server';
import { region } from 'ogygia';
import * as v from 'valibot';
import FeedList from '$lib/FeedList.svelte' with {
  region: 'raw'
};
import Card from '$lib/Card.svelte' with { wake: 'visible' };
import { loadFeed } from '$lib/server/feed';

export const feedTree = query(v.string(), async (user) => {
  const items = await loadFeed(user);
  return region(FeedList, {
    items: items.map((item) => region(Card, item))
  });
});
<script>
  import { Region } from 'ogygia';
  let { items } = $props();
</script>

<ul>
  {#each items as item}<li><Region of={item} /></li>{/each}
</ul>

Preloading

preload(region) from ogygia fetches a region’s HTML now and keeps it ready, so when the region is placed later it paints without a round trip. It takes a region value that arrived as an address, such as one nested in an array a remote function returned. Call it in the browser, from an island. It does nothing on the server, and nothing for a region whose HTML is already baked in.

In this example, Tabs is an island that gets one region per tab from a remote query. Hovering a tab warms that tab’s HTML, so the click shows it at once.

<script>
  import { preload, Region } from 'ogygia';
  import { tabs } from '$lib/tabs.remote';

  const list = tabs();
  let active = $state(0);
</script>

{#if list.current}
  {#each list.current as tab, i}
    <button
      onpointerenter={() => /*MK<*/ preload(tab.body)}
      onclick={() => (active = i)}
    >
      {tab.label}
    </button>
  {/each}
  <Region of={list.current[active].body} />
{/if}

Regions as pages

document(region, options) from ogygia/server renders a region into a complete HTML Response: doctype, head, the runtime, and the region’s HTML with its islands. Use it to answer a request from a handle or a +server.ts endpoint without a Kit page.

Its options:

  • title: the <title>, used only when no component set one with <svelte:head>.
  • head: extra HTML for the head, such as meta tags and fonts.
  • status: the HTTP status, 200 by default.
  • headers: extra or replacement response headers. By default the response has content-type set and cache-control: no-store; pass your own cache-control to cache it.
  • lang: <html lang>, 'en' by default.
  • pageState: what islands on the page read from $app/state (url, params, route, status, data, form, error). Without it, page.url and page.status come from the request and page.data is empty.
import { document } from 'ogygia/server';
import { region } from 'ogygia';
import Preview from '$lib/Preview.svelte';
import type { RequestHandler } from './$types';

export const GET: RequestHandler = async ({ url }) => {
  return document(
    region(Preview, { id: url.searchParams.get('id') ?? '' }),
    {
      title: 'Preview'
    }
  );
};

Do and don’t

  • Do use a held region when the server decides which component to show, and a server island when the component is fixed.
  • Do import result components region: 'raw' when they never need interaction. They ship no JavaScript.
  • Do pass the promise to of and use placeholder.
  • Don’t import the result components in a page that gets its regions from a load or a remote. The server sends them.