Skip to content

@ogygia/router

Server router

@ogygia/router writes SvelteKit's routing model as values: pages, layouts, loads, actions and endpoints in one typed table, served from your hooks or a catch-all route. Each component reads App['/path'] for its props, with no codegen, and a typed fetch client calls the endpoints.

On this page

Kit’s file routes work well until your routes stop being files. Paths that come from a CMS or a database, a tool that generates its pages, a package that ships routes for an app to spread in: each needs a route table you can compute. Even in an ordinary app, you may want a route, its load and its component in one place instead of across +page.svelte, +page.server.ts and +server.ts.

@ogygia/router is Kit’s routing model written as values. You import functions (routes, page, layout, load), build one table in an ordinary module, and export it. The types flow through the table, so each component reads its data, params and form from App['/path'], with no $types import and no generated files.

The table runs on the server. It matches the request, runs the loads, and renders the page through its layouts into a complete ogygia document: server HTML, with JavaScript only for the islands inside it. Moving between those pages in the browser is the job of ogygia’s SPA router, which needs nothing from this package.

For a handful of ordinary pages, Kit’s file routes stay simpler, and you can mix both in one app. Nothing requires the router.

import { routes, page, error } from '@ogygia/router';
import Home from '$lib/views/Home.svelte';
import Post from '$lib/views/Post.svelte';
import { posts } from '$lib/server/posts';

export const router = routes({
  '/': page(Home),
  '/posts/[slug]': page(Post, {
    load: async (c) => {
      const post = await posts.get(c.params.slug);
      if (!post) error(404, 'No such post');
      return { post };
    }
  })
});

export type App = typeof router.$infer;

Installation

Install it, then list its router() plugin beside ogygia(), before sveltekit(). The plugin tells the build that every module importing @ogygia/router renders pages, so the CSS of each component those pages reach is linked when they render. Without it, dev says router_css_inactive and the pages render with no component styles.

pnpm add @ogygia/router
import { sveltekit } from '@sveltejs/kit/vite';
import { ogygia } from 'ogygia/vite';
import { router } from '@ogygia/router/vite';
import { defineConfig } from 'vite';

export default defineConfig({
  plugins: [ogygia(), router(), sveltekit()]
});

Serving

The table answers requests through its own Kit handle, placed after ogygia’s in sequence(). A request the table matches gets the table’s answer. Any other request goes on to the rest of your app, Kit’s file routes included.

You can serve it from a Kit catch-all route instead, under a prefix. A table that sets cookies needs it for now, or has to end with Kit’s own redirect(). Serving covers both ways and every table option.

import { sequence } from '@sveltejs/kit/hooks';
import * as ogygia from 'ogygia/server';
import { router } from '$lib/router';

export const handle = sequence(
  ogygia.handle(),
  router.handle
);

Page data

A page component gets data, form and params as props, like a Kit +page.svelte. Type them by indexing App with the route’s key. If the load’s return changes, the component shows a type error, as with Kit’s $types.

The component is rendered on the server only. Mark an import inside it with wake and that part becomes an island that runs in the browser.

<script lang="ts">
  import type { App } from '$lib/router';
  import Likes from '$lib/islands/Likes.svelte' with {
    wake: 'visible'
  };

  let { data }: App['/posts/[slug]'] = $props();
</script>

<svelte:head><title>{data.post.title}</title></svelte:head>

<h1>{data.post.title}</h1>
{@html data.post.html}
<Likes slug={data.post.slug} />

Package contents

PageWhat it covers
ServingThe hook and the catch-all route, Kit’s own routes, base, slash, every table option, and prerendering.
Routes and paramsTable keys, [param], [[optional]], [...rest], which route wins, href(), and gating a route with when().
Pages and layoutspage(), layout(), nesting and breaking out, what a page component gets, islands on router pages, config.
Loading dataLoads, the data cascade, sharing a load without a waterfall, the table-wide load, and refreshing data.
Request contextEvery member of c, headers and cookies, c.visitor, anonymousVisitor(), and the flags option.
Form actionsactions, fail(), named actions, the form prop, and what works instead of use:enhance.
Endpoints{ GET, POST } entries, verb wrappers, body schemas, what a handler can return, and api<App>().
Error handlingredirect(), error(), error pages and which one renders, miss, and what every failure answers.
Typesparams and search schemas, the App map, Load, Action, Handler and Params, and the limits of inference.
StreamingA page that flushes at once and fills in, from a generator or from a load that returns a promise of a region.
@ogygia/router, /apiThe generated API reference.

Kit file equivalents

If you know Kit’s routing, each file and export you’d write there has one place in the table:

SvelteKit@ogygia/router
the src/routes/ treeone routes({ … }) table
+page.sveltethe first argument of page()
+page.server.ts (load, actions)the second argument of page()
a universal +page.ts or +layout.ts loadnone: every load runs on the server only
+layout.svelte and its loadlayout(name, Component, { load })
+error.svelteerror on layout() or routes()
+page@.svelte, +page@name.sveltewhere you place the route
a (group) foldera layout, keyed App['(name)']
+server.tsan { GET, POST, … } object
[id=matcher]a params schema, which answers 404 rather than letting another route try
await parent()a shared load()
export const configconfig on the table, a layout or a page
export const entriesentries on a page
export const prerendera catch-all route that exports prerender and entries
export const trailingSlashthe table’s slash option
export const csr, export const ssrnone: a router page is always server-rendered with csr = false
./$types (PageData, PageProps, …)App['/path']
redirect(), error(), fail()the same names, from @ogygia/router
depends() and invalidate(url)invalidateAll(), which runs every load

Integrations

  • @ogygia/postrender reads its config key from the table, at table, layout and page level, as from Kit’s export const config. See Set page options with config.
  • @ogygia/flags gates a whole route with when() and picks a page component per visitor with hero.pick({ control: Hero, bold: HeroBold }) in place of the component. Flags stick to c.visitor.
  • @ogygia/federation is built on this router: mount(peer) is a table entry that serves another team’s app under your layouts.
  • @ogygia/content collections give a dynamic route its pages to prerender through a page’s entries.
  • A package can ship a table for your app to spread into its own. See Ship a route table.