Remote functions in SvelteKit

By Esteban Trillonew today8 min readWhy SvelteSvelte

`getTodos()` looks like a drawer in your own desk. It's a hatch onto the street, so the lock goes on the function, not the page that calls it.
`getTodos()` looks like a drawer in your own desk. It's a hatch onto the street, so the lock goes on the function, not the page that calls it.

Part 14 of a series on Svelte in 2026. Part 13 covered form actions in +page.server.ts. This part is the newer way to talk to the server, which the SvelteKit docs say is where new development is going.

I put a function called getCounters in a file named todos.remote.ts, exported it, and never imported it anywhere. Then I built the app, pointed curl at it, and it answered with my server’s internal counters.

That’s the whole feature in one accident. A remote function is a server function you can import into a component and call like a local one, with its argument and return types intact. You don’t write the API route. SvelteKit writes it for you, one per export, whether a page uses it or not.

I like remote functions a lot. They’re also still experimental in SvelteKit 3.1, and the docs warn they’re “subject to change without notice”, so this post covers both halves: what you stop writing, and what’s still there that you didn’t write.1

Two flags before anything works

Remote functions need SvelteKit’s remoteFunctions flag and Svelte’s experimental async compiler option, both passed to the sveltekit() plugin in vite.config.ts (SvelteKit 3 has no svelte.config.js):

vite.config.ts
export default defineConfig({
plugins: [
sveltekit({
experimental: { remoteFunctions: true },
compilerOptions: { experimental: { async: true } },
}),
],
});

I ran everything here on SvelteKit 3.1.0, Svelte 5.57.3, Vite 8.3.5 and valibot 1.5.0, driven with Playwright 1.64.1 in Chromium. With only the first flag, the build failed on the first await in a component with experimental_async. With only the second, it failed on the .remote.ts file with config_feature_disabled, and the error message printed the config to add. You won’t ship this by accident.

A query is a fetch you don’t write

A remote module is any file under src with remote in its name. This one reads todos:

src/routes/todos.remote.ts
import * as v from "valibot";
import { query } from "$app/server";
import { todos } from "#lib/server/db.js";
export const getTodos = query(async () => [...todos]);
export const getTodo = query(v.number(), async (id) => {
return todos.find((t) => t.id === id) ?? null;
});

And the page awaits it, right in the component:

src/routes/todos/+page.svelte
<script lang="ts">
import { getTodos } from "../todos.remote";
const todos = $derived(await getTodos());
</script>
<ul>
{#each todos as todo (todo.id)}<li>{todo.text}</li>{/each}
</ul>

There’s no load, no +page.server.ts and no +server.ts. On the client, the import is replaced. I opened the built client chunk, and the whole remote module had become one line of stubs: $("12tkua5/getTodos"), $("12tkua5/getTodo") and so on, a hash plus a name. My #lib/server/db.js import and the seed data weren’t in any client file.

Each stub fetches from an endpoint SvelteKit generates. A client-side navigation to /todos sent GET /_app/remote/12tkua5/getTodos. A full page load sent none: the server ran the query during SSR and shipped the result with the HTML, so hydration didn’t ask again.

Two things the hand-written version wouldn’t have given me for free. The page called getTodos() twice, once for the list and once for a count, and the browser made one request, because identical calls share a cache entry. And the created field came back as a real Date, since arguments and results go through devalue rather than JSON.1

The types are the part the title promised. With getTodo taking a valibot v.number(), svelte-check 4.7.7 flagged getTodo('1') with “Argument of type ‘string’ is not assignable to parameter of type ‘number’”, and todo.txt with “Did you mean ‘text’?”. Nothing generated a client or a type file I had to keep in sync; the import is the contract.

The argument came from a stranger

That schema isn’t for TypeScript. It’s for the request.

getTodo(2) went out as GET …/getTodo?payload=WzJd, and WzJd is just [2] in base64. Anyone can write that URL. I sent ["1"] instead, a string where the schema wants a number, and got back {"type":"error","error":{"status":400,"message":"Bad Request"}}. The function never ran. The HTTP status of that response was 200, by the way; the 400 lives in the body, so a log that only reads status codes won’t count it.

The docs say to validate every argument with a Standard Schema library (Zod, Valibot, ArkType) and give you 'unchecked' as a deliberate opt-out.1 I’d treat a remote function with no schema the same way I’d treat an API route that does JSON.parse(body) and trusts the result, because that’s what it is.

Which brings back getCounters. On a production build served with vite preview, curl /_app/remote/12tkua5/getCounters returned my counters with a 200, and no page imported it. Every export of a remote module is a public endpoint. If a query returns something only a signed-in user should see, the check goes inside the query, reading cookies through getRequestEvent(), the same as it would in a route you wrote by hand.

A remote module exports getInvoice = query(v.string(), async (id) => db.invoice(id)). The only page that calls it is behind a +layout.server.ts that redirects anonymous users. Can an anonymous user read an invoice?

form is part 13 with types

The form kind covers what form actions did, and the docs point you at it first because it works without JavaScript.1

src/routes/todos.remote.ts
export const createTodo = form(
v.object({
text: v.pipe(v.string(), v.trim(), v.nonEmpty("Write something first.")),
}),
async ({ text }) => {
addTodo(text);
return { added: text };
},
);
<form {...createTodo}>
{#each createTodo.fields.text.issues() ?? [] as issue}
<p>{issue.message}</p>
{/each}
<input {...createTodo.fields.text.as("text")} />
<button>Add</button>
</form>
{#if createTodo.result?.added}<p>Added {createTodo.result.added}</p>{/if}

Spreading createTodo gives the form a real method="POST" and an action of ?/remote=12tkua5/createTodo, so with JavaScript off it posted as x-www-form-urlencoded, re-rendered with “Added oat”, and left that ?/remote=… in the URL. An empty submit rendered “Write something first.” from the schema’s message, and the input got aria-invalid="true". Part 13’s duplicate is back too: reloading after a native submit re-sent the POST and added a fifth item. A redirect(303, …) in the handler fixes it the same way.

With JavaScript on there’s no use:enhance to add; the spread includes the attachment that enhances it. My counter’s $state survived the submit, the URL stayed /todos, and the input was cleared.

The network tab showed three requests, though: the POST, then GET getTodos and GET getCount. By default a successful form refreshes every query on the page, which is the safe imitation of a full reload. Add one line to the handler, void getTodos().refresh(), and the refreshed list rides back inside the POST’s response. I counted one request for that version. The docs call it a single-flight mutation, and once you name a query to refresh, the refresh-everything default switches off for that submission.

command refreshes nothing

command is the one you call from an event handler, a like button or a drag-and-drop reorder, anywhere a <form> doesn’t fit:

export const addViaCommand = command(v.string(), async (text) => {
addTodo(text);
});

I wired three buttons to it on a page that listed await getTodos(). The plain one sent its POST, the server added the item, and the list on screen didn’t change. 14 items stayed 14. A command doesn’t refresh anything unless you tell it to.

Calling await getTodos().refresh() after the command fixed the list, in two round trips. Putting void getTodos().refresh() inside the command fixed it in one, the same single-flight trick as form. The docs still say to prefer form where you can, since a command is dead without JavaScript.1

A like button calls await addLike(post.id), a command that updates the database. Next to it, the page shows {await getLikes(post.id)}. The command's handler doesn't call refresh. What does the count show after the click?

Things that bit me

A pending snippet in the root layout switched off SSR for the whole app. I’d wrapped {@render children()} in a <svelte:boundary> with a “loading…” snippet, and the server sent exactly that: a page with “loading…” and no list, no form. With JavaScript off, the form from the last section simply didn’t exist. The Svelte docs do say it: during SSR a boundary with pending renders that snippet “while the rest of the content is ignored”.2 Put pending boundaries around the slow parts, never around everything.

A query can’t read event.url, params or route. Mine threw remote_request_property, “Cannot access event.url in a query. Pass the value as an argument to the query instead”, and the client got a generic 500. Queries are cached by their arguments and don’t re-run when you navigate, so a value from the URL has to be one of the arguments.

The dev server doesn’t check where requests come from. On vite dev, a command POST with Origin: https://evil.example went through. On vite preview, the same request got a 403 with “Cross-site remote requests are forbidden”, as did one with no Origin at all, and as did a text/plain body. Like part 13’s form actions, that protection only exists in a build, so test it there.

React’s version is for writes

React’s Server Functions look similar from the call site: mark a file "use server", import the function into a client component, call it. React is just as plain about what that creates: “Server Functions are exposed server endpoints and can be called anywhere in client code,” and their arguments are “fully client-controlled.”3

The difference is reads. The same page says Server Functions are designed for mutations and “not recommended for data fetching”, because frameworks usually run one at a time and can’t cache the result. For reads, React wants you in Server Components. SvelteKit’s query is the read half: cached per argument, deduplicated, refreshable from a mutation’s response. I didn’t build the React side; that comparison is from the docs.

What I’d take from this

Reach for form first and query second, and treat command as the thing you use when there’s no form to hang the write on. Put a schema on every argument and an auth check in every function that returns something private, since each export is an endpoint someone can call from a terminal.

And remember which flag you’re standing on. Remote functions have been in SvelteKit since 2.27 and they’re still marked experimental in 3.1, behind a compiler flag that Svelte says will go away in Svelte 6. I’d use them in a new app today. In an app I couldn’t touch for a year, I’d stay on load and form actions until the flag goes.

The remote functions page covers far more than I could run here: query.batch for n+1 lookups, query.live for streams, prerender, and client-requested refreshes with a required limit.

Next: SvelteKit 3, and what changed besides the config file.

  • Part 15 — SvelteKit 3: what's new: Config in vite.config.ts, #lib, env vars with schemas and one error hook for everything: what SvelteKit 3 now stops at build time, and what still slips through to a 500

Footnotes

  1. SvelteKit docs, Remote functions. ↩ ↩2 ↩3 ↩4 ↩5

  2. Svelte docs, await expressions, “Server-side rendering”. ↩

  3. React docs, 'use server'. ↩

Read next

  1. SvelteKit 3: what's newDec 1, 2026 Why Svelte · 8 min
  2. Migrating to SvelteKit 3 with sv migrateDec 1, 2026 Why Svelte · 7 min
  3. Form actions and progressive enhancementNov 30, 2026 Why Svelte · 9 min
  4. SvelteKit fundamentals: routes and layoutsNov 30, 2026 Why Svelte · 8 min
  5. Scoped styles: CSS that stays putNov 30, 2026 Why Svelte · 9 min
Piwi hands a single letter to the user at a mailbox; a small note reads no noise.

Get the next one in your inbox

One email when a post goes out, with its sketch. Nothing in between, and one link to leave.

Sign in faster next time?

Add a passkey and skip the email link. Your fingerprint, face or device PIN is enough.