@ogygia/router
Request context
Every load, action, handler and gate gets c, the router's view of the request. It holds the typed params and query, Kit's request event, response helpers, a per-request scratch object and c.visitor, the one identity flags and federation read.
Code in a table needs the same things a Kit load does: the params, the query, cookies, a way to set a header, and who’s asking. Every load, action, endpoint handler, when() gate and miss gets them in one argument, c. It’s Kit’s RequestEvent reshaped for the table: the params and query come typed, the response helpers are on it, and it carries the visitor’s identity.
import { routes, page } from '@ogygia/router';
import Search from '$lib/views/Search.svelte';
import { search } from '$lib/server/search';
export const router = routes({
'/search/[scope]': page(Search, {
load: async (c) => {
c.setHeaders?.({ 'x-robots-tag': 'noindex' });
return {
scope: c.params.scope,
hits: await search(
c.params.scope,
c.search.q ?? '',
c.visitor?.sub
)
};
}
})
});Members
| Member | What it is |
|---|---|
c.params | The path params, typed by the route’s key, or the params schema’s output. |
c.search | The query: one string per key, first value wins. Or the search schema’s output. |
c.input | An endpoint’s validated JSON body, with a body schema. Otherwise undefined. |
c.url, c.request | The request’s URL and the Request. |
c.route.id | The matched pattern, like /posts/[slug]. '' in miss. |
c.fetch | Kit’s fetch, which forwards cookies and answers same-origin requests in-process. The global fetch outside Kit. |
c.cookies | Kit’s cookies. Setting one needs care; see below. |
c.locals, c.platform, c.getClientAddress | Kit’s, from the request event. |
c.setHeaders(headers) | Sets headers on the response. See below. |
c.event | Kit’s whole RequestEvent. |
c.json(), c.text(), c.redirect() | Build a Response. See What a handler can return. |
c.href(pattern, params) | A URL to a route of this table, with its base. See Build a link. |
c.state | A plain object for this request only, for a guard to hand something to a later load or handler. |
c.visitor | Who’s asking. See below. |
c.cookies, c.locals, c.platform, c.getClientAddress and c.event come from Kit, so they’re typed as possibly undefined. Served from Kit through router.handle or a catch-all route that passes the event, they’re always there. A table called with router.fetch(request) and no event, in a test say, doesn’t have them. c.setHeaders is typed as possibly undefined too, but it’s always there, event or not (#2293); write c.setHeaders?.(…) to satisfy the type.
Each request gets its own c. The page’s loads, its action and its gate all see the same one, so c.state set in the table-wide load is there in the handler.
Headers
c.setHeaders({ name: value }) sets headers on the response the router builds, from a load, an action or a handler. Use it rather than c.event.setHeaders: Kit’s own reaches only responses Kit builds through resolve(), which a table served from the hook skips.
- Once per header, per request.
c.setHeadersalso hands the headers to Kit, and Kit answers500when the same header is set twice in one request: a layout’s load and the page’s load both settingx-robots-tag, say. Set each header in one place.server-timingis the exception, which Kit joins; from the hook, though, only the last value set reaches the response. - Not
set-cookie. Kit refuses it insetHeaders(a500). Usec.cookies. cache-controldepends on how the table is served. A page, and JSON from a returned value orc.json(), already carrycache-control: no-store. From the hook, a header the response already has isn’t replaced, soc.setHeaders({ 'cache-control': … })has no effect there. From a catch-all route, Kit applies it on top and it does replaceno-store. For an endpoint served either way, pass the header toc.json(data, { headers })or return your ownResponse.- A
Responseyou got fromfetch()has headers that can’t be changed. Returning one from a handler in a request wherec.setHeaderswas called answers500. Copy it first:new Response(res.body, res).
These rough edges are tracked in #2293.
A streamed page sends its headers with the first yield, so set them in a load or before the first yield.
Cookies
Reading cookies with c.cookies.get() works however the table is served. Setting them doesn’t yet: from the hook (router.handle), a cookie set with c.cookies.set() or c.cookies.delete() never reaches the browser, because Kit adds set-cookie only to responses it builds itself (#2292). From a catch-all route, it arrives as usual.
Until that’s fixed, there are two ways to get a cookie out:
- Serve the table from a catch-all route. Every cookie arrives, a sign-in action’s and
anonymousVisitor()’s alike. - From the hook, end with Kit’s own
redirect(). The router leaves a redirect from@sveltejs/kitto Kit, and Kit adds the request’s cookies to its own redirects. That suits a sign-in action, which redirects anyway. It doesn’t help a cookie set on a page that renders, likeanonymousVisitor()‘s.
import { routes, page, fail } from '@ogygia/router';
import { redirect } from '@sveltejs/kit';
import Login from '$lib/views/Login.svelte';
import { auth } from '$lib/server/auth';
export const router = routes({
'/login': page(Login, {
actions: {
default: async (c) => {
const form = await c.request.formData();
const session = await auth.login(
String(form.get('email') ?? ''),
String(form.get('password') ?? '')
);
if (!session) return fail(400, { incorrect: true });
c.cookies?.set('session', session.id, {
path: '/',
httpOnly: true
});
redirect(303, '/'); // Kit's redirect: the cookie goes with it, served either way
}
}
})
});c.visitor
You say once, on the table, how to work out who a request is from, and every part of the app reads c.visitor. Flags stick to it, federation mounts sign it onward to other teams, and loads can personalize with it.
routes(table, { visitor }) takes a function of c that returns the visitor: an object with sub, the signed-in user’s id, and any other claims you want to carry, like roles. Return undefined for nobody.
c.visitor is worked out once per request, and only when something reads it: an endpoint that never asks never pays for it. When the request came through a signed federation hop that carries claims, those claims are the visitor, and your function doesn’t run.
Give logged-out visitors an identity
With no identity, a flag split puts a visitor in the control group. To keep a rollout sticky for visitors who never sign in, use anonymousVisitor(). On a visitor’s first request it makes a random id, sets it in a cookie and returns { vid: id, anonymous: true }; on later requests it reads the id back from the cookie and returns the same.
It sticks only when the table is served from a catch-all route; from the hook, the cookie is dropped and every request gets a new id.
- The id is
vid, neversub:subis a signed-in user’s id, and a cookie is whatever the browser sends. cookienames the cookie,og-vidby default, the same one flags fall back to.daysis its lifetime, 365 by default.- The cookie is first-party,
HttpOnly,SameSite=Laxand on/. Clearing it gives the visitor a new id.
import { routes, page } from '@ogygia/router';
import Home from '$lib/views/Home.svelte';
import { sessions } from '$lib/server/sessions';
export const router = routes(
{ '/': page(Home) },
{
visitor: (c) => {
const s = sessions.read(c.cookies?.get('session'));
return s ? { sub: s.userId, roles: s.roles } : undefined;
}
}
);import { routes, page, anonymousVisitor } from '@ogygia/router';
import Home from '$lib/views/Home.svelte';
import { sessions } from '$lib/server/sessions';
const anon = anonymousVisitor({
cookie: 'og-vid',
days: 365
});
export const router = routes(
{ '/': page(Home) },
{
visitor: (c) => {
const s = sessions.read(c.cookies?.get('session'));
return s ? { sub: s.userId } : anon(c);
}
}
);Feature flags
A flag a page reads is decided on that request and carried into every federation mount the page makes. Static and deferred remote regions don’t carry it (Flag decisions). A shell that only routes to other teams’ apps may read no flag itself, yet still want the visitor’s buckets to travel. List those flags in routes(table, { flags: [...] }): each is decided on every request the table matches, before any when() gate or load. See Shell flags.
import { routes } from '@ogygia/router';
import { mount } from '@ogygia/federation';
import { cms } from '$lib/server/peers';
import { newNav, checkoutV2 } from '$lib/flags';
export const router = routes(
{ '/cms/[...rest]': mount(cms) },
{ flags: [newNav, checkoutV2] }
);