$app/server
import {
function command<Output>(fn: () => MaybePromise<Output>): RemoteCommand<void, Output> (+2 overloads)Creates a remote command. When called from the browser, the function will be invoked on the server via a fetch call.
See Remote functions for full documentation.
command,
function form<Output>(fn: () => MaybePromise<Output>): RemoteForm<void, Output> (+2 overloads)Creates a form object that can be spread onto a <form> element.
See Remote functions for full documentation.
form,
function getRequestEvent(): RequestEventReturns the current RequestEvent. Can be used inside server hooks, server load functions, actions, and endpoints (and functions called by them).
In environments without AsyncLocalStorage, this must be called synchronously (i.e. not after an await).
getRequestEvent,
function prerender<Output>(fn: () => MaybePromise<Output>, options?: {
inputs?: RemotePrerenderInputsGenerator<void>;
dynamic?: boolean;
} | undefined): RemotePrerenderFunction<void, Output> (+2 overloads)
Creates a remote prerender function. When called from the browser, the function will be invoked on the server via a fetch call.
See Remote functions for full documentation.
prerender,
function query<Output>(fn: () => MaybePromise<Output>): RemoteQueryFunction<void, Output> (+2 overloads)Creates a remote query. When called from the browser, the function will be invoked on the server via a fetch call.
See Remote functions for full documentation.
query,
function read(asset: string): ResponseRead the contents of an imported asset from the filesystem
read,
function requested<Input, Output, Validated = Input>(query: RemoteQueryFunction<Input, Output, Validated>, limit: number): QueryRequestedResult<Validated, Output> (+1 overload)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.
requested
} from '$app/server';command
Available since 2.27
Creates a remote command. When called from the browser, the function will be invoked on the server via a fetch call.
See Remote functions for full documentation.
function command<Output>(
fn: () => MaybePromise<Output>
): RemoteCommand<void, Output>;function command<Input, Output>(
validate: 'unchecked',
fn: (arg: Input) => MaybePromise<Output>
): RemoteCommand<Input, Output>;function command<Schema extends StandardSchemaV1, Output>(
validate: Schema,
fn: (
arg: StandardSchemaV1.InferOutput<Schema>
) => MaybePromise<Output>
): RemoteCommand<
StandardSchemaV1.InferInput<Schema>,
Output
>;form
Available since 2.27
Creates a form object that can be spread onto a <form> element.
See Remote functions for full documentation.
function form<Output>(
fn: () => MaybePromise<Output>
): RemoteForm<void, Output>;function form<Input extends RemoteFormInput, Output>(
validate: 'unchecked',
fn: (
data: Input,
issue: InvalidField<Input>
) => MaybePromise<Output>
): RemoteForm<Input, Output>;function form<
Schema extends StandardSchemaV1<
RemoteFormInput,
Record<string, any>
>,
Output
>(
validate: true extends HasNonOptionalBoolean<
StandardSchemaV1.InferInput<Schema>
>
? 'Error: All booleans in form schemas must be optional (e.g. `v.optional(v.boolean(), false)`) because checkbox inputs do not send a false value when unchecked.'
: Schema,
fn: (
data: StandardSchemaV1.InferOutput<Schema>,
issue: InvalidField<StandardSchemaV1.InferInput<Schema>>
) => MaybePromise<Output>
): RemoteForm<StandardSchemaV1.InferInput<Schema>, Output>;getRequestEvent
Available since 2.20.0
Returns the current RequestEvent. Can be used inside server hooks, server load functions, actions, and endpoints (and functions called by them).
In environments without AsyncLocalStorage, this must be called synchronously (i.e. not after an await).
function getRequestEvent(): RequestEvent;prerender
Available since 2.27
Creates a remote prerender function. When called from the browser, the function will be invoked on the server via a fetch call.
See Remote functions for full documentation.
function prerender<Output>(
fn: () => MaybePromise<Output>,
options?:
| {
inputs?: RemotePrerenderInputsGenerator<void>;
dynamic?: boolean;
}
| undefined
): RemotePrerenderFunction<void, Output>;function prerender<Input, Output>(
validate: 'unchecked',
fn: (arg: Input) => MaybePromise<Output>,
options?:
| {
inputs?: RemotePrerenderInputsGenerator<Input>;
dynamic?: boolean;
}
| undefined
): RemotePrerenderFunction<Input, Output>;function prerender<Schema extends StandardSchemaV1, Output>(
schema: Schema,
fn: (
arg: StandardSchemaV1.InferOutput<Schema>
) => MaybePromise<Output>,
options?:
| {
inputs?: RemotePrerenderInputsGenerator<
StandardSchemaV1.InferInput<Schema>
>;
dynamic?: boolean;
}
| undefined
): RemotePrerenderFunction<
StandardSchemaV1.InferInput<Schema>,
Output
>;query
Available since 2.27
Creates a remote query. When called from the browser, the function will be invoked on the server via a fetch call.
See Remote functions for full documentation.
function query<Output>(
fn: () => MaybePromise<Output>
): RemoteQueryFunction<void, Output>;function query<Input, Output>(
validate: 'unchecked',
fn: (arg: Input) => MaybePromise<Output>
): RemoteQueryFunction<Input, Output>;function query<Schema extends StandardSchemaV1, Output>(
schema: Schema,
fn: (
arg: StandardSchemaV1.InferOutput<Schema>
) => MaybePromise<Output>
): RemoteQueryFunction<
StandardSchemaV1.InferInput<Schema>,
Output,
StandardSchemaV1.InferOutput<Schema>
>;read
Available since 2.4.0
Read the contents of an imported asset from the filesystem
import { function read(asset: string): ResponseRead the contents of an imported asset from the filesystem
read } from '$app/server';
import const somefile: stringsomefile from './somefile.txt';
const const asset: Responseasset = function read(asset: string): ResponseRead the contents of an imported asset from the filesystem
read(const somefile: stringsomefile);
const const text: stringtext = await const asset: Responseasset.Body.text(): Promise<string>text();function read(asset: string): Response;requested
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 { function requested<Input, Output, Validated = Input>(query: RemoteQueryFunction<Input, Output, Validated>, limit: number): QueryRequestedResult<Validated, Output> (+1 overload)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.
requested } from '$app/server';
for (const { const arg: unknownarg, const query: RemoteQuery<unknown>query } of requested<unknown, unknown, unknown>(query: RemoteQueryFunction<unknown, unknown, unknown>, limit: number): QueryRequestedResult<unknown, unknown> (+1 overload)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.
requested(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.
void const query: RemoteQuery<unknown>query.function 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.
refresh();
}As a shorthand for the above, you can also call refreshAll on the result:
import { function requested<Input, Output, Validated = Input>(query: RemoteQueryFunction<Input, Output, Validated>, limit: number): QueryRequestedResult<Validated, Output> (+1 overload)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.
requested } from '$app/server';
await requested<unknown, unknown, unknown>(query: RemoteQueryFunction<unknown, unknown, unknown>, limit: number): QueryRequestedResult<unknown, unknown> (+1 overload)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.
requested(getPost, 5).refreshAll: () => Promise<void>Call refresh on all queries selected by this requested invocation.
This is identical to:
import { requested } from '$app/server';
for await (const { query } of requested(getPost, ...)) {
void query.refresh();
}
refreshAll();Works with query.batch as well — refreshes for individual entries are
collected into a single batched call.
For live queries, the same applies, but with reconnect and reconnectAll.
function requested<Input, Output, Validated = Input>(
query: RemoteQueryFunction<Input, Output, Validated>,
limit: number
): QueryRequestedResult<Validated, Output>;function requested<Input, Output, Validated = Input>(
query: RemoteLiveQueryFunction<Input, Output, Validated>,
limit: number
): LiveQueryRequestedResult<Validated, Output>;Cookies
interface Cookies {…}get: (name: string, opts?: import('cookie').ParseOptions) => string | undefined;namethe name of the cookieoptsthe options, passed directly tocookie.parseCookie. See documentation here
Gets a cookie that was previously set with cookies.set, or from the request headers.
getAll: (opts?: import('cookie').ParseOptions) => Array<{ name: string; value: string }>;optsthe options, passed directly tocookie.parseCookie. See documentation here
Gets all cookies that were previously set with cookies.set, or from the request headers.
set: (name: string, value: string, opts: import('cookie').SerializeOptions) => void;namethe name of the cookievaluethe cookie valueoptsthe options passed tocookie.stringifySetCookiewith the SvelteKit defaults described above. See documentation here
Sets a cookie. This will add a set-cookie header to the response, but also make the cookie available via cookies.get or cookies.getAll during the current request.
The httpOnly is true by default, as is secure, except during development, when it defaults to false. These must be explicitly disabled if you want cookies to be readable by client-side JavaScript and/or transmitted over HTTP.
The path option is '/' by default. You can use relative paths, or set path: '' to make the cookie only available on the current path and its children.
delete: (name: string, opts: import('cookie').SerializeOptions) => void;namethe name of the cookieoptsthe options passed tocookie.stringifySetCookiewith the SvelteKit defaults described above. See documentation here
Deletes a cookie by setting its value to an empty string and setting the expiry date in the past.
The httpOnly is true by default, as is secure, except during development, when it defaults to false. These must be explicitly disabled if you want cookies to be readable by client-side JavaScript and/or transmitted over HTTP.
The path option is '/' by default. You can use relative paths, or set path: '' to make the cookie only available on the current path and its children.
parse: typeof import('cookie').parseSetCookie;Parses a single Set-Cookie header. This allows you to apply cookies received from an external source:
import { function getRequestEvent(): RequestEventReturns the current RequestEvent. Can be used inside server hooks, server load functions, actions, and endpoints (and functions called by them).
In environments without AsyncLocalStorage, this must be called synchronously (i.e. not after an await).
getRequestEvent } from '$app/server';
export async function function GET(): Promise<void>GET() {
const { const cookies: CookiesGet or set cookies related to the current request
cookies } = function getRequestEvent(): RequestEventReturns the current RequestEvent. Can be used inside server hooks, server load functions, actions, and endpoints (and functions called by them).
In environments without AsyncLocalStorage, this must be called synchronously (i.e. not after an await).
getRequestEvent();
const const response: Responseresponse = await function fetch(input: string | URL | Request, init?: RequestInit): Promise<Response> (+1 overload)fetch('...');
for (const const str: stringstr of const response: Responseresponse.Response.headers: HeadersThe headers read-only property of the Response interface contains the Headers object associated with the response.
headers.Headers.getSetCookie(): string[]The getSetCookie() method of the Headers interface returns an array containing the values of all Set-Cookie headers associated with a response. This allows Headers objects to handle having multiple Set-Cookie headers, which wasn't possible prior to its implementation.
getSetCookie()) {
const { const name: stringSpecifies the name of the cookie.
name, const value: string | undefinedSpecifies the string to be the value for the cookie.
value, ...const options: {
maxAge?: number;
expires?: Date;
domain?: string;
path?: string;
httpOnly?: boolean;
secure?: boolean;
partitioned?: boolean;
priority?: "low" | "medium" | "high";
sameSite?: boolean | "lax" | "strict" | "none";
}
options } = const cookies: CookiesGet or set cookies related to the current request
cookies.Cookies.parse: (str: string, options?: ParseOptions) => SetCookieDeserialize a Set-Cookie header into an object.
parseSetCookie('foo=bar; HttpOnly')
=> { name: 'foo', value: 'bar', httpOnly: true }
parse(const str: stringstr);
const cookies: CookiesGet or set cookies related to the current request
cookies.Cookies.set: (name: string, value: string, opts: SerializeOptions) => voidSets a cookie. This will add a set-cookie header to the response, but also make the cookie available via cookies.get or cookies.getAll during the current request.
The httpOnly is true by default, as is secure, except during development, when it defaults to false. These must be explicitly disabled if you want cookies to be readable by client-side JavaScript and/or transmitted over HTTP.
The path option is '/' by default. You can use relative paths, or set path: '' to make the cookie only available on the current path and its children.
set(const name: stringSpecifies the name of the cookie.
name, const value: string | undefinedSpecifies the string to be the value for the cookie.
value, { ...const options: {
maxAge?: number;
expires?: Date;
domain?: string;
path?: string;
httpOnly?: boolean;
secure?: boolean;
partitioned?: boolean;
priority?: "low" | "medium" | "high";
sameSite?: boolean | "lax" | "strict" | "none";
}
options, path?: string | undefinedSpecifies the value for the Path Set-Cookie attribute.
When no path is set, the path is considered the "default path".
path: '/' });
}
// ...
}Note the use of headers.getSetCookie(), which returns an array of cookie headers, not headers.get('set-cookie') which returns a single comma-separated string.
serialize: (name: string, value: string, opts: import('cookie').SerializeOptions) => string;namethe name of the cookievaluethe cookie valueoptsthe options passed tocookie.stringifySetCookiewith the SvelteKit defaults described above. See documentation here
Serialize a cookie name-value pair into a Set-Cookie header string, but don't apply it to the response.
The httpOnly is true by default, as is secure, except during development, when it defaults to false. These must be explicitly disabled if you want cookies to be readable by client-side JavaScript and/or transmitted over HTTP.
The path option is '/' by default. You can use relative paths, or set path: '' to make the cookie only available on the current path and its children.
RequestEvent
interface RequestEvent<
Params extends AppLayoutParams<'/'> =
AppLayoutParams<'/'>,
RouteId extends AppRouteId | null = AppRouteId | null
> {…}readonly cookies: Cookies;Get or set cookies related to the current request
readonly fetch: typeof fetch;fetch is equivalent to the native fetch web API, with a few additional features:
- It can be used to make credentialed requests on the server, as it inherits the
cookieandauthorizationheaders for the page request. - It can make relative requests on the server (ordinarily,
fetchrequires a URL with an origin when used in a server context). - Internal requests (e.g. for
+server.jsroutes) go directly to the handler function when running on the server, without the overhead of an HTTP call. - During server-side rendering, the response will be captured and inlined into the rendered HTML by hooking into the
textandjsonmethods of theResponseobject. Note that headers will not be serialized, unless explicitly included viafilterSerializedResponseHeaders - During hydration, the response will be read from the HTML, guaranteeing consistency and preventing an additional network request.
You can learn more about making credentialed requests with cookies here.
readonly getClientAddress: () => string;The client's IP address, set by the adapter.
readonly locals: App.Locals;Contains custom data that was added to the request within the server handle hook.
readonly params: Params;The parameters of the current route - e.g. for a route like /blog/[slug], a { slug: string } object.
Inside query functions (including query.batch and query.live), accessing this property throws an error.
Pass values from the page as arguments to the query instead. Inside form and command functions it relates to the page
the remote function was called from, not the URL of the endpoint SvelteKit creates for the remote function. Never use it
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.
readonly platform: Readonly<App.Platform> | undefined;Additional data made available through the adapter.
readonly request: Request;The original request object.
readonly route: {…}Info about the current route.
id: RouteId;The ID of the current route - e.g. for src/routes/blog/[slug], it would be /blog/[slug]. It is null when no route is matched.
Inside query functions (including query.batch and query.live), accessing this property throws an error.
Pass values from the page as arguments to the query instead. Inside form and command functions it relates to the page
the remote function was called from, not the URL of the endpoint SvelteKit creates for the remote function. Never use it
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.
readonly setHeaders: (headers: Record<string, string>) => void;If you need to set headers for the response, you can do so using the this method. This is useful if you want the page to be cached, for example:
export async function function load({ fetch, setHeaders }: {
fetch: any;
setHeaders: any;
}): Promise<any>
load({ fetch, setHeaders }) {
const const url: "https://cms.example.com/articles.json"url = `https://cms.example.com/articles.json`;
const const response: anyresponse = await fetch: anyfetch(const url: "https://cms.example.com/articles.json"url);
setHeaders: anysetHeaders({
age: anyage: const response: anyresponse.headers.get('age'),
'cache-control': const response: anyresponse.headers.get('cache-control')
});
return const response: anyresponse.json();
}Setting the same header multiple times (even in separate load functions) is an error — you can only set a given header once.
You cannot add a set-cookie header with setHeaders — use the cookies API instead.
readonly url: URL;The requested URL.
Inside query functions (including query.batch and query.live), accessing this property throws an error.
Pass values from the page as arguments to the query instead. Inside form and command functions it relates to the page
the remote function was called from, not the URL of the endpoint SvelteKit creates for the remote function. Never use it
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.
readonly isDataRequest: boolean;true if the request comes from the client asking for +page/layout.server.js data. The url property will be stripped of the internal information
related to the data request in this case. Use this property instead if the distinction is important to you.
readonly isSubRequest: boolean;true for +server.js calls coming from SvelteKit without the overhead of actually making an HTTP request. This happens when you make same-origin fetch requests on the server.
readonly tracing: {…}- available since v2.31.0
Access to spans for tracing. If tracing is not enabled, these spans will do nothing.
enabled: boolean;Whether tracing is enabled.
root: Span;The root span for the request. This span is named sveltekit.handle.root.
current: Span;The span associated with the current handle hook, load function, or form action.
readonly isRemoteRequest: boolean;true if the request comes from the client via a remote function. The url property will be stripped of the internal information
related to the data request in this case. Use this property instead if the distinction is important to you.
query
namespace query {
/**
* Creates a batch query function that collects multiple calls and executes them in a single request
*
* See [Remote functions](https://svelte.dev/docs/kit/remote-functions#query.batch) for full documentation.
*
* @since 2.35
*/
function batch<Input, Output>(
validate: 'unchecked',
fn: (
args: Input[]
) => MaybePromise<(arg: Input, idx: number) => Output>
): RemoteQueryFunction<Input, Output>;
/**
* Creates a batch query function that collects multiple calls and executes them in a single request
*
* See [Remote functions](https://svelte.dev/docs/kit/remote-functions#query.batch) for full documentation.
*
* @since 2.35
*/
function batch<Schema extends StandardSchemaV1, Output>(
schema: Schema,
fn: (
args: StandardSchemaV1.InferOutput<Schema>[]
) => MaybePromise<
(
arg: StandardSchemaV1.InferOutput<Schema>,
idx: number
) => Output
>
): RemoteQueryFunction<
StandardSchemaV1.InferInput<Schema>,
Output,
StandardSchemaV1.InferOutput<Schema>
>;
/**
* Creates a live remote query. When called from the browser, the function will be invoked on the server via a streaming `fetch` call.
*
* See [Remote functions](https://svelte.dev/docs/kit/remote-functions#query.live) for full documentation.
*
* */
function live<Output>(
fn: (
arg: void
) => RemoteLiveQueryUserFunctionReturnType<Output>
): RemoteLiveQueryFunction<void, Output>;
function live<Input, Output>(
validate: 'unchecked',
fn: (
arg: Input
) => RemoteLiveQueryUserFunctionReturnType<Output>
): RemoteLiveQueryFunction<Input, Output>;
function live<Schema extends StandardSchemaV1, Output>(
schema: Schema,
fn: (
arg: StandardSchemaV1.InferOutput<Schema>
) => RemoteLiveQueryUserFunctionReturnType<Output>
): RemoteLiveQueryFunction<
StandardSchemaV1.InferInput<Schema>,
Output,
StandardSchemaV1.InferOutput<Schema>
>;
}Edit this page on GitHub llms.txt