SvelteKit Remote Functions: Part 1
SvelteKit is testing a new way to handle data. It is called Remote Functions. This feature allows the client and server to talk to each other easily.
What are Remote Functions?
Remote Functions let you call server-side logic from any part of your SvelteKit app. Even though you call them from the client, the code runs on the server. This means you can access databases or private environment variables safely.
How to enable it
You must turn on experimental mode in your svelte.config.js file:
const config = { kit: { experimental: { remoteFunctions: true } }, compilerOptions: { experimental: { async: true } } };
export default config;
Working with Queries
You can create remote functions by using files with the .remote.js or .remote.ts extension. There are four types:
- query (used for fetching data)
- form
- command
- prerender
The query function works like an HTTP GET request. You can import it into your Svelte components and use await to get your data.
Example of a remote query:
import { query } from '$app/server'; import * as db from '$lib/server/database';
export const getPosts = query(async () => {
const posts = await db.sqlSELECT title, slug FROM post;
return posts;
});
In your component, you use it like this:
{#each await getPosts() as { title, slug }}
Managing State
The query function provides three helpful properties to manage your UI:
- loading: True while fetching data.
- error: True if the request fails.
- current: Holds the successful data.
Smart Features
Validation: You can use libraries like Zod or Valibot to validate arguments passed to your query. This keeps your server safe.
Data Handling: SvelteKit uses devalue to send data. This supports complex types like Date and Map, which standard JSON cannot do easily.
Deduplication: If you call the same query multiple times with the same arguments, SvelteKit only runs it once. This prevents extra database load.
Refreshing: You can call .refresh() on a query to fetch the latest data from the server immediately.
Note: These features are experimental. The syntax might change in future updates.
Source: https://dev.to/nnutnonn/sveltekit-kaarthamngaankab-remote-function-part-1-4hg4
