Data & state
Remote functions
Kit's remote functions work inside islands unchanged. query, query.batch, query.live, prerender, command and form all run from an island, the server render's results are seeded so an island doesn't fetch twice, and a form submit refreshes the page in place.
On this page
An island often needs to talk to the server: read a list, save a change, follow a live count. Kit’s remote functions do that, and they work inside an island exactly as in a Kit page, because an island is an ordinary Svelte component. All six kinds run there: query, query.batch, query.live, prerender, command and form. They replace the endpoints and fetch calls you’d write by hand, and the server validates every call.
Two settings are needed, the same as for any Kit app that uses them: kit.experimental.remoteFunctions in svelte.config.js, and Svelte’s compilerOptions.experimental.async for await in components. A remote function that returns a held region also needs ogygia’s transport in src/hooks.ts.
In the example, an island awaits a query. The server render awaits it too, so the page arrives with the greeting in it.
import { query } from '$app/server';
export const greeting = query(
async () => 'Hello from the server'
);<script>
import { greeting } from '$lib/hello.remote';
</script>
<p>{await greeting()}</p><script>
import Greeting from '$lib/Greeting.svelte' with {
wake: 'load'
};
</script>
<Greeting />query
An island reads a query the way a Kit component does. await it for the value; that await runs during the server render, so the HTML has the data. A query object also has .current (the last value, kept while a new call is out), .loading, .error and .refresh().
Every island on a page shares one client runtime, and so one query cache. Two islands that call the same query with the same argument share one request and one result.
Why the island doesn’t fetch twice
In a production build, the results the server render awaited are written into the page, and an island that calls the same query when it wakes reads the result from there instead of fetching it. That covers query, query.live, prerender and form results. Kit does this itself only on csr = true pages; ogygia does it on csr = false pages.
A result is written into the page only when an island on the page can call that remote function, which means its code imports the remote module. A lake, a server island or the page’s own script that awaits a query only for the server render ships its HTML and no copy of the data, so a CMS entry rendered through a lake doesn’t cost the page twice. A result that failed, or hadn’t settled when the page went out, isn’t written either: the island fetches it.
In dev, the island fetches again when it wakes. Check data flows against a production build.
Demo
This counter is a client island. It reads a query and changes the value through two commands. The value lives on the server, so each click is a real round trip, and a .refresh() reads the value again afterwards. Open this page in a second tab, and both tabs share the count.
This docs page is prerendered, so the demo reads its query after it wakes. In your app, an await in the island reads it during the server render.
import { query, command } from '$app/server';
let count = 3;
export const getCount = query(async () => count);
export const bump = command(async () => {
count += 1;
return count;
});
export const reset = command(async () => {
count = 0;
return count;
});command
A command sends a POST to its endpoint and runs on the server. Call it from an event handler in the island. It doesn’t refresh anything on its own: tell the queries that changed, as the next section shows.
In production, POSTs go through Kit’s origin check, so a server behind a proxy needs the right ORIGIN (see Install), or every command and form answers 403.
In the example, a button bumps the count on the server, then reads it again.
<script>
import { getCount, bump } from '$lib/counter.remote';
const count = getCount();
</script>
<p>Count: {await count}</p>
<button
onclick={async () => {
await bump();
await count.refresh();
}}
>
+1
</button>Refreshing queries
After a command or a form changes data on the server, the queries that read it need new values. There are three ways, cheapest last:
- Call
.refresh()on the query in the island, after the command returns. That’s a second request. - Send the refresh with the change:
submit().updates(query)on a form, orcommand(…).updates(query), paired withrequested(query, limit).refreshAll()inside the command or form on the server. The new value comes back in the same response.updatesalone sends the query’s key but doesn’t fill the response.limitcaps how many of the query’s instances one request may refresh. - Return a held region from the command. Any
<Region>on the page that shows the same region repaints from the command’s own response. See Repaint after a command. When two commands can return the same region, give it the data’s version so the newest data stays on screen: Order answers with a version.
In the example, a like button sends the refresh with the command, so one request both adds the like and brings back the new count.
import { query, command, requested } from '$app/server';
let likes = 0;
export const getLikes = query(async () => likes);
export const like = command(async () => {
likes += 1;
await requested(getLikes, 1).refreshAll();
});<script>
import { getLikes, like } from '$lib/likes.remote';
</script>
<button onclick={() => like().updates(getLikes)}>
{await getLikes()} likes
</button>Forms
form() works inside an island: spread it onto a <form>. Without JavaScript, or before the island wakes, the form posts as a normal browser form and the page reloads with the result. Once the island is live, Kit submits it with fetch, with no reload.
After a successful submit, Kit refreshes the page’s data. On a csr = false page, ogygia does that as a soft refresh: it fetches the current page again, merges its <head> and updates page.data and the seeded remote data in place. There’s no body swap, no view transition and no island remount, so islands keep their state. Refresh the page’s data has the details. On Kit 3, whose form() calls refreshAll(), the submit also refreshes every query the page’s islands hold.
Kit skips this refresh when you take charge of it: when the submit calls .updates(…) (even with no arguments), or when the form’s handler refreshes queries on the server, as with requested(…).refreshAll() in Refresh queries after a change. Then page.data keeps its old values until the next navigation or invalidateAll().
In the example, a guestbook island posts a message through a remote form.
import { form } from '$app/server';
import * as v from 'valibot';
import { addMessage } from '$lib/server/guestbook';
export const sign = form(
v.object({ msg: v.pipe(v.string(), v.nonEmpty()) }),
async ({ msg }) => {
await addMessage(msg);
}
);<script>
import { sign } from '$lib/guestbook.remote';
</script>
<form {...sign}>
<input name="msg" />
<button>Sign</button>
</form>query.live
A query.live keeps a connection open and sends a new value each time the server yields one. In an island, .current holds the latest value and the component updates on each tick. Yield a held region instead of data, and the server renders each update: Live regions shows how.
query.batch and prerender need nothing special either. A prerender result an island awaits is seeded like a query’s, so the island doesn’t fetch it on wake.
Do and don’t
- Do refresh a query after a mutation, with
.refresh()orupdatesplusrequested(…, limit).refreshAll(). - Do keep remote calls that only feed the server render in the page, a lake or a server island, so their data isn’t shipped.
- Do check data flows against a production build, since dev doesn’t seed results.
- Don’t rely on
updatesalone: withoutrequested(…, limit).refreshAll()on the server, the response carries no new value. - Don’t fetch in
onMountto load data anawaitcould read during the server render.