```js // @noErrors import { command, form, getRequestEvent, prerender, query, read, 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](/docs/kit/remote-functions#command) for full documentation.
```dts function command( fn: () => MaybePromise ): RemoteCommand; ```
```dts function command( validate: 'unchecked', fn: (arg: Input) => MaybePromise ): RemoteCommand; ```
```dts function command( validate: Schema, fn: ( arg: StandardSchemaV1.InferOutput ) => MaybePromise ): RemoteCommand< StandardSchemaV1.InferInput, Output >; ```
## form
Available since 2.27
Creates a form object that can be spread onto a `
` element. See [Remote functions](/docs/kit/remote-functions#form) for full documentation.
```dts function form( fn: () => MaybePromise ): RemoteForm; ```
```dts function form( validate: 'unchecked', fn: ( data: Input, issue: InvalidField ) => MaybePromise ): RemoteForm; ```
```dts function form< Schema extends StandardSchemaV1< RemoteFormInput, Record >, Output >( validate: true extends HasNonOptionalBoolean< StandardSchemaV1.InferInput > ? '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, issue: InvalidField> ) => MaybePromise ): RemoteForm, 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`](https://nodejs.org/api/async_context.html#class-asynclocalstorage), this must be called synchronously (i.e. not after an `await`).
```dts 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](/docs/kit/remote-functions#prerender) for full documentation.
```dts function prerender( fn: () => MaybePromise, options?: | { inputs?: RemotePrerenderInputsGenerator; dynamic?: boolean; } | undefined ): RemotePrerenderFunction; ```
```dts function prerender( validate: 'unchecked', fn: (arg: Input) => MaybePromise, options?: | { inputs?: RemotePrerenderInputsGenerator; dynamic?: boolean; } | undefined ): RemotePrerenderFunction; ```
```dts function prerender( schema: Schema, fn: ( arg: StandardSchemaV1.InferOutput ) => MaybePromise, options?: | { inputs?: RemotePrerenderInputsGenerator< StandardSchemaV1.InferInput >; dynamic?: boolean; } | undefined ): RemotePrerenderFunction< StandardSchemaV1.InferInput, 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](/docs/kit/remote-functions#query) for full documentation.
```dts function query( fn: () => MaybePromise ): RemoteQueryFunction; ```
```dts function query( validate: 'unchecked', fn: (arg: Input) => MaybePromise ): RemoteQueryFunction; ```
```dts function query( schema: Schema, fn: ( arg: StandardSchemaV1.InferOutput ) => MaybePromise ): RemoteQueryFunction< StandardSchemaV1.InferInput, Output, StandardSchemaV1.InferOutput >; ```
## read
Available since 2.4.0
Read the contents of an imported asset from the filesystem ```js // @errors: 7031 import { read } from '$app/server'; import somefile from './somefile.txt'; const asset = read(somefile); const text = await asset.text(); ```
```dts 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` 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](/docs/kit/remote-functions#Single-flight-mutations-Client-requested-refreshes) for usage in a remote `command` or `form`. ```ts import { requested } from '$app/server'; for (const { arg, query } of 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 query.refresh(); } ``` As a shorthand for the above, you can also call `refreshAll` on the result: ```ts import { requested } from '$app/server'; await requested(getPost, 5).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`.
```dts function requested( query: RemoteQueryFunction, limit: number ): QueryRequestedResult; ```
```dts function requested( query: RemoteLiveQueryFunction, limit: number ): LiveQueryRequestedResult; ```
## Cookies
```dts interface Cookies {/*…*/} ```
```dts get: (name: string, opts?: import('cookie').ParseOptions) => string | undefined; ```
- `name` the name of the cookie - `opts` the options, passed directly to `cookie.parseCookie`. See documentation [here](https://github.com/jshttp/cookie?tab=readme-ov-file#cookieparsecookiestr-options)
Gets a cookie that was previously set with `cookies.set`, or from the request headers.
```dts getAll: (opts?: import('cookie').ParseOptions) => Array<{ name: string; value: string }>; ```
- `opts` the options, passed directly to `cookie.parseCookie`. See documentation [here](https://github.com/jshttp/cookie?tab=readme-ov-file#cookieparsecookiestr-options)
Gets all cookies that were previously set with `cookies.set`, or from the request headers.
```dts set: (name: string, value: string, opts: import('cookie').SerializeOptions) => void; ```
- `name` the name of the cookie - `value` the cookie value - `opts` the options passed to `cookie.stringifySetCookie` with the SvelteKit defaults described above. See documentation [here](https://github.com/jshttp/cookie?tab=readme-ov-file#cookiestringifysetcookiesetcookieobj-options)
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.
```dts delete: (name: string, opts: import('cookie').SerializeOptions) => void; ```
- `name` the name of the cookie - `opts` the options passed to `cookie.stringifySetCookie` with the SvelteKit defaults described above. See documentation [here](https://github.com/jshttp/cookie?tab=readme-ov-file#cookiestringifysetcookiesetcookieobj-options)
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.
```dts parse: typeof import('cookie').parseSetCookie; ```
Parses a single `Set-Cookie` header. This allows you to apply cookies received from an external source: ```js // @errors: 7031 import { getRequestEvent } from '$app/server'; export async function GET() { const { cookies } = getRequestEvent(); const response = await fetch('...'); for (const str of response.headers.getSetCookie()) { const { name, value, ...options } = cookies.parse(str); cookies.set(name, value, { ...options, 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.
```dts serialize: (name: string, value: string, opts: import('cookie').SerializeOptions) => string; ```
- `name` the name of the cookie - `value` the cookie value - `opts` the options passed to `cookie.stringifySetCookie` with the SvelteKit defaults described above. See documentation [here](https://github.com/jshttp/cookie?tab=readme-ov-file#cookiestringifysetcookiesetcookieobj-options)
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
```dts interface RequestEvent< Params extends AppLayoutParams<'/'> = AppLayoutParams<'/'>, RouteId extends AppRouteId | null = AppRouteId | null > {/*…*/} ```
```dts readonly cookies: Cookies; ```
Get or set cookies related to the current request
```dts readonly fetch: typeof fetch; ```
`fetch` is equivalent to the [native `fetch` web API](https://developer.mozilla.org/en-US/docs/Web/API/fetch), with a few additional features: - It can be used to make credentialed requests on the server, as it inherits the `cookie` and `authorization` headers for the page request. - It can make relative requests on the server (ordinarily, `fetch` requires a URL with an origin when used in a server context). - Internal requests (e.g. for `+server.js` routes) 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 `text` and `json` methods of the `Response` object. Note that headers will _not_ be serialized, unless explicitly included via [`filterSerializedResponseHeaders`](/docs/kit/hooks#handle) - 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](/docs/kit/load#Cookies).
```dts readonly getClientAddress: () => string; ```
The client's IP address, set by the adapter.
```dts readonly locals: App.Locals; ```
Contains custom data that was added to the request within the [`server handle hook`](/docs/kit/hooks#handle).
```dts 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.
```dts readonly platform: Readonly | undefined; ```
Additional data made available through the adapter.
```dts readonly request: Request; ```
The original request object.
```dts readonly route: {/*…*/} ```
Info about the current route.
```dts 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.
```dts readonly setHeaders: (headers: Record) => 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: ```js // @errors: 7031 /// file: src/routes/blog/+page.js export async function load({ fetch, setHeaders }) { const url = `https://cms.example.com/articles.json`; const response = await fetch(url); setHeaders({ age: response.headers.get('age'), 'cache-control': response.headers.get('cache-control') }); return response.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`](/docs/kit/$app-server#Cookies) API instead.
```dts 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.
```dts 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.
```dts 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.
```dts readonly tracing: {/*…*/} ```
- available since v2.31.0
Access to spans for tracing. If tracing is not enabled, these spans will do nothing.
```dts enabled: boolean; ```
Whether tracing is enabled.
```dts root: Span; ```
The root span for the request. This span is named `sveltekit.handle.root`.
```dts current: Span; ```
The span associated with the current `handle` hook, `load` function, or form action.
```dts 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
```dts 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( validate: 'unchecked', fn: ( args: Input[] ) => MaybePromise<(arg: Input, idx: number) => Output> ): RemoteQueryFunction; /** * 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: Schema, fn: ( args: StandardSchemaV1.InferOutput[] ) => MaybePromise< ( arg: StandardSchemaV1.InferOutput, idx: number ) => Output > ): RemoteQueryFunction< StandardSchemaV1.InferInput, Output, StandardSchemaV1.InferOutput >; /** * 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( fn: ( arg: void ) => RemoteLiveQueryUserFunctionReturnType ): RemoteLiveQueryFunction; function live( validate: 'unchecked', fn: ( arg: Input ) => RemoteLiveQueryUserFunctionReturnType ): RemoteLiveQueryFunction; function live( schema: Schema, fn: ( arg: StandardSchemaV1.InferOutput ) => RemoteLiveQueryUserFunctionReturnType ): RemoteLiveQueryFunction< StandardSchemaV1.InferInput, Output, StandardSchemaV1.InferOutput >; } ```