Remote functions are a tool for type-safe communication between client and server. They can be called anywhere in your app, but always run on the server, meaning they can safely access server-only modules containing things like environment variables and database clients.
Combined with Svelte’s experimental support for await, it allows you to load and manipulate data directly inside your components.
This feature is currently experimental, meaning it is likely to contain bugs and is subject to change without notice. You must opt in by adding the compilerOptions.experimental.async and kit.experimental.remoteFunctions options in your svelte.config.js:
The options to be passed to the Svelte compiler. A few options are set by default,
including dev and css. However, some options are non-configurable, like
filename, format, generate, and cssHash (in dev).
Allow await keyword in deriveds, template expressions, and the top level of components
5.36
:true}}};exportdefaultconfigconstconfig:Config
{import('@sveltejs/kit').Config}
;
Overview
Remote functions are exported from a .remote.js or .remote.ts file, and come in four flavours: query, form, command and prerender. On the client, the exported functions are transformed to fetch wrappers that invoke their counterparts on the server via a generated HTTP endpoint. Remote files can be placed anywhere in your src directory (except inside the src/lib/server directory), and third party libraries can provide them, too.
query
The query function allows you to read dynamic data from the server.
For static data, consider using prerender functions instead. Queries cannot be used when the entire page is prerendered (meaning export const prerender = true is applied to the page or a parent layout), such as when using adapter-static.
reference(async()=>{constpostsconstposts:any[]=awaitdb(alias)module"$lib/server/database"importdb.sqlfunctionsql(strings:TemplateStringsArray,...values:any[]):Promise<any[]>`
SELECT title, slug
FROM post
ORDER BY published_at
DESC
`;returnpostsconstposts:any[];});
Throughout this page, you’ll see imports from fictional modules like $lib/server/database and $lib/server/auth. These are purely for illustrative purposes — you can use whatever database client and auth setup you like.
Since getPost exposes an HTTP endpoint, it’s important to validate this argument to be sure that it’s the correct type. For this, we can use any Standard Schema validation library such as Zod or Valibot:
Throws an error with a HTTP status code and an optional message.
When called during request handling, this will cause SvelteKit to
return an error response without invoking handleError.
Make sure you're not catching the thrown error, which would prevent SvelteKit from handling it.
(),async(slug(parameter)slug:string)=>{const[postconstpost:any]=awaitdb(alias)module"$lib/server/database"importdb.sqlfunctionsql(strings:TemplateStringsArray,...values:any[]):Promise<any[]>`
SELECT * FROM post
WHERE slug =${slug(parameter)slug:string}`;if(!postconstpost:any)error(alias)error(status:number,body?:{message:string;}extendsApp.Error?App.Error|string|undefined:never):never(+1overload)importerror
Throws an error with a HTTP status code and an optional message.
When called during request handling, this will cause SvelteKit to
return an error response without invoking handleError.
Make sure you're not catching the thrown error, which would prevent SvelteKit from handling it.
Both the argument and the return value are serialized with devalue, which handles types like Date and Map (and custom types defined in your transport hook) in addition to JSON.
For query and prerender arguments (but not return values), objects, maps, and sets are sorted so that instances with the same members result in the same cache key. For example, getPosts({ limit: 10, offset: 10 }) and getPosts({ offset: 10, limit: 10 }) will result in the same cache key. If order is important to you, you’ll have to use an array.
Deduplication
When you call a query function, SvelteKit serializes the argument you call it with and uses it as a cache key. On the server, this is used to create a request-scoped cache so that multiple invocations of the same query only result in the work happening once. On the client, SvelteKit does something similar: Multiple identical invocations of a query all point to the same instance.
You can await a query in any context — components, event handlers, universal load functions, async callbacks — and SvelteKit will dedupe with whatever other consumers are using the same query. For example:
<script>import{getData}from'./data.remote.js';// awaited inside the component template — populates the cacheconstdata=getData();</script><p>{awaitdata}</p><!-- this dedupes with the component-level use above; no extra request --><buttononclick={async()=>console.log(awaitgetData())}>click me!</button>
The cache is shared as long as the query is in active use — rendered in a component, currently being awaited, or otherwise referenced. Once nothing is using it, the cached value is released.
Refreshing queries
Any query can be re-fetched via its refresh method, which retrieves the latest value from the server:
<buttononclick={()=>getPosts().refresh()}>Check for new posts</button>
Queries are cached while they’re on the page, meaning getPosts() === getPosts(). This means you don’t need a reference like const posts = getPosts() in order to update the query.
query.batch
query.batch works like query except that it batches requests that happen within the same macrotask. This solves the so-called n+1 problem: rather than each query resulting in a separate database call (for example), simultaneous queries are grouped together.
On the server, the callback receives an array of the arguments the function was called with. It must return a function of the form (input: Input, index: number) => Output. SvelteKit will then call this with each of the input arguments to resolve the individual calls with their results.
(),async(cityIds(parameter)cityIds:string[])=>{constweatherconstweather:any[]=awaitdb(alias)module"$lib/server/database"importdb.sqlfunctionsql(strings:TemplateStringsArray,...values:any[]):Promise<any[]>`
SELECT * FROM weather
WHERE city_id = ANY(${cityIds(parameter)cityIds:string[]})
`;constlookupconstlookup:Map<any,any>=newMapvarMap:MapConstructornew<any,any>(iterable?:Iterable<readonly[any,any]>|null|undefined)=>Map<any,any>(+3overloads)(weatherconstweather:any[].map(method)Array<any>.map<[any,any]>(callbackfn:(value:any,index:number,array:any[])=>[any,any],thisArg?:any):[any,any][]
Calls a defined callback function on each element of an array, and returns an array that contains the results.
callbackfn
A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.
thisArg
An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
Returns a specified element from the Map object. If the value that is associated to the provided key is an object, then you will get a reference to that object and any change made to that object will effectively modify it inside the Map.
Returns the element associated with the specified key. If no element is associated with the specified key, undefined is returned.
query.live is for accessing real-time data from the server. It behaves similarly to query, but the callback — typically an async generator function — returns an AsyncIterable:
A callback used to initialize the promise. This callback is passed two arguments:
a resolve callback used to resolve the promise with a value or the result of another promise,
and a reject callback used to reject the promise with a provided reason or error.
During server-side rendering, await getTime() returns the first yielded value then closes the iterator. This initial value is serialized and reused during hydration.
On the client, the query stays connected while it’s actively used in a component. Multiple instances share a connection. When there are no active uses left, the stream disconnects and server-side iteration is stopped.
Live queries expose a connected property and reconnect() method:
If the connection drops, connected becomes false. SvelteKit will attempt to reconnect passively, with exponential backoff, and actively if navigator.onLine goes from false to true.
Unlike query, live queries do not have a refresh() method, as they are self-updating.
If you need direct, imperative access to the underlying stream of values (rather than the reactive current property), live query instances are themselves async-iterable. You can for await over the instance directly:
The console module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
A global console instance configured to write to process.stdout and
process.stderr. The global console can be used without importing the node:console module.
Warning: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the note on process I/O for
more information.
Example using the global console:
console.log('hello world');// Prints: hello world, to stdoutconsole.log('hello %s','world');// Prints: hello world, to stdoutconsole.error(newError('Whoops, something bad happened'));// Prints error message and stack trace to stderr:// Error: Whoops, something bad happened// at [eval]:5:15// at Script.runInThisContext (node:vm:132:18)// at Object.runInThisContext (node:vm:309:38)// at node:internal/process/execution:77:19// at [eval]-wrapper:6:22// at evalScript (node:internal/process/execution:76:60)// at node:internal/main/eval_string:23:3constname='Will Robinson';console.warn(`Danger${name}! Danger!`);// Prints: Danger Will Robinson! Danger!, to stderr
Example using the Console class:
constout=getStreamSomehow();consterr=getStreamSomehow();constmyConsole=newconsole.Console(out,err);myConsole.log('hello world');// Prints: hello world, to outmyConsole.log('hello %s','world');// Prints: hello world, to outmyConsole.error(newError('Whoops, something bad happened'));// Prints: [Error: Whoops, something bad happened], to errconstname='Will Robinson';myConsole.warn(`Danger${name}! Danger!`);// Prints: Danger Will Robinson! Danger!, to err
Prints to stdout with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to printf(3)
(the arguments are all passed to util.format()).
constcount=5;console.log('count: %d',count);// Prints: count: 5, to stdoutconsole.log('count:',count);// Prints: count: 5, to stdout
Multiple consumers of the same live query (whether reactive — via await or current — or imperative for await loops) share a single underlying connection. The first value yielded to a for await iterator is the most-recently-received value, if one is already available, mirroring the semantics of awaiting the resource directly. Subsequent yields fire whenever a new value arrives from the server. If values arrive faster than the consumer drains the iterator, only the latest pending value is kept — live streams are not event logs.
On the server, for await likewise joins a per-request shared iteration of the underlying generator, so concurrent consumers within the same request don’t run the user-defined generator multiple times.
It’s essential that you don’t cache live query responses in a service worker, since the cloned response will continue streaming long after the page is closed. Make sure that your caching logic excludes any responses with a Cache-Control header that includes no-store.
form
The form function makes it easy to write data to the server. It takes a callback that receives data constructed from the submitted FormData...
Throws an error with a HTTP status code and an optional message.
When called during request handling, this will cause SvelteKit to
return an error response without invoking handleError.
Make sure you're not catching the thrown error, which would prevent SvelteKit from handling it.
Redirect a request. When called during request handling, SvelteKit will return a redirect response.
Make sure you're not catching the thrown redirect, which would prevent SvelteKit from handling it.
Most common status codes:
303 See Other: redirect as a GET request (often used after a form POST request)
307 Temporary Redirect: redirect will keep the request method
308 Permanent Redirect: redirect will keep the request method, SEO will be transferred to the new page
Hint: This schema removes unknown entries. The output will only include the
entries you specify. To include unknown entries, use looseObject. To
return an issue for unknown entries, use strictObject. To include and
validate unknown entries, use objectWithRest.
())}),async({title(parameter)title:string,content(parameter)content:string})=>{ // Check the user is logged inconstuserconstuser:auth.User|null=awaitauth(alias)module"$lib/server/auth"importauth.getUserfunctiongetUser():Promise<auth.User|null>
Gets a user's info from their cookies, using getRequestEvent
Throws an error with a HTTP status code and an optional message.
When called during request handling, this will cause SvelteKit to
return an error response without invoking handleError.
Make sure you're not catching the thrown error, which would prevent SvelteKit from handling it.
Passes a string and
{@linkcode
replaceValue
}
to the [Symbol.replace] method on
{@linkcode
searchValue
}
. This method is expected to implement its own replacement algorithm.
searchValue
An object that supports searching for and replacing matches within a string.
replaceValue
The replacement text.
(/ /g,'-'); // Insert into the databaseawaitdb(alias)module"$lib/server/database"importdb.sqlfunctionsql(strings:TemplateStringsArray,...values:any[]):Promise<any[]>`
INSERT INTO post (slug, title, content)
VALUES (${slugconstslug:string},${title(parameter)title:string},${content(parameter)content:string})
`; // Redirect to the newly created pageredirect(alias)redirect(status:300|301|302|303|304|305|306|307|308|({}&number),location:string|URL):neverimportredirect
Redirect a request. When called during request handling, SvelteKit will return a redirect response.
Make sure you're not catching the thrown redirect, which would prevent SvelteKit from handling it.
Most common status codes:
303 See Other: redirect as a GET request (often used after a form POST request)
307 Temporary Redirect: redirect will keep the request method
308 Permanent Redirect: redirect will keep the request method, SEO will be transferred to the new page
...and returns an object that can be spread onto a <form> element. The callback is called whenever the form is submitted.
src/routes/blog/new/+page
<script>import{createPost}from'../data.remote';</script><h1>Create a new post</h1><form{...createPost}><!-- form content goes here --><button>Publish!</button></form>
<scriptlang="ts">import{createPost}from'../data.remote';</script><h1>Create a new post</h1><form{...createPost}><!-- form content goes here --><button>Publish!</button></form>
The form object contains method and action properties that allow it to work without JavaScript (i.e. it submits data and reloads the page). It also has an attachment that progressively enhances the form when JavaScript is available, submitting data without reloading the entire page.
As with query, if the callback uses the submitted data, it should be validated by passing a Standard Schema as the first argument to form.
Fields
A form is composed of a set of fields, which are defined by the schema. In the case of createPost, we have two fields, title and content, which are both strings. To get the attributes for a field, call its .as(...) method, specifying which input type to use. For most input types, you can also pass a second argument — .as(type, value) — to control the rendered value:
<form{...createPost}><label><h2>Title</h2><input{...createPost.fields.title.as('text')}/></label><label><h2>Write your post</h2><textarea{...createPost.fields.content.as('text')}></textarea></label><button>Publish!</button></form>
These attributes allow SvelteKit to set the correct input type, set a name that is used to construct the data passed to the handler, populate the value of the form (for example following a failed submission, to save the user having to re-enter everything), and set the aria-invalid state.
Passing a second argument to .as(...) is useful when rendering a form from existing data, such as an edit form or multiple instances created with for(...). As well as setting the value of the element when it is rendered, it controls the value of the element when the form is reset. radio, submit and hidden inputs always need this value, and checkbox inputs need it when they represent one option in an array field. file inputs cannot be populated this way.
The generated name attribute uses JS object notation (e.g. nested.array[0].value). String keys that require quotes such as object['nested-array'][0].value are not supported. Under the hood, boolean checkbox and number field names are prefixed with b: and n:, respectively, to signal SvelteKit to coerce the values from strings prior to validation.
Fields can be nested in objects and arrays, and their values can be strings, numbers, booleans or File objects. For example, if your schema looked like this...
Hint: This schema removes unknown entries. The output will only include the
entries you specify. To include unknown entries, use looseObject. To
return an issue for unknown entries, use strictObject. To include and
validate unknown entries, use objectWithRest.
Hint: This schema removes unknown entries. The output will only include the
entries you specify. To include unknown entries, use looseObject. To
return an issue for unknown entries, use strictObject. To include and
validate unknown entries, use objectWithRest.
<script>import{createProfile}from'./data.remote';const{name,photo,info,attributes}=createProfile.fields;</script><form{...createProfile}enctype="multipart/form-data"><label><input{...name.as('text')}/> Name</label><label><input{...photo.as('file')}/> Photo</label><label><input{...info.height.as('number')}/> Height (cm)</label><label><input{...info.likesDogs.as('checkbox')}/> I like dogs</label><h2>My best attributes</h2><input{...attributes[0].as('text')}/><input{...attributes[1].as('text')}/><input{...attributes[2].as('text')}/><button>submit</button></form>
Because our form contains a file input, we’ve added an enctype="multipart/form-data" attribute. The values for info.height and info.likesDogs are coerced to a number and a boolean respectively.
If a checkbox input is unchecked, the value is not included in the FormData object that SvelteKit constructs the data from. As such, we have to make the value optional in our schema. In Valibot that means using v.optional(v.boolean(), false) instead of just v.boolean(), whereas in Zod it would mean using z.coerce.boolean<boolean>().
In the case of radio and checkbox inputs that all belong to the same field, the value must be specified as a second argument to .as(...):
Hint: This schema removes unknown entries. The output will only include the
entries you specify. To include unknown entries, use looseObject. To
return an issue for unknown entries, use strictObject. To include and
validate unknown entries, use objectWithRest.
<form{...survey}><h2>Which operating system do you use?</h2>{#eachoperatingSystemsasos}<label><input{...survey.fields.operatingSystem.as('radio',os)}>{os}</label>{/each}<h2>Which languages do you write code in?</h2>{#eachlanguagesaslanguage}<label><input{...survey.fields.languages.as('checkbox',language)}>{language}</label>{/each}<button>submit</button></form>
Alternatively, you could use select and select multiple:
<form{...survey}><h2>Which operating system do you use?</h2><select{...survey.fields.operatingSystem.as('select')}>{#eachoperatingSystemsasos}<option>{os}</option>{/each}</select><h2>Which languages do you write code in?</h2><select{...survey.fields.languages.as('select multiple')}>{#eachlanguagesaslanguage}<option>{language}</option>{/each}</select><button>submit</button></form>
As with unchecked checkbox inputs, if no selections are made then the data will be undefined. For this reason, the languages field uses v.optional(v.array(...), []) rather than just v.array(...).
Programmatic validation
In addition to declarative schema validation, you can programmatically mark fields as invalid inside the form handler using the invalid helper from @sveltejs/kit. This is useful for cases where you can’t know if something is valid until you try to perform some action.
It throws just like redirect or error
It accepts multiple arguments that can be strings (for issues relating to the form as a whole — these will only show up in fields.allIssues()) or standard-schema-compliant issues (for those relating to a specific field). Use the issue parameter for type-safe creation of such issues:
Use this to throw a validation error to imperatively fail form validation.
Can be used in combination with issue passed to form actions to create field-specific issues.
import{invalid}from'@sveltejs/kit';import{form}from'$app/server';import{tryLogin}from'$lib/server/auth';import*asvfrom'valibot';exportconstlogin=form(v.object({name:v.string(),_password:v.string()}),async({name,_password})=>{constsuccess=tryLogin(name,_password);if(!success){invalid('Incorrect username or password');}// ...});
reference}from'$app/server';import*asdb(alias)module"$lib/server/database"importdbfrom'$lib/server/database';exportconstbuyHotcakesconstbuyHotcakes:RemoteForm<{qty:number;},void>=form(alias)form<v.ObjectSchema<{readonlyqty:v.SchemaWithPipe<readonly[v.NumberSchema<undefined>,v.MinValueAction<number,1,"you must buy at least one hotcake">]>;},undefined>,void>(validate:v.ObjectSchema<{readonlyqty:v.SchemaWithPipe<readonly[v.NumberSchema<undefined>,v.MinValueAction<number,1,"you must buy at least one hotcake">]>;},undefined>,fn:(data:{qty:number;},issue:{qty:(message:string)=>StandardSchemaV1<Input=unknown,Output=Input>.Issue;}&((message:string)=>StandardSchemaV1<Input=unknown,Output=Input>.Issue))=>MaybePromise<...>):RemoteForm<...>(+2overloads)importform
Creates a form object that can be spread onto a <form> element.
reference(vimportv.object(alias)object<{readonlyqty:v.SchemaWithPipe<readonly[v.NumberSchema<undefined>,v.MinValueAction<number,1,"you must buy at least one hotcake">]>;}>(entries:{readonlyqty:v.SchemaWithPipe<readonly[v.NumberSchema<undefined>,v.MinValueAction<number,1,"you must buy at least one hotcake">]>;}):v.ObjectSchema<{readonlyqty:v.SchemaWithPipe<readonly[v.NumberSchema<undefined>,v.MinValueAction<number,1,"you must buy at least one hotcake">]>;},undefined>(+1overload)exportobject
Creates an object schema.
Hint: This schema removes unknown entries. The output will only include the
entries you specify. To include unknown entries, use looseObject. To
return an issue for unknown entries, use strictObject. To include and
validate unknown entries, use objectWithRest.
entries
The entries schema.
An object schema.
({qty(property)qty:v.SchemaWithPipe<readonly[v.NumberSchema<undefined>,v.MinValueAction<number,1,"you must buy at least one hotcake">]>:vimportv.pipe(alias)pipe<v.NumberSchema<undefined>,v.MinValueAction<number,1,"you must buy at least one hotcake">>(schema:v.NumberSchema<undefined>,item1:v.MinValueAction<number,1,"you must buy at least one hotcake">|v.PipeAction<number,number,v.MinValueIssue<number,1>>):v.SchemaWithPipe<readonly[v.NumberSchema<undefined>,v.MinValueAction<number,1,"you must buy at least one hotcake">]>(+20overloads)exportpipe
Adds a pipeline to a schema, that can validate and transform its input.
(),vimportv.minValue(alias)minValue<number,1,"you must buy at least one hotcake">(requirement:1,message:"you must buy at least one hotcake"):v.MinValueAction<number,1,"you must buy at least one hotcake">(+1overload)exportminValue
Creates a min value validation action.
requirement
The minimum value.
message
The error message.
A min value action.
(1,'you must buy at least one hotcake'))}),async(data(parameter)data:{qty:number;},issue(parameter)issue:{qty:(message:string)=>StandardSchemaV1.Issue;}&((message:string)=>StandardSchemaV1.Issue))=>{try{awaitdb(alias)module"$lib/server/database"importdb.buyfunctionbuy(qty:number):Promise<void>(data(parameter)data:{qty:number;}.qty(property)qty:number);}catch(e(localvar)e:unknown){if(e(localvar)e:unknown.codeany==='OUT_OF_STOCK'){invalid(alias)invalid(...issues:(StandardSchemaV1<Input=unknown,Output=Input>.Issue|string)[]):neverimportinvalid
Use this to throw a validation error to imperatively fail form validation.
Can be used in combination with issue passed to form actions to create field-specific issues.
import{invalid}from'@sveltejs/kit';import{form}from'$app/server';import{tryLogin}from'$lib/server/auth';import*asvfrom'valibot';exportconstlogin=form(v.object({name:v.string(),_password:v.string()}),async({name,_password})=>{constsuccess=tryLogin(name,_password);if(!success){invalid('Incorrect username or password');}// ...});
2.47.3
reference(issue(parameter)issue:{qty:(message:string)=>StandardSchemaV1.Issue;}&((message:string)=>StandardSchemaV1.Issue).qty(property)qty:(message:string)=>StandardSchemaV1<Input=unknown,Output=Input>.Issue(`we don't have enough hotcakes`));}}});
Validation
If the submitted data doesn’t pass the schema, the callback will not run. Instead, each invalid field’s issues() method will return an array of { message: string } objects, and the aria-invalid attribute (returned from as(...)) will be set to true:
<form{...createPost}><label><h2>Title</h2>{#eachcreatePost.fields.title.issues()asissue}<pclass="issue">{issue.message}</p>{/each}<input{...createPost.fields.title.as('text')}/></label><label><h2>Write your post</h2>{#eachcreatePost.fields.content.issues()asissue}<pclass="issue">{issue.message}</p>{/each}<textarea{...createPost.fields.content.as('text')}></textarea></label><button>Publish!</button></form>
If the title is valid, or has not yet been validated, createPost.fields.title.issues() will return undefined.
You don’t need to wait until the form is submitted to validate the data — you can call validate() programmatically, for example in an oninput callback (which will validate the data on every keystroke) or an onchange callback:
By default, issues will be ignored if they belong to form controls that haven’t yet been interacted with. To validate all inputs, call validate({ includeUntouched: true }).
For client-side validation, you can specify a preflight schema which will populate issues() and prevent data being sent to the server if the data doesn’t validate:
<script>import*asvfrom'valibot';import{createPost}from'../data.remote';constschema=v.object({title:v.pipe(v.string(),v.nonEmpty()),content:v.pipe(v.string(),v.nonEmpty())});</script><h1>Create a new post</h1><form{...createPost.preflight(schema)}><!-- --></form>
The preflight schema can be the same object as your server-side schema, if appropriate, though it won’t be able to do server-side checks like ‘this value already exists in the database’. Note that you cannot export a schema from a .remote.ts or .remote.js file, so the schema must either be exported from a shared module, or from a <script module> block in the component containing the <form>.
To get a list of all issues, rather than just those belonging to a single field, you can use the fields.allIssues() method:
Alternatively, createPost.fields.value() would return a { title, content } object.
The value() of a field does not reflect defaults provided as a second argument to as (as in fields.title.as('text', '...')) until it is edited or submitted. You can programmatically update a field (or a collection of fields) via the set(...) method:
<script>import{createPost}from'../data.remote';// this...createPost.fields.set({title:'My new blog post',content:'Lorem ipsum dolor sit amet...'});// ...is equivalent to this:createPost.fields.title.set('My new blog post');createPost.fields.content.set('Lorem ipsum dolor sit amet');</script>
Handling sensitive data
In the case of a non-progressively-enhanced form submission (i.e. where JavaScript is unavailable, for whatever reason) value() is also populated if the submitted data is invalid, so that the user does not need to fill the entire form out from scratch.
You can prevent sensitive data (such as passwords and credit card numbers) from being sent back to the user by using a name with a leading underscore:
In this example, if the data does not validate, only the first <input> will be populated when the page reloads.
Returns and redirects
The example above uses redirect(...), which sends the user to the newly created page. Alternatively, the callback could return data, in which case it would be available as createPost.result:
Hint: This schema removes unknown entries. The output will only include the
entries you specify. To include unknown entries, use looseObject. To
return an issue for unknown entries, use strictObject. To include and
validate unknown entries, use objectWithRest.
<script>import{createPost}from'../data.remote';</script><h1>Create a new post</h1><form{...createPost}><!-- --></form>{#ifcreatePost.result?.success}<p>Successfully published!</p>{/if}
<scriptlang="ts">import{createPost}from'../data.remote';</script><h1>Create a new post</h1><form{...createPost}><!-- --></form>{#ifcreatePost.result?.success}<p>Successfully published!</p>{/if}
This value is ephemeral — it will vanish if you resubmit, navigate away, or reload the page.
The result value need not indicate success — it can also contain validation errors, along with any data that should repopulate the form on page reload.
If an error occurs during submission, the nearest +error.svelte page will be rendered.
enhance
We can customize what happens when the form is submitted with the enhance method:
src/routes/blog/new/+page
<script>import{createPost}from'../data.remote';import{showToast}from'$lib/toast';</script><h1>Create a new post</h1><form{...createPost.enhance(async(form)=>{try{if(awaitform.submit()){form.element.reset();showToast('Successfully published!');}else{showToast('Invalid data!');}}catch(error){showToast('Oh no! Something went wrong');}})}><!-- --></form>
<scriptlang="ts">import{createPost}from'../data.remote';import{showToast}from'$lib/toast';</script><h1>Create a new post</h1><form{...createPost.enhance(async(form)=>{try{if(awaitform.submit()){form.element.reset();showToast('Successfully published!');}else{showToast('Invalid data!');}}catch(error){showToast('Oh no! Something went wrong');}})}><!-- --></form>
When using enhance, the <form> is not automatically reset — you must call form.element.reset() if you want to clear the inputs.
The callback receives a copy of the form instance. It has all the same properties and methods except enhance, and form.submit() performs the submission directly without re-running the enhance callback. Inside the callback, form.element is always defined.
Multiple instances of a form
Some forms may be repeated as part of a list. In this case you can create separate instances of a form function via for(id) to achieve isolation.
When each instance should render different values, pass them as the second argument to .as(...):
It’s possible for a <form> to have multiple submit buttons. For example, you might have a single form that allows you to log in or register depending on which button was clicked.
To accomplish this, add a field to your schema for the button value, and use as('submit', value) to bind it:
Hint: This schema removes unknown entries. The output will only include the
entries you specify. To include unknown entries, use looseObject. To
return an issue for unknown entries, use strictObject. To include and
validate unknown entries, use objectWithRest.
(),async(id(parameter)id:string)=>{const[rowconstrow:any]=awaitdb(alias)module"$lib/server/database"importdb.sqlfunctionsql(strings:TemplateStringsArray,...values:any[]):Promise<any[]>`
SELECT likes
FROM item
WHERE id =${id(parameter)id:string}`;returnrowconstrow:any.likesany;});exportconstaddLikeconstaddLike:RemoteCommand<string,void>=command(alias)command<v.StringSchema<undefined>,void>(validate:v.StringSchema<undefined>,fn:(arg:string)=>MaybePromise<void>):RemoteCommand<string,void>(+2overloads)importcommand
Creates a remote command. When called from the browser, the function will be invoked on the server via a fetch call.
(),async(id(parameter)id:string)=>{awaitdb(alias)module"$lib/server/database"importdb.sqlfunctionsql(strings:TemplateStringsArray,...values:any[]):Promise<any[]>`
UPDATE item
SET likes = likes + 1
WHERE id =${id(parameter)id:string}`;});
Now simply call addLike, from (for example) an event handler:
+page
<script>import{getLikes,addLike}from'./likes.remote';import{showToast}from'$lib/toast';let{item}=$props();</script><buttononclick={async()=>{try{awaitaddLike(item.id);}catch(error){showToast('Something went wrong!');}}}>add like</button><p>likes: {awaitgetLikes(item.id)}</p>
<scriptlang="ts">import{getLikes,addLike}from'./likes.remote';import{showToast}from'$lib/toast';let{item}=$props();</script><buttononclick={async()=>{try{awaitaddLike(item.id);}catch(error){showToast('Something went wrong!');}}}>add like</button><p>likes: {awaitgetLikes(item.id)}</p>
Commands cannot be called during render.
Single-flight mutations
The purpose of both form and command is mutating data. In many cases, mutating data invalidates other data. By default, form deals with this by automatically invalidating all queries and load functions following a successful submission, to emulate what would happen with a traditional full-page reload. command, on the other hand, does nothing. Typically, neither of these options is going to be the ideal solution — invalidating everything is likely wasteful, as it’s unlikely a form submission changed everything being displayed on your webpage. In the case of command, doing nothing likely under-invalidates your app, leaving stale data displayed. In both cases, it’s common to have to perform two round-trips to the server: One to run the mutation, and another after that completes to re-request the data from any queries you need to refresh.
SvelteKit solves both of these problems with single-flight mutations: Your form submission or command invocation can refresh queries and pass their results back to the client in a single request.
Server-driven refreshes
In most circumstances, the server handler knows what client data needs to be updated based on its arguments:
Hint: This schema removes unknown entries. The output will only include the
entries you specify. To include unknown entries, use looseObject. To
return an issue for unknown entries, use strictObject. To include and
validate unknown entries, use objectWithRest.
entries
The entries schema.
An object schema.
({/* ... */}),async(data(parameter)data:{})=>{ // form logic goes here... // Refresh `getPosts()` on the server, and send // the data back with the result of `createPost` // it's safe to throw away the promise from `refresh`, // as the framework awaits it for us before serving the responsevoidgetPostsconstgetPosts:(arg:void)=>RemoteQuery<void>().refresh(method)refresh():Promise<void>
On the client, this function will re-fetch the query from the server.
On the server, this can be called in the context of a command or form and the refreshed data will accompany the action response back to the client.
This prevents SvelteKit needing to refresh all queries on the page in a second server round-trip.(); // Redirect to the newly created pageredirect(alias)redirect(status:300|301|302|303|304|305|306|307|308|({}&number),location:string|URL):neverimportredirect
Redirect a request. When called during request handling, SvelteKit will return a redirect response.
Make sure you're not catching the thrown redirect, which would prevent SvelteKit from handling it.
Most common status codes:
303 See Other: redirect as a GET request (often used after a form POST request)
307 Temporary Redirect: redirect will keep the request method
308 Permanent Redirect: redirect will keep the request method, SEO will be transferred to the new page
Hint: This schema removes unknown entries. The output will only include the
entries you specify. To include unknown entries, use looseObject. To
return an issue for unknown entries, use strictObject. To include and
validate unknown entries, use objectWithRest.
()}),async(post(parameter)post:{id:string;})=>{ // form logic goes here...constresultconstresult:any=externalApiconstexternalApi:any
{any}
.updateany(post(parameter)post:{id:string;}); // The API already gives us the updated post, // no need to refresh it, we can set it directlygetPostconstgetPost:(arg:string)=>RemoteQuery<void>(post(parameter)post:{id:string;}.id(property)id:string).set(method)set(value:void):void
On the client, this function will update the value of the query without re-fetching it.
On the server, this can be called in the context of a command or form and the specified data will accompany the action response back to the client.
This prevents SvelteKit needing to refresh all queries on the page in a second server round-trip.(resultconstresult:any);});
Because queries are keyed based on their arguments, getPost(post.id).set(result) on the server knows to look up the matching getPost(id) on the client to update it. The same goes for getPosts().refresh() -- it knows to look up getPosts() with no argument on the client.
Reconnecting live queries in mutations
Single-flight mutations can also reconnect query.live instances. In a form / command handler, call .reconnect() on the live query resource you want to reconnect:
Hint: This schema removes unknown entries. The output will only include the
entries you specify. To include unknown entries, use looseObject. To
return an issue for unknown entries, use strictObject. To include and
validate unknown entries, use objectWithRest.
This schedules a reconnect for the matching active client instances and applies it as part of the mutation response (i.e. in the same flight as the form/command result). You might need this if, for example, the command modifies a cookie that the live query needs to restart in order to capture.
Client-requested refreshes
Unfortunately, life isn’t always as simple as the preceding example. The server always knows which query functions to update, but it may not know which specific query instances to update. For example, if getPosts({ filter: 'author:santa' }) is rendered on the client, calling getPosts().refresh() in the server handler won’t update it. You’d need to call getPosts({ filter: 'author:santa' }).refresh() instead — but how could you know which specific combinations of filters are currently rendered on the client, especially if your query argument is more complicated than an object with just one key?
SvelteKit makes this easy by allowing the client to request that the server updates specific data using submit().updates (for form) or myCommand().updates (for command):
awaitsubmitfunctionsubmit():Promise<any>&{updates(...updates:RemoteQueryUpdate[]):Promise<any>;}().updates(method)updates(...updates:RemoteQueryUpdate[]):Promise<any>( // to request all active instances of getPostsgetPostsfunctiongetPosts(args:{filter:string;}):RemoteQuery<Post[]>, // to request a specific instancegetPostsfunctiongetPosts(args:{filter:string;}):RemoteQuery<Post[]>({filter(property)filter:string:'author:santa'}), // to request a specific instance with an optimistic overridegetPostsfunctiongetPosts(args:{filter:string;}):RemoteQuery<Post[]>({filter(property)filter:string:'author:santa'}).withOverride(method)withOverride(update:(current:Post[])=>Post[]):RemoteQueryOverride
Temporarily override a query's value during a single-flight mutation to provide optimistic updates.
Inside a remote command or form callback, returns an iterable
of { arg, query } entries for the query instances the client asked to refresh, up to
the supplied limit. Each query is a RemoteQuery bound to the original
client-side cache key, so refresh() / set() propagate correctly even when
the query's schema transforms the input. arg is the validated argument,
i.e. the value after the schema has run (so InferOutput<Schema> for queries
declared with a Standard Schema).
Arguments that fail validation or exceed limit are recorded as failures in
the response to the client.
See Client-requested refreshes
for usage in a remote command or form.
import{requested}from'$app/server';for(const{arg,query}ofrequested(getPost,5)){// `arg` is the validated argument; `query` is bound to the client's// cache key. It's safe to throw away this promise -- SvelteKit will// await it and forward any errors to the client.voidquery.refresh();}
As a shorthand for the above, you can also call refreshAll on the result:
Hint: This schema removes unknown entries. The output will only include the
entries you specify. To include unknown entries, use looseObject. To
return an issue for unknown entries, use strictObject. To include and
validate unknown entries, use objectWithRest.
Hint: This schema removes unknown entries. The output will only include the
entries you specify. To include unknown entries, use looseObject. To
return an issue for unknown entries, use strictObject. To include and
validate unknown entries, use objectWithRest.
entries
The entries schema.
An object schema.
({/* ... */}),async(data(parameter)data:{})=>{ // form logic goes here...for(const{queryconstquery:RemoteQuery<void>reference}ofrequested(alias)requested<{filter:string;},void,{filter:string;}>(query:RemoteQueryFunction<{filter:string;},void,{filter:string;}>,limit:number):QueryRequestedResult<{filter:string;},void>(+1overload)importrequested
Inside a remote command or form callback, returns an iterable
of { arg, query } entries for the query instances the client asked to refresh, up tothe supplied limit. Each query is a RemoteQuery bound to the originalclient-side cache key, so refresh() / set() propagate correctly even whenthe query's schema transforms the input. arg is the validated argument,i.e. the value after the schema has run (so InferOutput<Schema> for queriesdeclared with a Standard Schema).
Arguments that fail validation or exceed limit are recorded as failures in
import{requested}from'$app/server';for(const{arg,query}ofrequested(getPost,5)){// `arg` is the validated argument; `query` is bound to the client's// cache key. It's safe to throw away this promise -- SvelteKit will// await it and forward any errors to the client.voidquery.refresh();}
As a shorthand for the above, you can also call refreshAll on the result:
On the client, this function will re-fetch the query from the server.
On the server, this can be called in the context of a command or form and the refreshed data will accompany the action response back to the client.
This prevents SvelteKit needing to refresh all queries on the page in a second server round-trip.();} // Redirect to the newly created pageredirect(alias)redirect(status:300|301|302|303|304|305|306|307|308|({}&number),location:string|URL):neverimportredirect
Redirect a request. When called during request handling, SvelteKit will return a redirect response.
Make sure you're not catching the thrown redirect, which would prevent SvelteKit from handling it.
Most common status codes:
303 See Other: redirect as a GET request (often used after a form POST request)
307 Temporary Redirect: redirect will keep the request method
308 Permanent Redirect: redirect will keep the request method, SEO will be transferred to the new page
{Redirect} This error instructs SvelteKit to redirect to the specified location.
{Error} If the provided status is invalid or the location cannot be used as a header value.
(303,`/blog/${slugconstslug:""}`);});
requested gives you access to the queries the client requested to refresh. Each entry is an { arg, query } object: arg is the value the query’s implementation function received — i.e. the argument after the schema has validated and (where applicable) transformed it — and query is a RemoteQuery already bound to the client’s original cache key, so calling query.refresh() / query.set(...) updates the correct client instance. If parsing an argument fails, that query will error, but the entire command will not fail. requested’s second parameter, limit, is the maximum number of items it will return. Any refresh requests beyond this limit will fail.
limit is required because the list of refresh requests is controlled by the client — each entry causes the server to validate an argument and usually re-fetch data, so an unbounded list is a denial-of-service risk. Choose a limit that reflects the worst case you’re willing to handle per request. You can pass Infinity if you have explicitly decided to accept any number of refreshes, but it is not recommended.
Additionally, requested allows a simple shorthand when all you want to do is refresh the requested query instances:
// this is the same as looping over the result and calling `void query.refresh()`.awaitrequested(alias)requested<any,any,any>(query:RemoteQueryFunction<any,any,any>,limit:number):QueryRequestedResult<any,any>(+1overload)importrequested
Inside a remote command or form callback, returns an iterable
of { arg, query } entries for the query instances the client asked to refresh, up to
the supplied limit. Each query is a RemoteQuery bound to the original
client-side cache key, so refresh() / set() propagate correctly even when
the query's schema transforms the input. arg is the validated argument,
i.e. the value after the schema has run (so InferOutput<Schema> for queries
declared with a Standard Schema).
Arguments that fail validation or exceed limit are recorded as failures in
the response to the client.
See Client-requested refreshes
for usage in a remote command or form.
import{requested}from'$app/server';for(const{arg,query}ofrequested(getPost,5)){// `arg` is the validated argument; `query` is bound to the client's// cache key. It's safe to throw away this promise -- SvelteKit will// await it and forward any errors to the client.voidquery.refresh();}
As a shorthand for the above, you can also call refreshAll on the result:
Why does the command have to name every query it’s willing to refresh? Two reasons:
Bundle size. If a command could implicitly refresh any query in your app, SvelteKit would have to include every query’s code in the command’s server bundle, because it can’t know ahead of time which ones will be called.
Denial-of-service. Any malicious user can inspect their network tab to discover which queries your app uses, then POST a command with a client-supplied list of thousands of refreshes. The only defence is for the server handler to declare which queries it is willing to refresh — and in what quantity (hence the required limit).
prerender
The prerender function is similar to query, except that it will be invoked at build time to prerender the result. Use this for data that changes at most once per redeployment.
reference(async()=>{constpostsconstposts:any[]=awaitdb(alias)module"$lib/server/database"importdb.sqlfunctionsql(strings:TemplateStringsArray,...values:any[]):Promise<any[]>`
SELECT title, slug
FROM post
ORDER BY published_at
DESC
`;returnpostsconstposts:any[];});
You can use prerender functions on pages that are otherwise dynamic, allowing for partial prerendering of your data. This results in very fast navigation, since prerendered data can live on a CDN along with your other static assets.
In the browser, prerendered data is saved using the Cache API. This cache survives page reloads, and will be cleared when the user first visits a new deployment of your app.
Prerender arguments
As with queries, prerender functions can accept an argument, which should be validated with a Standard Schema:
Throws an error with a HTTP status code and an optional message.
When called during request handling, this will cause SvelteKit to
return an error response without invoking handleError.
Make sure you're not catching the thrown error, which would prevent SvelteKit from handling it.
(),async(slug(parameter)slug:string)=>{const[postconstpost:any]=awaitdb(alias)module"$lib/server/database"importdb.sqlfunctionsql(strings:TemplateStringsArray,...values:any[]):Promise<any[]>`
SELECT * FROM post
WHERE slug =${slug(parameter)slug:string}`;if(!postconstpost:any)error(alias)error(status:number,body?:{message:string;}extendsApp.Error?App.Error|string|undefined:never):never(+1overload)importerror
Throws an error with a HTTP status code and an optional message.
When called during request handling, this will cause SvelteKit to
return an error response without invoking handleError.
Make sure you're not catching the thrown error, which would prevent SvelteKit from handling it.
Any calls to getPost(...) found by SvelteKit’s crawler while prerendering pages will be saved automatically, but you can also specify which values it should be called with using the inputs option:
By default, prerender functions are excluded from your server bundle, which means that you cannot call them with any arguments that were not prerendered. You can set dynamic: true to change this behaviour:
As long as you’re not passing invalid data to your remote functions, there are only two reasons why the argument passed to a command, query or prerender function would fail validation:
the function signature changed between deployments, and some users are currently on an older version of your app
someone is trying to attack your site by poking your exposed endpoints with bad data
In the second case, we don’t want to give the attacker any help, so SvelteKit will generate a generic 400 Bad Request response. You can control the message by implementing the handleValidationError server hook, which, like handleError, must return an App.Error (which defaults to { message: string }):
reference('unchecked',async({id(parameter)id:string}:{id(property)id:string:string})=>{ // the shape might not actually be what TypeScript thinks // since bad actors might call this function with other arguments});
Using getRequestEvent
Inside query, form and command you can use getRequestEvent to get the current RequestEvent object. This makes it easy to build abstractions for interacting with cookies, for example:
reference(async()=>{constuserconstuser:User|null=awaitgetUserconstgetUser:(arg:void)=>RemoteQuery<User|null>();returnuserconstuser:User|null&&{name(property)name:string:userconstuser:User.name(property)User.name:string,avatar(property)avatar:string:userconstuser:User.avatar(property)User.avatar:string};});// this query could be called from multiple places, but// the function will only run once per requestconstgetUserconstgetUser:RemoteQueryFunction<void,User|null>=query(alias)query<User|null>(fn:()=>MaybePromise<User|null>):RemoteQueryFunction<void,User|null>(+2overloads)importquery
Creates a remote query. When called from the browser, the function will be invoked on the server via a fetch call.
Gets a cookie that was previously set with cookies.set, or from the request headers.
name
the name of the cookie
opts
the options, passed directly to cookie.parse. See documentation here
('session_id'));});
Note that some properties of RequestEvent are different inside remote functions:
you cannot set headers (other than writing cookies, and then only inside form and command functions)
route, params and url relate to the page the remote function was called from, not the URL of the endpoint SvelteKit creates for the remote function. Never use them to determine whether or not a user is authorized to access certain data, as these values are part of the request which could be manipulated. Queries are also not re-run when the user navigates (unless the argument to the query changes as a result of navigation), and so you should be mindful of how you use these values.
Redirects
Inside query, form and prerender functions it is possible to use the redirect(...) function. It is not possible inside command functions, as you should avoid redirecting here. (If you absolutely have to, you can return a { redirect: location } object and deal with it in the client.)