@ogygia/router
Serving
A route table answers from your server hooks, ahead of Kit's own routes, or from a catch-all route under a prefix. Options on routes() set the prefix, the trailing-slash policy, the error page, a guard, the visitor and the plugins' config, and entries() lists the pages to prerender.
On this page
A table is a value; something has to hand it requests. There are two places in a Kit app. The server hook puts the table in front of the whole app: it answers every path it matches, and Kit gets the rest. A catch-all route gives the table one subtree, like /app/…. It’s the way to prerender a table’s pages, and, for now, to set cookies.
Either way, keep ogygia.handle() first. The table’s pages need its request scope, and it reads the table’s config for plugins like postrender before the table runs.
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
);Server hook
router.handle is a Kit handle. For each request, the table answers if it matches the path; if it doesn’t, the request goes on to resolve, so Kit’s routes and endpoints answer as usual.
The hook runs before Kit renders its route, so the table wins over a Kit route at the same path. Use that to move routes into the table one at a time, or when() to hand a path back to Kit for some requests.
A key that matches everything, like /[...rest] with no base, also matches Kit’s own requests that pass through the hook, such as the /_app/remote/… calls of remote functions, and answers them in Kit’s place. Give a catch-all key a base, or use narrower keys.
Catch-all route
To give the table one subtree, add a Kit catch-all +server.ts there and pass each request to router.fetch(request, event). It returns the table’s Response, or null when the table doesn’t answer. Export the handler as GET and as Kit’s fallback, so posts to actions and every endpoint verb reach the table too.
Set the table’s base to the route’s path. With Kit’s paths.base, include it: a site served under /docs with the route at src/routes/app/[...path] needs base: '/docs/app'.
Under a base, the table answers every path inside it, matched or not; see An unmatched path. The ?? error(404) covers a request that reaches the route from outside the base.
router.fetch() takes any Request and doesn’t need Kit: the package’s own tests call it directly. Without the event, c.cookies, c.locals, c.platform, c.getClientAddress and c.event are undefined, and c.fetch is the global fetch. c.setHeaders() still works.
import { error } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { router } from '$lib/router';
const serve: RequestHandler = async (event) =>
(await router.fetch(event.request, event)) ??
error(404, 'Not found');
export const GET = serve;
export const fallback = serve;import { routes, page } from '@ogygia/router';
import Home from '$lib/views/Home.svelte';
import Settings from '$lib/views/Settings.svelte';
export const router = routes(
{ '/': page(Home), '/settings': page(Settings) }, // /app and /app/settings
{ base: '/app' }
);
export type App = typeof router.$infer;Differences
Both ways run the same table and render the same pages. Two things differ, because in the hook the router answers without Kit’s resolve(), and Kit only finishes a response it builds through resolve():
- Cookies. Served from the hook, a cookie set with
c.cookies.set()never reaches the browser: Kit adds theset-cookieheader only to responses it resolves, or to its own redirects. That covers a session cookie set by an action and the cookieanonymousVisitor()sets. From a catch-all route, they arrive as usual. Until that’s fixed (#2292), serve a table that sets cookies from a catch-all route, or end the code that sets one with Kit’s ownredirect(); see Set cookies. Reading cookies works both ways. - Headers set with
c.setHeaders(). From the hook, the router adds them only where the response has no such header yet, so thecache-control: no-storea page carries stays. From a catch-all route, Kit applies them on top, soc.setHeaders({ 'cache-control': … })does replace it. See Set response headers (#2293).
Table options
routes(table, options) takes these, all optional:
| Option | Default | What it does |
|---|---|---|
base | '' | The prefix the table lives under. See below. |
slash | 'ignore' | The trailing-slash policy: 'ignore', 'never' or 'always'. See below. |
error | none | The root error page. |
miss | none | What an unmatched path under base answers. See miss. |
load | none | A table-wide load that runs before every route. |
visitor | none | How to work out who’s asking, read as c.visitor. |
flags | none | Flags to decide on every request, so federation hops carry them. |
config | none | Kit’s config for every page in the table. |
Mount under a prefix with base
base is stripped from the path before matching, so a table with base: '/app' matches /app against its / key and /app/settings against /settings. A trailing / on base is ignored. A path outside the prefix isn’t the table’s: router.handle passes it on, and router.fetch returns null.
href() puts base in front of every URL it builds, and so do the paths entries() lists.
Pick a trailing-slash policy with slash
By default ('ignore'), a key matches its path with or without a trailing slash, and both get the page. Search engines then see two URLs for one page. Pick one:
'never'answers/about/with a308to/about;'always'answers/aboutwith a308to/about/.
The redirect keeps the query string and always stays on your site. The root, /, is never redirected. The policy is the table’s own: Kit’s trailingSlash option doesn’t apply to it.
The policy runs before matching, for every path under base and every method, so it covers endpoints too. With 'always', a POST to /api/posts gets a 308 to /api/posts/, a file-like key such as /report/[id].json redirects to /report/7.json/, and every call of the typed client, which builds paths with no trailing slash, costs a redirect.
Prerendering
router.entries() lists the paths of the table’s pages for a prerender crawl, each as { path } with base in front:
- a page whose key has no param is always listed;
- a page with params is listed once per param set its
entriesoption returns, filled into the pattern; - a page with params and no
entriesisn’t listed: it can still be found by Kit’s crawler through a link, or rendered live; - endpoints are never listed;
- a page behind
when()is listed as if it weren’t gated. If the gate is off at build time, its prerender answers 404 or falls through, and the build fails. Filter those paths out in your catch-all’sentriesexport (#2293).
entries on a page is Kit’s per-route entries export: a function, async or not, that returns the param sets, values as strings.
To prerender, serve the table from a catch-all route and export prerender and entries there. Kit’s entries wants the catch-all’s own param, without a leading /, so map the list: passing router.entries straight through makes Kit stop the build with “Parameter ‘path’ … cannot start or end with a slash”. Use prerender = 'auto', so the route still answers live for paths that weren’t prerendered and for posts. Keep posts on fallback: Kit won’t prerender a +server.ts that exports POST, PUT, PATCH or DELETE.
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, {
entries: async () =>
(await posts.refs()).map((p) => ({
slug: p.id
})) ,
load: async (c) => ({
post: await posts.get(c.params.slug)
})
})
},
{ base: '/app' }
);import { error } from '@sveltejs/kit';
import type { EntryGenerator, RequestHandler } from './$types';
import { router } from '$lib/router';
const serve: RequestHandler = async (event) =>
(await router.fetch(event.request, event)) ??
error(404, 'Not found');
export const GET = serve;
export const fallback = serve;
export const prerender = 'auto';
export const entries: EntryGenerator = async () =>
(await router.entries()).map(({ path }) => ({
path: path.slice('/app/'.length)
}));Kit routes
One app can have both. Kit’s file routes keep working for every path the table doesn’t answer, and you can move routes from one to the other one at a time.
- Navigation between them. The SPA router moves between router pages and
csr = falseKit pages without a full page load, in both directions. A link to acsr = trueKit page is a full page load, as from any ogygia page. - Page state. On a router page,
$app/stateand$app/navigationwork in islands and components as on acsr = falseKit page. See Islands, regions and page state. - The document. A router page doesn’t use
app.html. See Set the title, styles and head. - Hooks. Your
handle,handleErrorandhandleFetchstill run around the table:localsset by an earlier hook in thesequence()is onc.locals. reroute. The table matches the URL as it was requested. Kit’sreroutehook changes only which Kit route answers, not which table route does.- Kit’s form check. Kit’s cross-site form check runs before any hook, so it guards the table’s actions.