@ogygia/router
Loading data
A load is a function of the request that returns a page's data. The loads of a page and its layouts run at the same time and merge outermost first, a shared load() runs once per request however often it's awaited, and a table-wide load guards every route.
On this page
A page needs data from somewhere before it renders: a database row, the signed-in user, a list from an API. A load fetches it. It’s a function of c, the request context, and it can be async. You give one to a page, to a layout, or to the whole table. Each request runs every load on the page’s branch, and the page gets their merged data.
Written in the table, a load needs no type annotation: the route’s key types c.params, and what it returns becomes the page’s data type in App. A load runs on the server only, so it can read a database or a secret.
import { routes, page, error } from '@ogygia/router';
import Post from '$lib/views/Post.svelte';
import { posts } from '$lib/server/posts';
export const router = routes({
'/posts/[slug]': page(Post, {
load: async (c) => {
const post = await posts.get(c.params.slug);
if (!post) error(404, 'No such post');
return { post, related: await posts.related(post.id) };
}
})
});
export type App = typeof router.$infer;Loads outside the table
To keep a long load in its own file, check it with satisfies Load<'/pattern'>. That types c.params from the pattern and keeps the load’s own return type, which App reads.
Use satisfies, not a : Load<…> annotation; Type code written outside the table says why.
A load checked against one pattern doesn’t fit a key with other params: postLoad on /docs/[id] is a type error. A load built outside a table without a pattern gets loose params (Record<string, string | undefined>) and fits any key.
import { error, type Load } from '@ogygia/router';
import { posts } from '$lib/server/posts';
export const postLoad = (async (c) => {
const post = await posts.get(c.params.slug);
if (!post) error(404, 'No such post');
return { post };
}) satisfies Load<'/posts/[slug]'>;import { routes, page } from '@ogygia/router';
import Post from '$lib/views/Post.svelte';
import { postLoad } from '$lib/server/post-load';
export const router = routes({
'/posts/[slug]': page(Post, { load: postLoad })
});Data merging
A page’s data is the merge of every load on its branch: the table-wide load, then each layout’s load from the outermost in, then the page’s own. Later loads win on a key they share. A load that returns nothing, or something that isn’t an object, adds nothing.
The page component and every layout read that merged object. page.data from $app/state is the same object, so a component anywhere on the page can read page.data.user, where a Kit user would look for it.
import { routes, page, layout } from '@ogygia/router';
import Shell from '$lib/views/Shell.svelte';
import DashShell from '$lib/views/DashShell.svelte';
import Dashboard from '$lib/views/Dashboard.svelte';
import { auth } from '$lib/server/auth';
import { teams } from '$lib/server/teams';
import { stats } from '$lib/server/stats';
const app = layout('app', Shell, {
load: async (c) => ({ user: await auth.user(c.cookies) })
});
const dash = layout('dash', DashShell, {
load: async (c) => ({ team: await teams.of(c.cookies) })
});
export const router = routes(
app({
...dash({
'/dashboard': page(Dashboard, {
load: async () => ({ stats: await stats.today() })
})
})
})
);
// App['/dashboard']['data'] is { user, team, stats }Shared loads
The loads on a branch all start at once, as in Kit, so a page with three loads waits for the slowest, not the sum. When one load needs another’s result, wrap the shared one in load() and await it. A load() value runs once per request: the layout’s own run and every await of it share one result. That’s Kit’s await parent(), without waiting on the whole parent.
A layout’s guard like admin’s runs beside the page’s load, not before it: all the loads on a branch start together. A page load with side effects, or one that must not run for a refused visitor, should await the shared load itself and check, or the check belongs in the table-wide load, which does run first. A layout’s guard never protects an action: on a form post, the action runs after the table-wide load and before any layout or page load. Check the visitor in the action itself, or in the table-wide load.
A failure is shared too: if session throws, every await session(c) in that request gets the same error, and the load doesn’t run again. A shared load called after its request has ended rejects with the reason the request ended.
load(fn) used in a page’s load slot takes the page’s params, like a bare function. Outside a table, load('/pattern', fn) types c.params from the pattern.
import {
routes,
page,
layout,
load,
redirect
} from '@ogygia/router';
import Shell from '$lib/views/Shell.svelte';
import AdminShell from '$lib/views/AdminShell.svelte';
import Users from '$lib/views/Users.svelte';
import { auth } from '$lib/server/auth';
const session = load(async (c) => ({
user: await auth.user(c.cookies)
}));
const app = layout('app', Shell, { load: session });
const admin = layout('admin', AdminShell, {
load: async (c) => {
const { user } = await session(c); // the same run as the app layout's
if (!user?.admin) redirect(303, '/login');
return { isAdmin: true };
}
});
export const router = routes(
app({ ...admin({ '/admin/users': page(Users) }) })
);Table-wide loads
routes(table, { load }) runs one load before every route the table matches, pages and endpoints alike. It’s Kit’s root +layout.server.ts load without a component: the place for a sign-in check when there’s no shared layout to hang it on. It runs first, once the route has matched and any when() gate has passed, and the branch’s own loads start after it ends. A path the table doesn’t match never runs it.
- Throw
redirect()to send the visitor elsewhere. No other load runs. - Return a
Responseto answer with it. No other load runs, and the route never runs. - Return data, and it merges into every page’s
data, outermost.
Don’t turn a visitor away with error() from this load yet. To fill in the error page, the router then runs every load on the page’s branch anyway, as the visitor you just refused, and hands their data to the error page. That data reaches the browser if an island on the error page reads page (#2294). An error() from a layout’s load or an action does the same. Until that’s fixed, a guard should redirect() a page request to a sign-in page and return a Response to an endpoint call, and the loads behind it shouldn’t rely on an error() guard to keep secrets out of their data.
Its data isn’t in the App type yet; see Where inference stops.
The guard below lets the sign-in page through and checks everything else:
- It tells routes apart by
c.route.id, the matched key, not byc.url.pathname. The key is the same under abaseand whatever theslashpolicy, so the sign-in page is never sent to itself in a loop. - It builds the sign-in URL with
c.href(), which puts thebasein front. - An endpoint behind the guard gets a
401Response, not a redirect. A redirect would send the typed client to an HTML page, which it would read as the endpoint’s answer.
An endpoint doesn’t get the table-wide load’s data. Hand it over through c.state, the per-request scratch object, as the guard above does with c.state.user, or make the guard a shared load() and await it in the handler.
import { routes, page, redirect } from '@ogygia/router';
import Home from '$lib/views/Home.svelte';
import Login from '$lib/views/Login.svelte';
import { auth } from '$lib/server/auth';
export const router = routes(
{
'/': page(Home),
'/login': page(Login),
'/api/me': { GET: (c) => c.state.user }
},
{
load: async (c) => {
if (c.route.id === '/login') return;
const user = await auth.user(c.cookies);
if (!user) {
if (c.route.id.startsWith('/api/'))
return new Response('Unauthorized', { status: 401 });
const next = encodeURIComponent(
c.url.pathname + c.url.search
);
redirect(303, `${c.href('/login')}?next=${next}`);
}
c.state.user = user;
}
}
);Responses from loads
A load can return a Response instead of data. The response is sent as it is, and nothing renders. Use it for a load that sometimes has to answer with a file or a redirect it builds itself. In App, the Response arm is dropped from data, so the component sees only the data arm.
import { routes, page } from '@ogygia/router';
import Invoice from '$lib/views/Invoice.svelte';
import { invoices } from '$lib/server/invoices';
export const router = routes({
'/invoices/[id]': page(Invoice, {
load: async (c) => {
const invoice = await invoices.get(c.params.id);
if (c.search.format === 'pdf') {
return new Response(await invoices.pdf(invoice), {
headers: { 'content-type': 'application/pdf' }
});
}
return { invoice };
}
})
});Load timing
- On every
GETandHEADof the page. - After an action, on a
POST: the action runs first, then every load, so the page renders with fresh data and the action’sform. - For the error page, when an
error()is thrown anywhere on the branch: every load on the branch runs, the ones that hadn’t started yet included. See What data the error page gets.
The page’s and layouts’ loads never run for a params or search schema miss, which answers before they start. The table-wide load has already run by then: it runs before the page checks its schemas.
Invalidation
There’s no depends(). On a router page, invalidate(url) and invalidateAll() from $app/navigation both fetch the page again, which runs every load on its branch, and islands that read page update. A remote form() does the same after a successful submit. See Refresh the page’s data.
This needs the SPA router. With ogygia({ router: false }), these calls may do nothing (#2277).