Data & state
State and context
Each island is its own root, so state doesn't flow between islands by itself. Share module state for app-wide values, hand one live object to several islands with a wired class, reach a whole subtree with context, and keep state alive across navigations.
On this page
- Module state
- Shared objects
- How it stays live
- Why the server never mixes visitors
- Context
- Define a typed context
- Set it
- Read it
- Swap the import in an existing layout
- Provide to one part of the page
- What a context value can be
- Context on csr = true pages
- Where context doesn’t reach
- Persistence across navigations
- Keep a whole island
- Half-filled forms
- Limits and errors
On a csr = false page each island hydrates as its own root. Svelte’s component tree stops at the island’s edge, and a value passed into an island crosses as a serialized copy, not a reference. So two islands don’t share state unless you give them a way to. Pick by where the state is born and who reads it:
| You need | Use |
|---|---|
| State inside one island | Plain $state in that island. |
| App-wide state that starts in the browser | Module state in a .svelte.ts file. |
| An object the server makes, handed to a few islands | A wired class, passed as a prop. |
| A value many islands in a subtree read (user, theme, cart) | Context. |
| State that survives moving to the next page | A named codec, or keep. |
Functions, stores and the full list of what crosses are on Serialization.
In the example, a layout sets a theme with setContext from ogygia instead of Svelte’s, and any island on the page reads it with getContext. With Svelte’s own setContext, the island would read undefined.
<script>
import { setContext } from 'ogygia';
let { children } = $props();
setContext('theme', 'dark');
</script>
{@render children()}<script>
import { getContext } from 'svelte';
const theme = getContext('theme');
</script>
<span>Theme: {theme}</span>Module state
A module with $state at its top level is one instance in the browser, shared by every island that imports it, because the page loads that module once. This needs no setup.
On the server the same module is one instance too, shared by every request. So keep module state for values that start in the browser and change there. Don’t write per-visitor data into it during a server render: the next visitor would see it. State the server makes per request belongs in a wired class.
In the example, a header badge and a product button share the module’s items.
export const cart = $state({ items: [] as string[] });<script>
import { cart } from '$lib/cart-state.svelte';
</script>
<span>Cart ({cart.items.length})</span><script>
import { cart } from '$lib/cart-state.svelte';
let { sku } = $props();
</script>
<button onclick={() => cart.items.push(sku)}>Add</button>Shared objects
A plain object crosses into an island as a copy, which is fine for data. A class instance, such as a cart with methods or a store the server filled, doesn’t survive a copy: its prototype and methods are lost. A class opts in by saying how it travels, with the wire macro:
encode says what leaves and decode says how to rebuild it. You write both, so nothing is guessed from the class’s shape. The class has to be exported from your app’s source; wire has the full contract.
Create one instance and pass it to as many islands as you like. The islands are separate bundles, but they share one live object: when one calls cart.add(), the other repaints.
The two widgets below are separate islands that share one Cart, passed as a prop:
How it stays live
The codec only copies data. The object stays live because the server gives each instance one id, and the browser rebuilds each id once and hands every island the same object. An island that wakes late (visible, idle) gets the instance the others already hold, with its current state.
Why the server never mixes visitors
The browser remembers rebuilt instances, but the server never does. Every request, and every server island render, decodes fresh, so one visitor’s state never renders into another visitor’s HTML. Create the instance per request, in the page or in load, like any other prop. The encode result travels with the props, so the server HTML and the first paint in the browser agree.
export class Cart {
items = $state<string[]>([]);
get count() {
return this.items.length;
}
add(item: string) {
this.items.push(item);
}
static wire = import.meta.og.wire({
encode: (c: Cart) => $state.snapshot(c.items),
decode: (items: string[]) =>
Object.assign(new Cart(), { items })
});
}<script>
import CartCount from '$lib/CartCount.svelte' with {
wake: 'load'
};
import AddButton from '$lib/AddButton.svelte' with {
wake: 'visible'
};
import { Cart } from '$lib/cart.svelte';
const cart = new Cart();
</script>
<CartCount {cart} />
<AddButton {cart} />Context
A prop is right when one object goes to two known islands. When a value has to reach many islands spread over the page, such as the signed-in user, a theme or a cart that a header badge and a product button both read, threading it through props is noise. Context gives it once, above them.
Svelte’s own context follows the component tree, and islands break that tree: on the client, a setContext above an island never reaches inside it. ogygia carries context across the split through the page itself. The provider writes its values into the HTML, serialized like island props, and each island reads the providers above the spot where it hydrates.
Define a typed context
createContext<T>(name) from ogygia returns Svelte’s [get, set, has]. Its key is Symbol.for(name), which the browser can rebuild in every island, so it’s the same key as a plain setContext(Symbol.for(name), …).
Set it
Call the setter in a component above the islands, usually a csr = false layout. The value reaches every island on the page. To change it later, change the live object you set: every reader sees the change.
Read it
An island calls the getter during setup, like Svelte’s getContext, and keeps the reference. A call later, say in an event handler, has no island hydrating to read from. Like Svelte’s, the getter throws when nothing above set the value (context_missing); call hasCart() first when the value is optional.
getContext from ogygia is Svelte’s own, re-exported so the imports read well together. ogygia fills each island’s context when it hydrates, so a plain getContext(Symbol.for('cart')) reads the same value as getCart().
Moving from the callable form
Up to 0.13, createContext(key, default?) returned a callable: cartCtx(cart) made a <Provide> entry and cartCtx.get() read it, keyed by the plain string. That form is gone. Destructure instead, call the setter above, and ask has() where you used a default. The key is now Symbol.for(name), not the string, so move a context’s provider and its readers together.
Swap the import in an existing layout
For a layout that already calls Svelte’s setContext, the smallest change is the import. setContext from ogygia does what Svelte’s does, and on the server it also records each value, so every island on the page can read it with its usual getContext('key'). The result is one flat page root every island inherits.
A key crosses when the browser can rebuild it: a string, or Symbol.for('name'). A one-off Symbol() key can’t cross (context_key_one_off; the build also warns, region_context_key_one_off).
A third argument, { islands: false }, keeps a key for the server-rendered tree only: same-tree getContext works, and nothing is written into the page. Use it for host-only values like element refs or a large config no island reads.
Provide to one part of the page
<Provide values={…}> wraps a subtree and gives its values to every island inside, shadowing the page root on the same key. Pass a plain object, or an array of them, merged left to right with falsy entries skipped. A Symbol.for key works as a computed key. The values are read once, when the provider renders.
The two widgets below are separate islands, and neither gets a prop. Both call getCart() and reach the same live Cart, so clicking Add repaints the count:
What a context value can be
Context values cross like island props:
- Plain data comes back as a copy taken when it was set. Each island gets its own, so a change in one isn’t seen by another. Right for a theme, a user name or config.
- A wired class comes back as one live instance, the same object in every island. Use it when islands have to see each other’s changes.
- A store comes back as one live store, shared by every island. See Stores.
- A function crosses only when marked with
import.meta.og.$. See Pass a function. - A snippet crosses through
<Provide>, as it does as a prop. A drop-insetContextdoesn’t carry snippets.
What happens to a value that can’t cross depends on how you set it. <Provide> takes a bare function for a snippet, so it can freeze quietly, and a class without a codec fails the render. With setContext, the key is dropped from the page, so islands read undefined. The server-rendered tree still sees it, and dev says why (context_value_function, context_dropped, context_unserializable). Once the context written into the page passes 32 kB, dev names the largest keys (context_marker_large); { islands: false } is usually the fix.
When no code in the app sets context through ogygia and an island reads getContext, the build warns (island_context_unprovided): a value set with Svelte’s own setContext in a csr = false layout never reaches the island.
Context on csr = true pages
When Kit hydrates the whole page, islands are plain components in one tree, so there’s nothing to bridge: setContext, createContext and <Provide> from ogygia behave exactly like Svelte’s. Islands inside a lake on such a page still wake on ogygia’s runtime, and still read the page’s context through the bridge. Importing from ogygia in a mixed app is safe either way.
Where context doesn’t reach
- A server island (
render: 'deferred') renders alone on its endpoint, so it never sees the page’s providers. Put the reader in awakeisland nested inside it. - A provider has to sit above the readers:
<Provide>above them in the page, or a drop-insetContextanywhere on the page (the page root).
import { createContext } from 'ogygia';
import type { Cart } from '$lib/cart.svelte';
export const [getCart, setCart, hasCart] =
createContext<Cart>('cart');<script>
import { Cart } from '$lib/cart.svelte';
import { setCart } from '$lib/cart-context';
let { children } = $props();
setCart(new Cart());
</script>
{@render children()}<script>
import { getCart } from '$lib/cart-context';
const cart = getCart();
</script>
<span>Cart ({cart.count})</span><script>
import { setContext } from 'ogygia';
let { data, children } = $props();
setContext('user', data.user);
setContext('scrollRefs', new Map(), { islands: false });
</script>
{@render children()}<script>
import { Provide } from 'ogygia';
import CartBadge from '$lib/CartBadge.svelte' with {
wake: 'load'
};
import { Cart } from '$lib/cart.svelte';
const cart = new Cart();
</script>
<Provide values={{ [Symbol.for('cart')]: cart }}>
<CartBadge />
</Provide>Persistence across navigations
By default state lasts as long as the page: the next page makes a fresh instance. Give a wired class’s codec an id, and its instance lasts for the session instead: the same live object follows the visitor from page to page in the tab.
On the next page the server still sends a fresh snapshot. Because the codec is named, the browser joins it to the instance the visitor already has, runs merge, and gives every island the same live object. Without a merge, the live object wins, so a cart mid-edit beats a fresh server read. Write merge to pull in what the server knows better, such as prices or stock.
The named instance lives in the tab’s memory. Another visitor never sees it, the server never keeps it, and a reload starts fresh. It needs the SPA router, since a full page load clears it. A cart that has to survive reloads or follow a sign-in needs real storage, a database plus a load, and merge is where the two meet.
Two classes with the same id would share one kept instance, and the browser logs an error in every build (continuity_id_collision). A context whose value is a named codec carries over with no other change.
Keep a whole island
with { keep: 'name' } keeps a whole island, not just an object: when the next page places an island with the same name, the live element and its mounted component move there instead of mounting again. Only the component and its $state are kept; the new page’s props are pushed in, so a prop that changes per page still updates. A music player keeps playing, a chart keeps its zoom.
It needs the SPA router; without it, dev warns (keep_without_router). Client islands has an example. To keep a block of plain markup with the islands inside it, use data-ogygia-keep instead.
Half-filled forms
Fields a visitor typed into survive leaving the page and coming back, with no setup. Before each navigation, the router records every input, textarea and select inside an island whose value differs from what the server rendered. When the visitor comes back to the same path in the same tab, by a link or Back, each field is filled in again as its island wakes, and input and change fire so bind: picks the value up. The query string isn’t part of the match, so /search?q=a and /search?q=b share one record. Only islands that wake within 5 seconds of the swap are filled in. The last 20 pages are remembered, in memory only.
Password fields are kept like any other field. Put data-ogygia-no-keep on every password or other secret field. It turns keeping off for one field or a subtree, and also suits a one-time code or a message box that should start empty. Turn it off everywhere with ogygia({ router: { forms: false } }).
export class Cart {
items = $state<string[]>([]);
prices = $state<Record<string, number>>({});
get count() {
return this.items.length;
}
add(item: string) {
this.items.push(item);
}
static wire = import.meta.og.wire({
id: 'cart',
encode: (c: Cart) => ({
items: $state.snapshot(c.items),
prices: $state.snapshot(c.prices)
}),
decode: (d: {
items: string[];
prices: Record<string, number>;
}) => Object.assign(new Cart(), d),
merge: (live, fresh) => {
live.prices = fresh.prices;
}
});
}<form>
<input name="email" type="email" />
<input
name="password"
type="password"
/*MK<*/ data-ogygia-no-keep
/>
<input name="code" /*MK<*/ data-ogygia-no-keep />
</form>Limits and errors
- A wired class has to be exported from a module your app compiles:
export class Cart,export { Cart }, or a namedexport default class Cart. An anonymousexport default classfails the build (wire_class_anonymous). A class declared somewhere the plugin doesn’t compile can’t be sent (transportable_unregistered). - An island that only receives an instance doesn’t have to import its class: the build makes sure the class loads. If it can’t, the island fails with
transportable_class_missing; import the class as a value there (notimport type). - Context needs a key the browser can rebuild, shared by the provider and every reader: the name passed to
createContext, a string, orSymbol.for('name').
See Constraints for every boundary rule.