@ogygia/router
Types
The table's $infer type gives every page, layout and endpoint its types, read from the loads, actions, handlers and schemas you wrote, with no codegen. A params or search schema coerces the URL into real types, and Load, Action and Handler type code written outside the table.
On this page
Kit generates a ./$types module per route. The router doesn’t generate anything: the table is a value, so TypeScript reads the types straight from it. You export one type from the module that builds the table, and every component indexes it by route.
$infer exists only as a type. Always write typeof router.$infer: reading router.$infer as a value throws.
The types come from what you wrote in the table: the patterns, the loads’ return types, the actions’ return types, the handlers’ return types and the schemas. They never come from the components, so there’s no cycle between the component that reads App and the module that imports the component.
import { routes, page } 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) => ({
post: await posts.get(c.params.slug)
})
})
});
export type App = typeof router.$infer;App types
App has one key per route and one per layout:
| Key | Holds |
|---|---|
A page’s pattern, '/posts/[slug]' | { data, form, params, search } |
A layout’s name in parentheses, '(app)' | { data, children } |
An endpoint’s pattern, '/api/posts/[id]' | One key per verb, in lowercase, each { out, in }, and params |
- A page’s
datais what every load on its branch returns, merged: each layout’s around it, then its own. A load that may return aResponseadds only its other arm. formis the union of what its actions return, eachfail()unwrapped to its data, plusnull. See Type the form prop.paramsis read from the pattern, or is theparamsschema’s output.searchis thesearchschema’s output, or{}with no schema.- A layout’s
datais typed as what its load and every layout around it return. At run time it holds the page’s whole merged data. - An endpoint verb’s
outis the handler’s plain return value,unknownwhen it returns aResponse.inis the body schema’s output,undefinedwith none. The typed client reads both.
Path keys always start with / and layout keys with (, so the two never collide.
Declaring the props as App['/posts/[slug]'] is the check. If the load stops returning post, the component no longer type-checks, the same flow as Kit’s PageProps.
Params from a pattern
Every kind of segment gives its param a type:
| Pattern | params |
|---|---|
/about | {} |
/docs/[slug] | { slug: string } |
/[[lang]]/docs | { lang?: string } |
/files/[...path] | { path: string } |
/report/[id].json | { id: string } |
The params are strict: inside the table, reading c.params.slug on a route that has no slug is a type error, in a load, an action or a handler. Params<'/docs/[slug]'> gives the same type anywhere.
<script lang="ts">
import type { App } from '$lib/router';
let { data, params }: App['/posts/[slug]'] = $props();
</script>
<h1>{data.post?.title ?? params.slug}</h1>Param schemas
Path params are strings. A page’s params option takes a Standard Schema (Valibot, Zod, ArkType, and others) that turns them into what you need. It runs before the action and the page’s and layouts’ loads (only the table-wide load runs earlier), and its output replaces c.params in the page’s load and actions, params in App, and the params prop.
A path whose params fail the schema answers a plain-text 404 Not found: a post id that isn’t a number names no post. No error page renders, and the page’s and layouts’ loads don’t run (the table-wide load already has). It’s also how to do what Kit’s param matchers do, with one difference: a failed schema doesn’t let another route try the path, it answers 404. Two routes that differ only by a matcher in Kit need different patterns here.
import { routes, page } from '@ogygia/router';
import * as v from 'valibot';
import Post from '$lib/views/Post.svelte';
import { posts } from '$lib/server/posts';
export const router = routes({
'/posts/[id]': page(Post, {
params: v.object({
id: v.pipe(v.string(), v.toNumber(), v.integer())
}) ,
load: async (c) => ({ post: await posts.byId(c.params.id) }) // c.params.id: number
})
});
export type App = typeof router.$infer; // App['/posts/[id]']['params'] is { id: number }Query strings
Without a schema, c.search is an object of strings, one per query key. A key that appears twice keeps its first value; read c.url.searchParams.getAll(key) for every value.
A page’s search option takes a Standard Schema for the query. Its output types c.search in the page’s load and actions, and search in App. Every value arrives as a string, so a number needs a conversion in the schema. A schema default fills a key that’s missing.
A query that fails the schema answers 400 with { "error": "Invalid query", "issues": [{ "message", "path" }] }, before any page load runs.
The page component isn’t given a search prop, though App['/archive'] has a search field. Return what the component needs from the load, as page above.
Endpoints have no search schema. Their body has one: see Validate a request body.
import { routes, page } from '@ogygia/router';
import * as v from 'valibot';
import Archive from '$lib/views/Archive.svelte';
import { posts } from '$lib/server/posts';
export const router = routes({
'/archive': page(Archive, {
search: v.object({
page: v.optional(
v.pipe(
v.string(),
v.toNumber(),
v.integer(),
v.minValue(1)
),
'1'
) ,
tag: v.optional(v.string())
}) ,
load: async (c) => ({
list: await posts.page(c.search.page, c.search.tag), // page: number, tag: string | undefined
page: c.search.page
})
})
});Helpers outside the table
Inside the table, the key types everything. Code in another file needs a pattern to type its c. Check it with satisfies, which types c and keeps the function’s own return type, the part App reads:
| Helper | Types |
|---|---|
Load<'/pattern'> | A load. See Write a load outside the table. |
Action<'/pattern'> | A form action. |
Handler<'/pattern', Input> | An endpoint handler, with c.input typed as Input. |
Don’t annotate with these (const l: Load<'/p'> = …): an annotation sets the return type to unknown, so data, form or the endpoint’s out loses its type. The API page still shows an annotation for Load; see below.
The other exported types:
Ctx<Params, Search, Input>is the type ofc.Params<'/pattern'>is a pattern’s params.HrefParams<'/pattern'>is whathref()takes for it, strings or numbers, andHrefArgs<'/pattern'>its argument list, with params optional when no param is required.InferOutput<Schema>is a Standard Schema’s output type, andStandardSchemaV1the schema type itself.InferMap<Table>is what$inferis, for a table type you hold.Simplify<T>flattens an intersection for display.Router,RoutesOptions,PageServer,PageDef,LayoutDef,LoadDef,ActionDef,Endpoint,VerbEntryandRouteTabledescribe the valuesroutes(),page(),layout(),load(),action()and the verb wrappers return.ActionFailure<Data>is whatfail()returns.AnyComponentis any Svelte component, andComponentPickwhat a flag’spick()returns, the two thingspage()takes besides a generator.CompiledPatternis whatcompile()returns.ApiClient<App>andApiClientOptionstype the typed client, andAnonymousVisitorOptionsthe options ofanonymousVisitor().
Params suits a server function that several routes’ code calls with one route’s params. Here a page’s load and an endpoint share one lookup, and passing it params of the wrong shape is a type error. The check is by shape, not by route: another route’s params with the same names pass.
Where the API page is older than this guide
The API page is generated from the package’s own descriptions, and a few of them are behind. Where they differ, this guide is right (#2294):
Loadshows an annotation (const l: Load<…> = …). Usesatisfies, as above.Router.entriessuggestsexport const entries = app.entries, which Kit rejects. Map the list as in Prerender a table’s pages. It lists dynamic pages that declareentriestoo, not only static ones.Router.fetchsays it returnsnullon no match. Under abase, an unmatched path gets a404response; see An unmatched path.Ctx.setHeaderssays it always works. A repeated header orset-cookieanswers500; see Set response headers.when()says a gated-off route under abasegets the app’s error page.missanswers first, and a request that doesn’t ask for HTML gets plain text; see An unmatched path.
import { error, type Params } from '@ogygia/router';
import { posts } from '$lib/server/posts';
export async function findPost(
params: Params<'/posts/[slug]'>
) {
const post = await posts.get(params.slug);
if (!post) error(404, 'No such post');
return post;
}import { routes, page } from '@ogygia/router';
import Post from '$lib/views/Post.svelte';
import { findPost } from '$lib/server/find-post';
export const router = routes({
'/posts/[slug]': page(Post, {
load: async (c) => ({ post: await findPost(c.params) })
}),
'/api/posts/[slug]': { GET: (c) => findPost(c.params) }
});Limits
- The table-wide load. What
routes(table, { load })returns merges into every page’sdataat run time, but it isn’t inApp(#2293). Return those keys from a layout’s load too if components need them typed, or read them in islands throughpage.data. - Islands reading
page.page.datafrom$app/stateis typed by Kit’s globalApp.PageData, not by the table. Declare the keys there, or pass values in as props. formbefore a post.App['/path']['form']includesnull; on aGETthe prop is actuallyundefined(#2293). Read it withform?.x, which handles both.c.href()takes any string pattern. Userouter.href()for a checked one.