@ogygia/router
Routes and params
A route table maps URL patterns to pages and endpoints. Patterns use Kit's grammar ([param], [[optional]], [...rest]), the most specific route wins as in Kit, href() builds a URL from a pattern, and when() switches a route on or off per request.
In Kit, a route’s URL is the folder its files sit in, so a URL that comes from data has no folder to live in. Here a route table is one object instead. Each key is a URL pattern, and each value is what answers it: a page made with page(), or an endpoint written as { GET, POST, … }. You pass the object to routes(), which checks the patterns and returns the router.
The key types everything under it. In the load above, c.params.slug is a string, and c.params.id would be a type error. That holds for loads, actions and handlers, at the top of the table, inside layouts and behind when().
import { routes, page } from '@ogygia/router';
import Home from '$lib/views/Home.svelte';
import Post from '$lib/views/Post.svelte';
import Files from '$lib/views/Files.svelte';
import About from '$lib/views/About.svelte';
import { posts } from '$lib/server/posts';
export const router = routes({
'/': page(Home),
'/[[lang]]/about': page(About),
'/posts/[slug]': page(Post, {
load: async (c) => ({
post: await posts.get(c.params.slug)
})
}),
'/files/[...path]': page(Files),
'/api/posts/[slug]': {
GET: async (c) => posts.get(c.params.slug)
}
});
export type App = typeof router.$infer;Patterns
Patterns use Kit’s route grammar, written as a path instead of folders. Every key starts with /.
| Pattern | Matches | c.params |
|---|---|---|
/about | /about | {} |
/posts/[slug] | /posts/hello | { slug: string } |
/[[lang]]/about | /about and /fr/about | { lang?: string } |
/files/[...path] | /files, /files/a, /files/a/b/c.txt | { path: string } |
/report/[id].json | /report/7.json | { id: string } |
/trips/[from]/[to] | /trips/paris/rome | { from: string; to: string } |
[param]matches one segment. A segment can mix text and a param, like[id].json.- A segment can hold several params too:
/[from]-[to]matches/paris-rome, each param taking the shortest run before the text that follows it and the last taking the rest, as in Kit. Both arrive inc.paramsat run time, but only the first is typed today:c.params.tois a type error, andhref()and the typed client refuseto(#2293). Give each param its own segment, as/trips/[from]/[to]does, until that’s fixed. [[optional]]is a whole segment that may be missing. Its param isundefinedthen.[...rest]is the last segment. It takes everything after it, slashes included, and can be empty ('').- Param names are JavaScript identifiers: a letter,
_or$, then letters, digits,_or$.
Params arrive decoded: /posts/caf%C3%A9 gives slug: 'café'. A malformed escape like %E0%A4 is kept as it was written instead of failing the request.
Matching ignores a trailing slash: /about and /about/ both match /about. To redirect one to the other, set the table’s slash option. A [...rest] value keeps the trailing slash, though: /files/a/ gives path: 'a/', where /posts/a/ gives slug: 'a' (#2293). Set slash: 'never' to get one value per page. A path longer than 8,192 characters matches no route.
What a pattern can’t do
routes() checks every key when the table is built and throws on one it can’t read, so a typo fails when the module loads, not on a request:
- a key that doesn’t start with
/; - a
[...rest]that isn’t the last segment; - a segment with a stray bracket, like
[slugora]b.
The error says what’s wrong and names the key, but has no message code or link yet (#2293). The same goes for the router’s other errors, like a duplicate layout name or an href() it refuses.
Kit’s param matchers ([id=integer]) aren’t part of the grammar, and a key with one throws the same way. To accept only numbers, give the page a params schema: it coerces the param and answers 404 when it doesn’t fit. Unlike a matcher, a failed schema doesn’t let another route try the path, so two routes that differ only by a matcher in Kit (/posts/[id=integer] beside /posts/[slug]) need different patterns here. Kit’s (group) folders aren’t part of it either; a layout is what groups routes here.
Route order
When several keys match a path, the router picks the one Kit would pick for the same files. Order in the table never matters, so spreading a package’s table into yours can’t change which route answers.
From the left, segment by segment:
- text beats a param:
/posts/newbeats/posts/[slug]; - a required param beats an optional one;
- a
[...rest]loses to any other param:/posts/[slug]beats/posts/[...rest]; - a
[[optional]]that isn’t the last segment counts for nothing, so/[[lang]]/docsranks like/docs; - a tie goes by the pattern’s text, never by table order.
import { routes, page } from '@ogygia/router';
import NewPost from '$lib/views/NewPost.svelte';
import Post from '$lib/views/Post.svelte';
import Archive from '$lib/views/Archive.svelte';
export const router = routes({
'/posts/[...rest]': page(Archive), // /posts/2024/05
'/posts/[slug]': page(Post), // /posts/hello
'/posts/new': page(NewPost) // /posts/new, whatever the order above
});Links
router.href(pattern, params) fills a pattern with params and puts the table’s base in front. The pattern must be a key of the table, and the params are required when the pattern has a required param, so renaming a route or a param turns every stale link into a type error. Values can be strings or numbers.
Inside a load, action or handler, c.href(pattern, params) does the same. It isn’t checked against the table’s keys.
Values are encoded the way Kit’s resolve() writes them. A rest value keeps its / and has each piece encoded. An empty optional or rest param drops its segment.
href() throws rather than build a URL that names another route or another site:
- a value that fills a whole segment with
.or.., which every URL parser drops; - a rest value with an empty piece (a leading, trailing or doubled
/), which could build//host; - a param that fills its segment empty anywhere but the last segment.
import { router } from '$lib/router';
router.href('/posts/[slug]', { slug: 'hello world' }); // '/posts/hello%20world'
router.href('/files/[...path]', { path: 'a/b c.txt' }); // '/files/a/b%20c.txt'
router.href('/[[lang]]/about'); // '/about', no params needed
router.href('/[[lang]]/about', { lang: 'fr' }); // '/fr/about'
router.href('/'); // '/'Conditional routes
Wrap any entry in when(gate, entry) and it exists only for requests the gate allows. The gate is any (c) => boolean. A boolean flag is one, so a staged rollout of a page, a beta route or an endpoint kill switch is one wrapper. It works on pages, endpoints and a federation mount().
When the gate says no, the route doesn’t exist for that request. With no base, the request goes on to the rest of your app, so during a migration a gated-off route can be served by a Kit route at the same path. Under a base, the table answers as for any unmatched path.
The gate runs after the route matches and before any load. A flag used as a gate is decided like any flag read: it sticks per visitor, it runs after a vendor source has primed, and it carries across federation. The App type sees the entry as if it weren’t wrapped.
router.entries() still lists a gated page for prerendering, whatever the gate would say (#2293).
import { routes, page, when } from '@ogygia/router';
import Checkout from '$lib/views/Checkout.svelte';
import NewCheckout from '$lib/views/NewCheckout.svelte';
import { checkoutV2, exportsOn } from '$lib/flags';
import { orders } from '$lib/server/orders';
export const router = routes({
'/checkout': page(Checkout),
'/checkout-v2': when(
checkoutV2,
page(NewCheckout)
) ,
'/api/export': when(exportsOn, {
GET: async () =>
new Response(await orders.csv(), {
headers: { 'content-type': 'text/csv' }
})
}),
'/checkout-preview': when(
(c) => c.cookies?.get('preview') === '1',
page(NewCheckout)
)
});Matching
compile(pattern) turns one pattern into its regular expression and param list, and throws on a malformed one, as routes() does. match_path(compiled, pathname) tries a list of compiled patterns in the order you give it and returns the first { pattern, params } that matches, or null. Sort the list yourself: unlike a table, match_path doesn’t apply Kit’s order.
They’re for code that needs the router’s grammar without a table, like this map from a blog’s old URLs to its new ones.
import { compile, match_path } from '@ogygia/router';
const old = [
compile('/blog/[slug]'),
compile('/blog/[...rest]')
];
export function newHome(pathname: string): string | null {
const hit = match_path(old, pathname);
if (!hit) return null;
return hit.pattern === '/blog/[slug]'
? `/posts/${encodeURIComponent(hit.params.slug ?? '')}`
: '/posts';
}