Skip to content

@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:

KeyHolds
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 data is what every load on its branch returns, merged: each layout’s around it, then its own. A load that may return a Response adds only its other arm.
  • form is the union of what its actions return, each fail() unwrapped to its data, plus null. See Type the form prop.
  • params is read from the pattern, or is the params schema’s output.
  • search is the search schema’s output, or {} with no schema.
  • A layout’s data is 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 out is the handler’s plain return value, unknown when it returns a Response. in is the body schema’s output, undefined with 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:

Patternparams
/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 }

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:

HelperTypes
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 of c.
  • Params<'/pattern'> is a pattern’s params. HrefParams<'/pattern'> is what href() takes for it, strings or numbers, and HrefArgs<'/pattern'> its argument list, with params optional when no param is required.
  • InferOutput<Schema> is a Standard Schema’s output type, and StandardSchemaV1 the schema type itself.
  • InferMap<Table> is what $infer is, for a table type you hold. Simplify<T> flattens an intersection for display.
  • Router, RoutesOptions, PageServer, PageDef, LayoutDef, LoadDef, ActionDef, Endpoint, VerbEntry and RouteTable describe the values routes(), page(), layout(), load(), action() and the verb wrappers return.
  • ActionFailure<Data> is what fail() returns.
  • AnyComponent is any Svelte component, and ComponentPick what a flag’s pick() returns, the two things page() takes besides a generator.
  • CompiledPattern is what compile() returns.
  • ApiClient<App> and ApiClientOptions type the typed client, and AnonymousVisitorOptions the options of anonymousVisitor().

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):

  • Load shows an annotation (const l: Load<…> = …). Use satisfies, as above.
  • Router.entries suggests export const entries = app.entries, which Kit rejects. Map the list as in Prerender a table’s pages. It lists dynamic pages that declare entries too, not only static ones.
  • Router.fetch says it returns null on no match. Under a base, an unmatched path gets a 404 response; see An unmatched path.
  • Ctx.setHeaders says it always works. A repeated header or set-cookie answers 500; see Set response headers.
  • when() says a gated-off route under a base gets the app’s error page. miss answers 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’s data at run time, but it isn’t in App (#2293). Return those keys from a layout’s load too if components need them typed, or read them in islands through page.data.
  • Islands reading page. page.data from $app/state is typed by Kit’s global App.PageData, not by the table. Declare the keys there, or pass values in as props.
  • form before a post. App['/path']['form'] includes null; on a GET the prop is actually undefined (#2293). Read it with form?.x, which handles both.
  • c.href() takes any string pattern. Use router.href() for a checked one.