# Remote functions in SvelteKit

- Published: 2026-12-01
- Tags: Why Svelte, Svelte
- URL: https://devtrillo.com/writing/why-svelte-14-remote-functions-in-sveltekit/

> Part 14 of a series on Svelte in 2026. [Part 13](/writing/why-svelte-13-form-actions-and-progressive-enhancement/) 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.[^remote]

## 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`):

```ts title="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:

```ts title="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:

```svelte title="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.[^remote]

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.[^remote] 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.

**Quiz:** 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?

- No, the layout's redirect protects the page and everything it calls
- Yes, if they know or guess an id
- No, because remote endpoints only accept requests from the app's own pages

**Answer:** Yes, if they know or guess an id — The query is a public endpoint. The schema checks that id is a string, not who's asking. The auth check belongs inside the query.

- Not "No, the layout's redirect protects the page and everything it calls": The layout guards the page's URL. The query has its own URL under /_app/remote, and nothing about the page runs when someone requests it directly.
- Not "No, because remote endpoints only accept requests from the app's own pages": That's true for writes in production, which check the Origin header. A query is a GET, and curl reads it fine.

## `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.[^remote]

```ts title="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 };
  },
);
```

```svelte
<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:

```ts
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.[^remote]

**Quiz:** 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?

- The new count, because remote functions keep queries in sync
- The old count, until something refreshes getLikes
- An error, because the cached query is now stale

**Answer:** The old count, until something refreshes getLikes — Call getLikes(id).refresh() inside the command to send the new value back with its response, or refresh it on the client after the await (a second request).

- Not "The new count, because remote functions keep queries in sync": That's the form default, not the command one. A command refreshes nothing on its own.
- Not "An error, because the cached query is now stale": Stale isn't an error. The query keeps showing its cached value until it's refreshed or set.

## 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".[^await] 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."[^usesrv]

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](https://svelte.dev/docs/kit/remote-functions) 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.

[^remote]: SvelteKit docs, [Remote functions](https://svelte.dev/docs/kit/remote-functions).

[^await]: Svelte docs, [`await` expressions](https://svelte.dev/docs/svelte/await-expressions), "Server-side rendering".

[^usesrv]: React docs, [`'use server'`](https://react.dev/reference/rsc/use-server).

- **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
