@ogygia/router
Streaming
A router page can send its fast part at once and the slow part later, on the same response. Write the page as an async generator, or return a promise of a region from a load and place it with <Region of>.
On this page
Some pages have one slow part: a report that takes two seconds to compute, a panel fed by a slow service. Waiting for it delays the whole page. A router page can send everything else at once and send the slow part when it’s ready, down the same response, with no second request from the browser.
There are two ways. A streamed page is an async generator in place of the component: its first yield goes out with the document, and each later yield replaces it. A late region is a promise of a region in a load’s data, placed with <Region of>: its placeholder goes out with the document, and the region follows. A page can have any number of late regions.
import { routes, page, type Ctx } from '@ogygia/router';
import { region } from 'ogygia';
import Report from '$lib/views/Report.svelte' with {
region: 'raw'
};
import { reports } from '$lib/server/reports';
export const router = routes({
'/report': page(async function* (c: Ctx) {
yield '<p class="skeleton">Crunching the numbers…</p>';
yield region(Report, {
numbers: await reports.compute(c.url.searchParams)
});
})
});Streamed pages
Pass an async generator function to page() where the component would go. It gets c, the request context, and data, the merged data of the branch’s loads, so it can take load and the other page() options like any page. Its output renders inside the page’s layouts. The table can’t type a generator’s arguments for you, so annotate them: Ctx<Params<'/pattern'>> for c, and the shape your loads return for data.
- The first yield renders into the document, and the document goes out right away.
- Each later yield is sent down the same response as it comes and replaces what’s in the slot, in order. Several yields give you progressive states.
- The response ends when the generator returns.
You can yield an HTML string, or a region made with region(Component, props) from ogygia. A region carries its CSS, and the islands inside it wake when it lands, with no extra code: they’re self-waking custom elements.
A yielded string is put in the page as it is, so anything from a database or a visitor in it must be escaped first. Yielding a region, as the example does for the title, lets Svelte do that.
Mark the components you yield
Mark the import of a component you yield: with { region: 'raw' }, or a wake if it should run in the browser. A marked component’s region brings its stylesheet with it. A plain import still renders to HTML, but its component styles aren’t linked, so it shows up unstyled. See Choose how the component is imported.
What a stream can’t change
- Status and headers go out with the first yield. A failure later can’t turn a 200 into an error, and
c.setHeaders()after the first yield is lost. - A throw after the first yield becomes an error card in the slot, “This section failed to load.”, followed by the message. The page still ends cleanly. The message is shown to the visitor as thrown, and your
handleErrorisn’t called, so catch errors that may hold internal details (a database error, say) and throw a plain one (#2294). - A throw before the first yield, or while the first yield renders, is a normal failure, not a card. An
error()renders the error page; anything else gets Kit’s 500. A generator that ends without yielding anything answers 500 through the error page. - Only
GETstreams. APOST(after an action) and aHEADrun the generator to the end and render its last yield, since an action’s answer has to be complete. - The visitor leaving ends the generator. The router calls its
return(), so afinallyin it runs. A cleanup that throws is logged asrequest_cleanup_failed. - Compressing proxies. A streamed response carries
cache-control: no-transform, added to anycache-controlthe page set. A proxy or CDN that compresses a response buffers it first, which turns the stream into one late paint;no-transformasks it to pass the bytes through. If your CDN compresses anyway, exempt these routes from compression or accept buffered delivery.
import {
routes,
page,
layout,
type Ctx,
type Params
} from '@ogygia/router';
import { region } from 'ogygia';
import Shell from '$lib/views/Shell.svelte';
import Heading from '$lib/views/Heading.svelte' with {
region: 'raw'
};
import Summary from '$lib/views/Summary.svelte' with {
region: 'raw'
};
import Detail from '$lib/views/Detail.svelte' with {
region: 'raw'
};
import { reports } from '$lib/server/reports';
const app = layout('app', Shell);
export const router = routes(
app({
'/reports/[id]': page(
async function* (
c: Ctx<Params<'/reports/[id]'>>,
data: { title: string }
) {
yield region(Heading, { title: data.title }); // Svelte escapes the title
yield region(Summary, {
summary: await reports.summary(c.params.id)
});
yield region(Detail, {
detail: await reports.detail(c.params.id)
});
},
{
load: async (c) => ({
title: await reports.title(c.params.id)
})
}
)
})
);Late regions
A load can return a promise of a region instead of waiting for it. Place it with <Region of={data.part}> and give the Region a placeholder snippet. The page goes out with the placeholder in place. When the promise settles, the region is baked and sent down the same response, and swaps in. This works on any router page answering a GET, streamed or not, and needs no generator.
- Late regions stream in the order they finish, not the order they’re on the page.
- A promise that rejects shows an error card in its own slot. The others still come. As with a streamed page, the card shows the rejection’s message as it is and
handleErrorisn’t called, so reject with a plain message (#2294). - A late region can hold a
<Region of>of its own; that one streams too, and the response ends only when every slot is filled. - A page with late regions gets the same
cache-control: no-transformas a streamed page. - The promise must resolve to a region or an HTML string. One that resolves to anything else ends the stream: its slot and every slot still waiting keep their placeholders, and on a streamed page the page’s own slot is replaced by an error card (#2293).
After a form post
Late regions stream only on a GET. The page an action renders, on a POST, has no stream, so a <Region of={promise}> on it does one of two things:
- With Svelte’s async mode on (
compilerOptions.experimental.async), the server waits for the promise and the page arrives with the region in it, as late as the slowest one. - Without it, the page shows the placeholder, and nothing ever fills it.
So end an action that changed something with redirect(303, …), as the forms page advises: the browser then GETs the page and the region streams. For an action that returns fail() or data and renders the page, await that part in the load when the request is a post: c.request.method === 'POST' ? await part : part.
Plain data doesn’t stream
A promise of plain data, not a region, isn’t streamed into islands on a router page, as it would be on a Kit page: the page seed leaves it out. Wrap the slow part in a region, as above.
import { routes, page } from '@ogygia/router';
import { region } from 'ogygia';
import Dashboard from '$lib/views/Dashboard.svelte';
import Usage from '$lib/views/Usage.svelte' with {
region: 'raw'
};
import { usage } from '$lib/server/usage';
export const router = routes({
'/dashboard': page(Dashboard, {
load: async (c) => ({
usage: usage
.forUser(c.cookies)
.then((rows) => region(Usage, { rows })) ,
greeting: 'Welcome back'
})
})
});<script lang="ts">
import { Region } from 'ogygia';
import type { App } from '$lib/router';
let { data }: App['/dashboard'] = $props();
</script>
<h1>{data.greeting}</h1>
<Region of={data.usage}>
{#snippet placeholder()}<p class="skeleton">
Loading usage…
</p>{/snippet}
</Region>