App
SPA router
Client-side navigation for csr = false pages, on by default. It takes same-origin link clicks, swaps the page in place with a view transition, prefetches the next page, keeps layout chrome alive and works with prerendered pages whose holes fill per visitor.
On this page
- Configuration
- Turn off view transitions for one page
- Links
- When it falls back to a full page load
- Prefetching
- Programmatic navigation
- Invalidation
- Page swaps
- Single-flight holes
- Server delta
- Navigation purpose
- Redirects
- Persistent layout
- Lifecycle events
- Accessibility
- Speculation rules
- Partial prerendering (PPR)
- See it
- Keep holes valid across deploys
- Island files after a deploy
- Do and don’t
Without Kit’s client, every link on a csr = false page would be a full page load: a white flash, and every piece of layout rebuilt from scratch. ogygia’s SPA router fills that gap. It’s on by default for the whole app, and there’s no component to render. When you click a same-origin link, ogygia fetches the next page, merges its <head>, updates the <body> in place and writes the history entry, all without a reload or Kit’s client. Pages cross-fade with a view transition instead of flashing.
On a csr = true route, Kit’s own client owns navigation, and the router leaves its clicks alone.
The router needs nothing beyond the setup you already did in Install. ogygia() turns it on.
import { sveltekit } from '@sveltejs/kit/vite';
import { ogygia } from 'ogygia/vite';
import { defineConfig } from 'vite';
export default defineConfig({
plugins: [ogygia(), sveltekit()]
});Configuration
All router settings live in one place, the router option of ogygia():
| Setting | What it does |
|---|---|
router: true (default) | Router on, view transitions on, form continuity on. |
router: false | No router. Same-origin links are full page loads, the router’s code is left out of the build, and the browser speculates. |
router: { viewTransitions: false } | Router on, no view transitions. |
router: { forms: false } | Router on, but half-filled form fields in islands aren’t carried across navigations. |
router: { serverDelta: true } | Off by default. The server skips islands the browser already holds. See Skip re-rendering what didn’t change. |
Keep the router when you want navigation that feels like an app: no flash, chrome that stays put, prefetch on hover. Turn it off when a plain multi-page site is enough.
View transitions are also skipped for a visitor whose system asks for reduced motion (prefers-reduced-motion: reduce), and in a browser without the View Transitions API.
In the example, the app keeps SPA navigation but turns view transitions off everywhere.
Turn off view transitions for one page
A page can skip the transition with a meta tag in its head. The router reads it from the page it’s going to, so a navigation to that page swaps without a transition. Navigation stays client-side. This suits a checkout step or a full-bleed media page.
import { sveltekit } from '@sveltejs/kit/vite';
import { ogygia } from 'ogygia/vite';
import { defineConfig } from 'vite';
export default defineConfig({
plugins: [
ogygia({
router: { viewTransitions: false }
}),
sveltekit()
]
});<svelte:head>
<meta name="ogygia-router" content="plain" />
</svelte:head>Links
The router takes a click on an <a href> when all of these are true:
- It’s a plain left click: no Ctrl, Cmd, Shift or Alt.
- The link goes to the same origin.
- The link has no
target(ortarget="_self"), nodownloadattribute and norel="external". - No element at or above the link has
data-sveltekit-reload. Kit’s grammar applies:"off"or"false"on a nearer element opts a subtree back in. - No script called
preventDefault()on the click first.
A link inside a web component’s shadow root counts too. A link to the page you’re on, without a hash, refreshes that page in place. A link that only changes the hash jumps to it.
Form submissions aren’t intercepted. A plain <form method="POST"> is a normal browser navigation, and a remote form() sends its own request (see Remote functions).
Kit’s other link options, data-sveltekit-noscroll, data-sveltekit-replacestate and data-sveltekit-keepfocus, aren’t read.
When it falls back to a full page load
The router fetches the next page first, and gives the navigation back to the browser when it can’t swap it in:
- the answer isn’t HTML, or it’s a file to download (
Content-Disposition: attachment); - a redirect took it to another origin;
- the next page is a
csr = truepage, or a page without ogygia’s router; - the next page comes from another build (a deploy happened while the tab was open), so its islands run on their own build’s code;
- the fetch failed, or the swap threw.
Prefetching
The router follows Kit’s preload grammar, so your data-sveltekit-preload-data and data-sveltekit-preload-code attributes work unchanged. For each attribute, the nearest element that carries it decides, and when both apply, the more eager value wins. Unlike Kit, preload-code also fetches the whole page, since a page’s code arrives with the page:
| Value | When the page is fetched |
|---|---|
eager | As soon as the page is idle after it loads. |
viewport | When the link comes on screen. |
hover (or "") | When the pointer moves over the link. |
tap | On mousedown or touchstart. |
off, false | Never. |
A link with no preload attribute above it isn’t prefetched. A new Kit app’s src/app.html already puts data-sveltekit-preload-data="hover" on <body>, so every link there prefetches on hover.
A prefetch also loads the code of the islands on that page, so the click has nothing left to download. A prefetched page is kept for 8 seconds, at most 32 pages or 4 MB. It isn’t kept at all when its response says Cache-Control: private, no-store or no-cache, or sets a cookie (spa_html_cacheable(cacheControl, setCookie) from ogygia/app is that rule as a function). Every kept page is dropped when a remote command or form succeeds, so a click after a change never shows the old page.
In the example, the sidebar’s links prefetch as they scroll into view, and the logout link never prefetches.
<script>
let { children } = $props();
</script>
<nav data-sveltekit-preload-data="viewport">
<a href="/docs/start/install">Install</a>
<a href="/docs/regions/overview">Regions</a>
<a href="/logout" data-sveltekit-preload-data="off">Log out</a
>
</nav>
{@render children()}Programmatic navigation
An island can navigate, refresh or listen to navigations with the functions from ogygia/app. They have the same names and shapes as Kit’s $app/navigation, and $app/navigation imported inside an island reaches the same functions. On a csr = true page each call goes to Kit’s real client instead, so a component shared between both kinds of page works on both.
| Function | What it does |
|---|---|
goto(url, opts?) | Navigates. replaceState: true replaces the current history entry. Another origin needs external: true, which loads it in full. |
invalidateAll() | Refreshes the current page’s data in place. See Refresh the page’s data. |
invalidate() | The same as invalidateAll(). Without Kit’s client there are no single dependencies to refresh. |
preloadData(url) | Prefetches a page and its islands’ code, as a hover would. |
preloadCode(url) | Does nothing with the router on: a page’s code arrives with the page. |
beforeNavigate(fn) | Calls fn before each navigation. Call nav.cancel() to stop it. |
afterNavigate(fn) | Calls fn after each navigation, and once right away with type: 'enter'. |
disableScrollHandling() | Does nothing: the router always sets the scroll itself. The console says so (scroll_handling_noop). |
bust_page_cache() | Drops every prefetched page, say after a sign-in. |
$app/navigation in an island also reaches functions ogygia/app doesn’t export: refreshAll(), onNavigate, snapshot, and pushState/replaceState (below). refreshAll() refreshes every query the page’s islands hold and the page’s data, at the same time. onNavigate and snapshot do nothing on a csr = false page, with no message: the router runs its own view transitions and keeps no Kit history to restore.
beforeNavigate and afterNavigate unsubscribe when the island is destroyed. Their from and to carry the url. params is always {} and route.id is always null, because without Kit’s client there’s no route table in the browser.
goto() returns a promise that rejects for a URL it won’t take: one that isn’t http: or https: (goto_not_http), or one on another origin without external: true (goto_cross_origin).
Kit’s shallow routing, pushState and replaceState, has no equivalent. A call does nothing, and the console says so (shallow_routing_unsupported). Navigate with goto(), or keep the state in the URL.
With router: false, goto() is a full page load, preloadData() and preloadCode() add speculation hints, and beforeNavigate and afterNavigate never fire.
In the example, a search island sends the visitor to the results page, replacing the current history entry while they type.
<script>
import { goto } from 'ogygia/app';
let q = $state('');
</script>
<input
bind:value={q}
oninput={() =>
goto(`/search?q=${encodeURIComponent(q)}`, {
replaceState: true
})}
/>Invalidation
invalidateAll() is a soft refresh, not a navigation. It fetches the current page again, merges its <head>, and updates page.data and the remote-function data seeded into the page. There’s no body swap, no view transition, no island remount, and beforeNavigate and afterNavigate don’t fire. Islands keep their state and read the new page.data.
A remote form() calls it on its own after a successful submit, unless the submit calls .updates(…) or the form’s handler refreshes queries on the server (see Submit forms). A query an island holds isn’t refreshed by it: call .refresh() on the query, as Remote functions shows.
Page swaps
On each navigation the router:
- waits up to 2 seconds for the next page’s new stylesheets, so the page doesn’t paint unstyled, then fires
og:before-swapand merges its<head>; - updates the
<body>in place, matching elements by key. An island that is on both pages with the same props stays mounted, with its state. An island that’s new mounts, and one that’s gone unmounts; - sets the title, fires
og:after-swap, and moves the scroll: to the top, or to the#hashtarget; - announces the new page and moves focus (see Accessibility), then fires
og:page-load.
Back and Forward fetch the page again, since the router keeps no copy of an old page, and put the scroll back where the visitor left it. The router holds that position while islands above it wake and grow, until the visitor scrolls, clicks or types.
When a region on the page sits inside a web component’s shadow root, the router can’t match elements there, so it replaces the whole body instead of updating it in place. Islands then mount again.
Single-flight holes
When the next page has server islands, the router reads them from the page it fetched and asks for all the holes that fetch at load in one batch request, up to 32 per request, instead of one request each. This needs no attribute.
The answer streams back out of order: each hole’s HTML arrives as soon as that hole has rendered, so a fast one lands before a slow one whatever their order on the page. A command that returns a region uses the same single-response path, so one round trip both changes the data and repaints.
Server delta
By default the server renders the whole next page on every navigation. With serverDelta on, the browser tells the server which islands it already holds, and the server renders only the ones whose inputs changed:
On a navigation, the browser sends the fingerprint of each hydrated island in an x-ogygia-known header. A fingerprint covers the island’s component and its props, and both sides read the same value the server wrote into the page, so they can’t disagree. The server skips each island whose fingerprint is in the list, and the browser keeps that island live with its state. When the list would make the header longer than 6144 characters, the browser leaves the header off and the server renders everything.
It’s off by default. When it’s off, the header is never sent and the server always renders the whole page.
Don’t turn it on in an app that uses postrender yet: the partial render is stored as the page, and full page loads then get the skipped islands empty (#2300).
import { sveltekit } from '@sveltejs/kit/vite';
import { ogygia } from 'ogygia/vite';
import { defineConfig } from 'vite';
export default defineConfig({
plugins: [
ogygia({ router: { serverDelta: true } }),
sveltekit()
]
});Navigation purpose
Not every page fetch is a visit. A prefetch happens before the visitor decided to go anywhere, and Back or Forward fetches a page they’ve already seen. A server that does something when it renders a page, like counting a view, writing “last seen” or showing a one-time banner, shouldn’t do it for those.
The router names the reason in an x-ogygia-purpose request header:
| Value | When |
|---|---|
| (absent) | A click, goto(), or a soft refresh of the same page. |
prefetch | Fetched early, on hover, tap, viewport, eager or preloadData(). |
history | Back or Forward. |
The header is advisory: a server that ignores it still renders correctly.
A click on a page that was prefetched in the last 8 seconds sends no request of its own: the router shows the prefetched page. So a missing header doesn’t mean every visit reaches the server, and a soft refresh (invalidateAll(), or a remote form’s submit) isn’t a new visit either. Use the header to skip work for fetches that may not be visits, and count views in the browser with og:page-load, which fires once for every page view.
In the example, a server load skips a “last seen” write when the fetch may not be a visit.
import { markSeen } from '$lib/server/stats';
export async function load({ params, request }) {
if (!request.headers.has('x-ogygia-purpose'))
await markSeen(params.slug);
return { slug: params.slug };
}Redirects
A redirect() in a server load works across a client navigation. The router follows it, shows the page it landed on, and writes that address to the address bar. The redirect doesn’t get a history entry of its own, so Back skips it, as on a full page load. A redirect to another origin becomes a full browser navigation.
Persistent layout
Put data-ogygia-keep="name" on an element, and the router carries it across navigations as it is: its DOM moves into the next page instead of being rebuilt, so island state, scroll position and playing media all continue. The next page has to have an element with the same name, and it should, since both pages render the same layout. This is how the sidebar on this site keeps its scroll position.
The attribute also tells ogygia that the live DOM owns the subtree. DOM ownership explains what that means. To keep a single island instead of a whole subtree, mark its import with { keep: 'name' } (see Client islands).
<script>
import SideNav from '$lib/SideNav.svelte' with {
wake: 'load'
};
let { children } = $props();
</script>
<aside data-ogygia-keep="sidebar">
<SideNav />
</aside>
<main>{@render children()}</main>Lifecycle events
A swap doesn’t run <script> tags from the next page, in its <head> or its body, which is how the browser treats inserted scripts. Code that should run on every page view needs a hook. The router fires three plain events on document:
| Event | When |
|---|---|
og:before-swap | Just before the swap: the DOM is still the old page, but location is already the new address. |
og:after-swap | The next page’s DOM is in place. Its islands still wake on their own schedules. |
og:page-load | The navigation is done: head merged, scroll and focus set. Also fires once on the first load, so one listener covers every page view. |
The events carry no detail: read location for the new page’s address. With router: false they don’t fire, since every page is a full load.
For code with state, an island with wake: 'load' is still the first tool: it mounts again on each navigation with real component lifecycles. The events are for page-wide glue code such as analytics, focus management or restarting a third-party widget.
In the example, a script in src/app.html sends a page view on the first load and after every navigation. It runs once, on the first load, and its listener stays.
<script>
document.addEventListener('og:page-load', () => {
navigator.sendBeacon('/api/pageview', location.pathname);
});
</script>Accessibility
A full page load tells a screen reader that the page changed and puts keyboard focus at the top. A swap does neither on its own, so the router does both on every navigation:
- It announces the new page. A visually hidden
aria-liveregion gets the new<title>(or the path, when there’s no title). - It moves focus. Focus goes to the first match: on Back or Forward, the element that had focus when the visitor left (if it has an
id); then the#hashtarget; then the first[autofocus]element; then the top of the page.
The exception is a control inside kept chrome (data-ogygia-keep) that has focus. It keeps it, so a search box in a kept header doesn’t lose focus mid-typing.
Speculation rules
With router: false, the browser owns navigation, and the server handle adds one Speculation Rules script to every page. A browser that can prerender prerenders likely next pages, with moderate eagerness (roughly, when the pointer rests on a link): it runs the page’s JavaScript, wakes its islands and fills its server islands in a hidden tab, and the click shows the page at once. A browser that can only prefetch prefetches. A browser without support ignores the script. There’s nothing to configure and no client JavaScript. A page that has its own <script type="speculationrules"> gets none from ogygia.
With the router on, ogygia adds no rules. A speculated page serves only a real browser navigation, which a swap never is, so the page would download twice. The router’s own prefetch does the same job for a cache the swap can read.
Two kinds of link are never speculated: links to the region endpoint, and rel="nofollow" links. Beyond that, data-ogygia-speculate gives you a switch: "off" on a link or a subtree turns it off, and "on" on a link or subtree inside it turns it back on.
Use off for links with side effects that must not run early, like a logout or a one-time action, and while you debug navigation and want a cold click.
In the example, the account menu turns speculation off for all its links but turns the inbox back on.
<nav data-ogygia-speculate="off">
<a href="/logout">Log out</a>
<a href="/inbox" data-ogygia-speculate="on">Inbox</a>
</nav>Partial prerendering (PPR)
A page with export const prerender = true is built once into a static file, and a server island on it still renders per visitor. That’s partial prerendering: the CDN serves the shell with no server render, and each hole fetches its HTML when the page loads. Holes stay the only dynamic part; anything rendered inline is baked at build time.
Speculation pays off most here. To prerender a PPR page, the browser fetches a static file and fills its holes, with almost nothing left to render, so in MPA mode moving between PPR pages costs almost nothing.
In the example, Hero is baked into the static file, and Recommendations and Greeting render on every visit.
See it
The frame below is a real prerendered page, /demo/ppr. Its shell clock is baked into the static file and never moves. Its hole clock is a server island that renders on every request. Reload, and the one page shows two different times.
Keep holes valid across deploys
A hole on a prerendered page is signed for 10 years. Its props are already public in the static HTML, so a long signature gives nothing away. Holes on other pages keep the short ttl.
The signing key matters more than the lifetime. By default each build signs with a fresh random key, so a deploy would break the holes on every static page from an earlier build and every page a CDN still holds. Set a stable OGYGIA_SECRET and holes from earlier builds stay valid. The build warns when you prerender holes without one. If your server can’t read its environment at runtime, pass the secret to handle({ secret }). See OGYGIA_SECRET.
The holes need a running server with ogygia.handle(), so a fully static adapter-static build can’t fill them. sessionCookie doesn’t work with them either: a prerendered hole’s URL is the same for every visitor, so it can’t be bound to one visitor’s session. Read cookies in the island’s component instead.
Island files after a deploy
Files under _app/immutable/ are cached for a year and never checked again, so every file ogygia writes there is named after its content: the runtime, each island’s code, and the build’s map of where each island’s code lives. A deploy that changes an island gives it a new file name. An island whose code didn’t change keeps its name, and its cached copy stays valid.
Each island also has a stable name in its entry attribute, the same from build to build, which every lookup uses; no file is served at it. The file the browser loads is in the region’s src attribute. An island with no src (one the browser rendered itself, or one a remote function sent) finds its file in the build’s map.
One file has a fixed name: _app/ogygia.json, next to SvelteKit’s _app/version.json. It holds the current build’s map. Serve it the way you serve version.json, so it’s always checked again, never cached for long.
When a cache serves a page from an older build:
- If that build’s files are still on your server or CDN, the page runs its own build’s code throughout.
- If they’re gone, each island reads
_app/ogygia.jsonand wakes on the current build’s code, and the devtools Page tab and the profiler report name each island this happened to. The runtime file itself can’t recover this way, so keep the previous build’s_app/immutable/files for as long as your HTML stays cached. The same goes for SvelteKit’s own files.
A visitor who keeps a tab open across a deploy and then clicks a link gets the next page as a full page load, since it comes from another build. Their islands then run on that build’s runtime and code, never mixed with the old ones.
Two settings make deploys cheap:
- A stable
OGYGIA_SECRET(above) keeps cached pages’ holes valid. - A fixed
kit.version.name, such as your commit hash. By default SvelteKit puts the build time into its client code, so every build renames every island that imports SvelteKit code, even when nothing changed. With a fixed version, the same source builds the same file names.
export const prerender = true;<script>
import Hero from '$lib/Hero.svelte';
import Recommendations from '$lib/Recommendations.svelte' with {
render: 'deferred'
};
import Greeting from '$lib/Greeting.svelte' with {
render: 'deferred'
};
</script>
<Hero />
<Greeting />
<Recommendations />Do and don’t
- Do wrap chrome that must stay (a sidebar, a player, a header) in
data-ogygia-keep. - Do use the
data-sveltekit-preload-*attributes you already know. - Do read
x-ogygia-purposebefore a server load does something a prefetch shouldn’t trigger, and count page views in the browser withog:page-load. - Do set a stable
OGYGIA_SECRETbefore you ship prerendered holes. - Don’t expect
<script>tags in the next page’s<head>or body to run after a swap. Use an island orog:page-load. - Don’t import
$app/navigationfunctions and expect shallow routing. Usegoto()and keep state in the URL. - Don’t keep the router if a plain multi-page site is enough.
router: falseremoves it and turns on speculation.