Guide for SvelteKit Remote Functions...
Type-safe client-server communication for SvelteKit applications.
Use this skill by default for all SvelteKit projects. It covers:
queryformcommandRemote functions are defined in .remote.js or .remote.ts files.
// data.remote.ts
import { query } from '$app/server';
import { z } from 'zod';
export const getPosts = query(async () => {
return await db.getAllPosts();
});
export const getPost = query(z.string(), async (slug) => {
return await db.getPost(slug);
});
// Batch queries to prevent N+1 problems
export const getPostsBatch = query.batch(
z.string(),
async (slugs) => {
const posts = await db.getPostsBySlug(slugs);
return slugs.map(slug => posts.find(p => p.slug === slug));
}
);
<!-- +page.svelte -->
<script>
import { getPosts } from './data.remote';
</script>
{#each await getPosts() as post}
<div>{post.title}</div>
{/each}
Or using properties:
<script>
import { getPosts } from './data.remote';
const posts = getPosts();
</script>
{#if posts.loading}
Loading...
{:else if posts.error}
Error!
{:else}
{#each posts.current as post}
<div>{post.title}</div>
{/each}
{/if}
// data.remote.ts
import { form } from '$app/server';
import { redirect } from '@sveltejs/kit';
import { z } from 'zod';
export const createPost = form(async (data) => {
const title = data.get('title');
// Sensitive fields (prefixed with _) are not sent back to client
const password = data.get('_password');
await db.insert(title);
// Refresh queries that changed
getPosts().refresh();
redirect(303, '/posts');
});
// With validation schema
export const createUser = form(
z.object({
email: z.string().email(),
username: z.string().min(3),
_password: z.string().min(8) // Sensitive field
}),
async (data) => {
await db.createUser(data);
redirect(303, '/login');
}
);
<!-- +page.svelte -->
<form {...createPost}>
<input name="title" />
<input name="_password" type="password" />
<button>Create</button>
</form>
<!-- Multiple isolated form instances -->
{#each items as item}
<form {...deleteItem.for(item.id)}>
<button>Delete {item.name}</button>
</form>
{/each}
// likes.remote.ts
import { command, query } from '$app/server';
import { z } from 'zod';
export const getLikes = query(z.string(), async (id) => {
return await db.getLikes(id);
});
export const addLike = command(z.string(), async (id) => {
await db.incrementLikes(id);
getLikes(id).refresh();
});
<!-- +page.svelte -->
<script>
import { getLikes, addLike } from './likes.remote';
let { item } = $props();
const likes = getLikes(item.id);
</script>
<button onclick={() => addLike(item.id)}>
Like ({await likes})
</button>
<script>
import { getPosts } from './data.remote';
const posts = getPosts();
</script>
<button onclick={() => posts.refresh()}>
Refresh
</button>
Default: All queries refresh after form/command (inefficient).
Better: Specify which queries to refresh (single-flight mutation).
export const createPost = form(async (data) => {
await db.insert(data);
getPosts().refresh(); // ← Only refresh affected queries
redirect(303, '/posts');
});
<form {...createPost.enhance(async ({ submit }) => {
await submit().updates(getPosts()); // ← Specify queries
})}>
</form>
await addLike(id).updates(getLikes(id));
<form {...addTodo.enhance(async ({ data, submit }) => {
await submit().updates(
getTodos().withOverride((todos) => [
...todos,
{ text: data.get('text') }
])
);
})}>
</form>
The override applies immediately and reverts on error.
For complete implementation details, read the reference files:
query for fetching list and form for creationquery().refresh() before redirectquery for data and command for updatecommand().updates(query().withOverride(...))form.enhance() to customize submissionsubmit().updates() for targeted refreshWRONG - Missing Zod schema:
// ❌ DON'T: Arguments without validation
export const getPost = query(async (slug) => {
return await db.getPost(slug);
});
CORRECT:
// ✅ DO: Always validate arguments
import { z } from 'zod';
export const getPost = query(z.string(), async (slug) => {
return await db.getPost(slug);
});
WRONG - Empty object parameter:
// ❌ DON'T: Use empty object syntax
export const getPosts = query(async ({}) => {
return await db.getAllPosts();
});
CORRECT:
// ✅ DO: Omit parameters entirely
export const getPosts = query(async () => {
return await db.getAllPosts();
});
WRONG - Forgetting required arguments:
// ❌ DON'T: Call without required arguments
const post = getPost(); // Missing slug parameter!
CORRECT:
// ✅ DO: Always pass required arguments
const post = getPost(params.slug);
WRONG - Event as second parameter:
// ❌ DON'T: Use event as function parameter
export const getUser = query(z.string(), async (id, event) => {
const session = event.cookies.get('session');
return await db.getUser(id);
});
// ❌ Also wrong for commands
export const updateUser = command(z.string(), async (id, event) => {
const userId = event.locals.user.id;
await db.update(id, userId);
});
CORRECT:
// ✅ DO: Use getRequestEvent()
import { getRequestEvent } from '$app/server';
export const getUser = query(z.string(), async (id) => {
const { cookies } = getRequestEvent();
const session = cookies.get('session');
return await db.getUser(id);
});
// ✅ For commands too
export const updateUser = command(z.string(), async (id) => {
const { locals } = getRequestEvent();
const userId = locals.user.id;
await db.update(id, userId);
});
Query function signatures:
query(async () => { })query(z.schema(), async (arg) => { })query(async ({}) => { })query(async (arg) => { }) without schemaquery(z.schema(), async (arg, event) => { })When calling remote functions:
getPosts()getPost('slug-value')Form and Command:
FormDataAccessing request context:
import { getRequestEvent } from '$app/server' then use getRequestEvent()event as a function parameterAlways validate arguments using Standard Schema (Zod recommended):
import { z } from 'zod';
// String
query(z.string(), async (id) => { })
// Number
query(z.number(), async (count) => { })
// Object
query(z.object({
id: z.string(),
name: z.string()
}), async (data) => { })
// Optional
query(z.string().optional(), async (id) => { })
// Sensitive fields (underscore prefix)
form(z.object({
username: z.string(),
_password: z.string().min(8),
_apiKey: z.string().optional()
}), async (data) => {
// _password and _apiKey not sent back to client
})
// Complex schemas
query(z.object({
filters: z.object({
status: z.enum(['active', 'archived']),
limit: z.number().min(1).max(100)
})
}), async (params) => { })
Customize how validation errors are returned (e.g., for security):
// hooks.server.ts
export function handleValidationError({ event, issues }) {
// Hide validation details from client
return {
message: 'Invalid request',
code: 'VALIDATION_ERROR'
};
// Or return detailed errors
// return { issues };
}
getX() === getX()RequestEvent differs (no params/route.id, url.pathname is always /)handleValidationError hook in hooks.server.ts to customize validation error responses