## error
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; the error will be passed to `handleError` as an _expected_ error.
Make sure you're not catching the thrown error, which would prevent SvelteKit from handling it.
## fail
Create an `ActionFailure` object. Call when form submission fails.
```dts
function fail(status: number): ActionFailure;
```
```dts
function fail(
status: number,
data: T
): ActionFailure;
```
## invalid
Available since 2.47.3
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.
```ts
import { invalid } from '@sveltejs/kit';
import { form } from '$app/server';
import { tryLogin } from '#lib/server/auth';
import * as v from 'valibot';
export const login = form(
v.object({ name: v.string(), _password: v.string() }),
async ({ name, _password }) => {
const success = tryLogin(name, _password);
if (!success) {
invalid('Incorrect username or password');
}
// ...
}
);
```
```dts
function invalid(
...issues: (StandardSchemaV1.Issue | string)[]
): never;
```
## isActionFailure
Checks whether this is an action failure thrown by `fail`.
```dts
function isActionFailure(e: unknown): e is ActionFailure;
```
## isHttpError
Checks whether this is an error thrown by `error`.
```dts
function isHttpError(
e: unknown,
status?: T
): e is HttpError & {
status: T extends undefined ? never : T;
};
```
## isRedirect
Checks whether this is a redirect thrown by `redirect`.
```dts
function isRedirect(e: unknown): e is Redirect;
```
## isValidationError
Available since 2.47.3
Checks whether this is an validation error thrown by `invalid`.
```dts
function isValidationError(e: unknown): e is ActionFailure;
```
## json
use `Response.json`
Create a JSON `Response` object from the supplied data.
```dts
function json(data: any, init?: ResponseInit): Response;
```
## normalizeUrl
Available since 2.18.0
Strips possible SvelteKit-internal suffixes and trailing slashes from the URL pathname.
Returns the normalized URL as well as a method for adding the potential suffix back
based on a new pathname (possibly including search) or URL.
```js
// @errors: 7031
import { normalizeUrl } from '@sveltejs/kit';
const { url, denormalize } = normalizeUrl('/blog/post/__data.json');
console.log(url.pathname); // /blog/post
console.log(denormalize('/blog/post/a')); // /blog/post/a/__data.json
```
## redirect
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
[See all redirect status codes](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#redirection_messages)
Create a `Response` object from the supplied body.
```dts
function text(body: string, init?: ResponseInit): Response;
```
## Action
Shape of a form action method that is part of `export const actions = {...}` in `+page.server.js`.
See [form actions](/docs/kit/form-actions) for more information.
## Adapter
[Adapters](/docs/kit/adapters) are responsible for taking the production build and turning it into something that can be deployed to a platform of your choosing.
```dts
interface Adapter {/*…*/}
```
```dts
name: string;
```
The name of the adapter, using for logging. Will typically correspond to the package name.
- `details.config` The merged adapter-specific route config exported from the route with `export const config`
Test support for `read` from `$app/server`.
```dts
instrumentation?: () => boolean;
```
- available since v2.31.0
Test support for `instrumentation.server.js`. To pass, the adapter must support running `instrumentation.server.js` prior to the application code.
```dts
emulate?: () => MaybePromise;
```
Creates an `Emulator`, which allows the adapter to influence the environment
during dev, build and prerendering.
```dts
vite?: {
plugins?: {
/**
* Vite plugins placed before any of SvelteKit's own plugins.
* @since 3.0.0
*/
pre?: Plugin[];
/**
* Vite plugins placed after any of SvelteKit's own plugins.
* @since 3.0.0
*/
post?: Plugin[];
};
};
```
## AwaitedActions
```dts
type AwaitedActions<
T extends Record any>
> = OptionalUnion<
{
[Key in keyof T]: UnpackValidationError<
Awaited>
>;
}[keyof T]
>;
```
## Builder
This object is passed to the `adapt` function of adapters.
It contains various methods and properties that are useful for adapting the app.
```dts
interface Builder {/*…*/}
```
```dts
log: Logger;
```
Print messages to the console. `log.info` and `log.minor` are silent unless Vite's `logLevel` is `info`.
- `from` the source file or directory
- `to` the destination file or directory
- `opts.filter` a function to determine whether a file or directory should be copied
- `opts.replace` a map of strings to replace
- returns an array of files that were copied
- `options` an object containing the following properties:
- `options.entrypoint` the path to the entrypoint to trace.
- `options.instrumentation` the path to the instrumentation file.
- `options.start` the name of the start file. This is what `entrypoint` will be renamed to.
- `options.module` configuration for the resulting entrypoint module.
- `options.module.generateText` a function that receives the relative paths to the instrumentation and start files, and generates the text of the module to be traced. If not provided, the default implementation will be used, which uses top-level await.
- available since v2.31.0
Instrument `entrypoint` with `instrumentation`.
Renames `entrypoint` to `start` and creates a new module at
`entrypoint` which imports `instrumentation` and then dynamically imports `start`. This allows
the module hooks necessary for instrumentation libraries to be loaded prior to any application code.
Caveats:
- "Live exports" will not work. If your adapter uses live exports, your users will need to manually import the server instrumentation on startup.
- If `tla` is `false`, OTEL auto-instrumentation may not work properly. Use it if your environment supports it.
- Use `hasServerInstrumentationFile` to check if the user has a server instrumentation file; if they don't, you shouldn't do this.
- `directory` The directory containing the files to be compressed
- returns an array of the files in `directory` that were compressed
Compress files in `directory` with gzip and brotli, where appropriate. Generates `.gz` and `.br` files alongside the originals.
## CaughtError
The error passed to the [`handleError`](/docs/kit/hooks#handleError) hooks.
Use the `kind` discriminant to distinguish errors from your app (thrown with the
[`error`](/docs/kit/errors#App-errors) helper), errors generated by
SvelteKit itself (such as 404s), validation errors, and unknown errors (thrown by your code,
or code it calls).
```dts
type CaughtError<
Issue extends StandardSchemaV1.Issue =
StandardSchemaV1.Issue
> =
| {
[Kind in keyof CaughtErrorMap]: {
/** Identifies the category and origin of the error */
kind: Kind;
/** The caught error. Its type depends on `kind` */
error: CaughtErrorMap[Kind];
/** Only present for validation errors */
issues?: undefined;
};
}[keyof CaughtErrorMap]
| ValidationCaughtError;
```
## ClientCaughtError
The error passed to the client-side `handleError` hook.
- `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.
- `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.
- `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.
- `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.
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.
- `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.
## DefinedEnvVars
The return type of [`defineEnvVars`](/docs/kit/@sveltejs-kit-env#defineEnvVars).
```dts
type DefinedEnvVars<
T extends Record>
> = {
readonly [K in keyof T]: EnvVarEntry;
};
```
## Emulator
A collection of functions that influence the environment during dev, build and prerendering
A function that is called with the current route `config` and `prerender` option
and returns an `App.Platform` object
## EnvVarConfig
[Environment variables](/docs/kit/environment-variables) can be configured by exporting
a `variables` object from `src/env.ts`, using [`defineEnvVars`](/docs/kit/@sveltejs-kit-env#defineEnvVars).
```dts
interface EnvVarConfig {/*…*/}
```
```dts
public?: boolean;
```
- default `false`
Whether the environment variable can be accessed by client-side code.
- if `true`, it can be imported from `$app/env/public`
- if `false`, it can be imported from `$app/env/private`, which is a [server-only module](/docs/kit/server-only-modules)
```dts
static?: boolean;
```
- default `false`
Whether the value is determined at build time or when the app runs.
- if `true`, the build time value is inlined into the bundle. This enables optimisations like dead-code elimination
- if `false`, the value is read from the environment when the app starts
A [Standard Schema](https://standardschema.dev/) validator that is applied to the value when the app starts.
Alternatively, a function that returns the (possibly transformed) value, or throws an error explaining
the problem. Returning `undefined` is valid, so a function can describe an optional variable.
The validator can output any value — not necessarily a string — but public, non-static values must be
serializable by [devalue](https://github.com/sveltejs/devalue) so that they can be sent to the browser.
If omitted, the value must be set, but may be an empty string.
```dts
description?: string;
```
A description of the variable that will be used for inline documentation on hover.
## Handle
The [`handle`](/docs/kit/hooks#handle) hook runs every time the SvelteKit server receives a [request](/docs/kit/web-standards#Fetch-APIs-Request) and
determines the [response](/docs/kit/web-standards#Fetch-APIs-Response).
It receives an `event` object representing the request and a function called `resolve`, which renders the route and generates a `Response`.
This allows you to modify response headers or bodies, or bypass SvelteKit entirely (for implementing routes programmatically, for example).
## HandleClientError
The client-side [`handleError`](/docs/kit/hooks#handleError) hook runs for every error thrown while navigating, except redirects.
Errors that were already transformed by the server-side hook are not passed to it a second time.
The `kind` property discriminates between _app_ errors (thrown with the [`error`](/docs/kit/errors#App-errors) helper),
_framework_ errors (generated by SvelteKit itself, such as 404s) and _unknown_ errors (thrown by your code, or code it calls).
The hook returns an object matching `App.Error`, in which `status` and `message` are optional — return them only to
override the defaults. Omitted properties are inherited from the caught error: the body passed to `error(...)` for app errors,
the status and safe message for framework errors, and `500`/`'Internal Error'` for unknown errors. Return nothing to
keep the defaults entirely (if you augment `App.Error` with required properties, you must return those).
Make sure that this function _never_ throws an error.
## HandleFetch
The [`handleFetch`](/docs/kit/hooks#handleFetch) hook allows you to modify (or replace) the result of an [`event.fetch`](/docs/kit/load#Making-fetch-requests) call that runs on the server (or during prerendering) inside an endpoint, `load`, `action`, `handle`, `handleError` or `reroute`.
## HandleServerError
The server-side [`handleError`](/docs/kit/hooks#handleError) hook runs for every error thrown while responding to a request, except redirects.
The `kind` property discriminates between _app_ errors (thrown with the [`error`](/docs/kit/errors#App-errors) helper),
_framework_ errors (generated by SvelteKit itself, such as 404s), _validation_ errors (caused by invalid remote function arguments)
and _unknown_ errors (thrown by your code, or code it calls).
The hook returns an object matching `App.Error`, in which `status` and `message` are optional — return them only to
override the defaults. Omitted properties are inherited from the caught error: the body passed to `error(...)` for app errors,
the status and safe message for framework and validation errors, and `500`/`'Internal Error'` for unknown errors. Return nothing to
keep the defaults entirely (if you augment `App.Error` with required properties, you must return those).
Make sure that this function _never_ throws an error.
## HttpError
The object returned by the [`error`](/docs/kit/@sveltejs-kit#error) function.
```dts
interface HttpError {/*…*/}
```
```dts
status: number;
```
The [HTTP status code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#client_error_responses), in the range 400-599.
```dts
body: App.Error;
```
The content of the error.
## InvalidField
A function and proxy object used to imperatively create validation errors in form handlers.
Access properties to create field-specific issues: `issue.fieldName('message')`.
The type structure mirrors the input data structure for type-safe field access.
Call `invalid(issue.foo(...), issue.nested.bar(...))` to throw a validation error.
## KitConfig
See the [configuration reference](/docs/kit/configuration) for details.
## LiveQueryRequestedResult
```dts
type LiveQueryRequestedResult = Iterable<
LiveRequestedEntry
> &
AsyncIterable> & {
/**
* Call `reconnect` on all live queries selected by this `requested` invocation.
* This is identical to:
* ```ts
* import { requested } from '$app/server';
*
* for await (const { query } of requested(liveQuery, ...)) {
* void query.reconnect();
* }
* ```
*/
reconnectAll: () => Promise;
};
```
## LiveRequestedEntry
A single entry yielded by [`requested`](/docs/kit/$app-server#requested)
when called with a `query.live`. `arg` is the validated argument; `query` is a
`RemoteLiveQuery` bound to the client's original cache key, so `reconnect()` targets
the correct client subscription.
```dts
type LiveRequestedEntry = {
arg: Validated;
query: RemoteLiveQuery
## Load
The generic form of `PageLoad` and `LayoutLoad`. You should import those from `./$types` (see [generated types](/docs/kit/types#Generated-types))
rather than using `Load` directly.
```dts
type Load<
Params extends AppLayoutParams<'/'> =
AppLayoutParams<'/'>,
InputData extends Record | null = Record<
string,
any
> | null,
ParentData extends Record = Record<
string,
any
>,
OutputData extends Record | void =
Record | void,
RouteId extends AppRouteId | null = AppRouteId | null
> = (
event: LoadEvent
) => MaybePromise;
```
## LoadEvent
The generic form of `PageLoadEvent` and `LayoutLoadEvent`. You should import those from `./$types` (see [generated types](/docs/kit/types#Generated-types))
rather than using `LoadEvent` directly.
```dts
interface LoadEvent<
Params extends AppLayoutParams<'/'> =
AppLayoutParams<'/'>,
Data extends Record | null = Record<
string,
any
> | null,
ParentData extends Record = Record<
string,
any
>,
RouteId extends AppRouteId | null = AppRouteId | null
> extends NavigationEvent {/*…*/}
```
```dts
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
data: Data;
```
Contains the data returned by the route's server `load` function (in `+layout.server.js` or `+page.server.js`), if any.
```dts
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/@sveltejs-kit#Cookies) API in a server-only `load` function instead.
`setHeaders` has no effect when a `load` function runs in the browser.
```dts
parent: () => Promise;
```
`await parent()` returns data from parent `+layout.js` `load` functions.
Implicitly, a missing `+layout.js` is treated as a `({ data }) => data` function, meaning that it will return and forward data from parent `+layout.server.js` files.
Be careful not to introduce accidental waterfalls when using `await parent()`. If for example you only want to merge parent data into the returned output, call it _after_ fetching your other data.
This function declares that the `load` function has a _dependency_ on one or more URLs or custom identifiers, which can subsequently be used with [`invalidate()`](/docs/kit/$app-navigation#invalidate) to cause `load` to rerun.
Most of the time you won't need this, as `fetch` calls `depends` on your behalf — it's only necessary if you're using a custom API client that bypasses `fetch`.
URLs can be absolute or relative to the page being loaded, and must be [encoded](https://developer.mozilla.org/en-US/docs/Glossary/percent-encoding).
Custom identifiers have to be prefixed with one or more lowercase letters followed by a colon to conform to the [URI specification](https://www.rfc-editor.org/rfc/rfc3986.html).
The following example shows how to use `depends` to register a dependency on a custom identifier, which is `invalidate`d after a button click, making the `load` function rerun.
```js
// @errors: 7031
/// file: src/routes/+page.js
let count = 0;
export async function load({ depends }) {
depends('increase:count');
return { count: count++ };
}
```
```html
/// file: src/routes/+page.svelte
{data.count}
```
```dts
untrack: (fn: () => T) => T;
```
Use this function to opt out of dependency tracking for everything that is synchronously called within the callback. Example:
```js
// @errors: 7031
/// file: src/routes/+page.server.js
export async function load({ untrack, url }) {
// Untrack url.pathname so that path changes don't trigger a rerun
if (untrack(() => url.pathname === '/')) {
return { message: 'Welcome!' };
}
}
```
```dts
tracing: {/*…*/}
```
- available since v2.31.0
Access to spans for tracing. If tracing is not enabled or the function is being run in the browser, 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 `load` function.
## LoadProperties
```dts
type LoadProperties<
input extends Record | void
> = input extends void
? undefined // needs to be undefined, because void will break intellisense
: input extends Record
? input
: unknown;
```
## RemoteForm
The type of a remote `form` function. See [Remote functions](/docs/kit/remote-functions#form) for full documentation.
```dts
type RemoteForm<
Input extends RemoteFormInput | void,
Output
> = {
/** Attachment that sets up an event handler that intercepts the form submission on the client to prevent a full page reload */
[attachment: symbol]: (node: HTMLFormElement) => void;
method: 'POST';
/** The URL to send the form to. */
action: string;
/** The `
## RemoteFormEnhanceCallback
The callback passed to a remote form's `enhance` method. See [Remote functions](/docs/kit/remote-functions#form) for full documentation.
## RemoteFormEnhanceInstance
The form instance as received inside an `enhance` callback. See [Remote functions](/docs/kit/remote-functions#form) for full documentation.
## RemoteFormField
Form field accessor type that provides name(), value(), and issues() methods
```dts
type RemoteFormField =
RemoteFormFieldMethods & {
/**
* Returns an object that can be spread onto an input element with the correct type attribute,
* aria-invalid attribute if the field is invalid, and appropriate value/checked property getters/setters.
* @example
* ```svelte
*
*
*
* ```
*/
as>(
...args: AsArgs
): InputElementProps;
};
```
## RemoteFormFieldType
```dts
type RemoteFormFieldType = {
[K in keyof InputTypeMap]: T extends InputTypeMap[K]
? K
: never;
}[keyof InputTypeMap];
```
## RemoteFormFieldValue
```dts
type RemoteFormFieldValue =
| string
| string[]
| number
| boolean
| File
| File[];
```
## RemoteFormFields
Recursive type to build form fields structure with proxy access
```dts
type RemoteFormFields =
WillRecurseIndefinitely extends true
? RecursiveFormFields
: NonNullable extends
| string
| number
| boolean
| File
? RemoteFormField>
: // [NonNullable] is used to prevent distributing over union while still allowing
// nullable wrappers (e.g. `string[] | undefined` from a schema with `.default([])`)
// to be treated as arrays; only the last condition should distribute over unions
[NonNullable] extends [string[] | File[]]
? RemoteFormField> & {
[K in number]: RemoteFormField<
NonNullable[number]
>;
}
: [NonNullable] extends [Array]
? RemoteFormFieldContainer> & {
[K in number]: RemoteFormFields;
}
: RemoteFormFieldContainer & {
[K in KeysOfUnion]-?: RemoteFormFields<
ValueOfUnionKey
>;
};
```
## RemoteFormInput
```dts
interface RemoteFormInput {/*…*/}
```
```dts
[key: string]: MaybeArray | undefined;
```
## RemoteFormIssue
```dts
interface RemoteFormIssue {/*…*/}
```
```dts
message: string;
```
```dts
path: Array;
```
## RemoteLiveQuery
```dts
type RemoteLiveQuery = RemoteResource &
AsyncIterable & {
/** `true` if the live stream is currently connected. */
readonly connected: boolean;
/** `true` once the current live stream iterator is done. */
readonly done: boolean;
/** Reconnects the live stream immediately. */
reconnect(): Promise;
};
```
## RemoteLiveQueryFunction
The type of a remote `query.live` function. See [Remote functions](/docs/kit/remote-functions#query.live) for full documentation.
The optional `Validated` generic parameter represents the argument type *after* the
query's schema has validated and (optionally) transformed it, and matches the type
yielded by [`requested`](/docs/kit/$app-server#requested).
## RemotePrerenderFunction
The type of a remote `prerender` function. See [Remote functions](/docs/kit/remote-functions#prerender) for full documentation.
```dts
type RemoteQuery = RemoteResource & {
/**
* 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.
*/
set(value: T): 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(): Promise;
/**
* Temporarily override a query's value during a [single-flight mutation](https://svelte.dev/docs/kit/remote-functions#Single-flight-mutations) to provide optimistic updates.
*
* ```svelte
*
*
*
## RemoteQueryFunction
The return value of a remote `query` function. See [Remote functions](/docs/kit/remote-functions#query) for full documentation.
The optional `Validated` generic parameter represents the argument type *after* the
query's schema has validated and (optionally) transformed it — this is the type the
query's implementation function receives on the server, and the type yielded by
[`requested`](/docs/kit/$app-server#requested). For queries declared
with [Standard Schema](https://standardschema.dev/) it differs from `Input` when the
schema contains a transform (e.g. `v.pipe(v.number(), v.transform(String))` has
`Input = number` but `Validated = string`). For `'unchecked'` validators and queries
without arguments it defaults to `Input`.
```dts
type RemoteResource = Promise & {
/** The error in case the query fails. */
get error(): App.Error | undefined;
/** `true` before the first result is available and during refreshes */
get loading(): boolean;
} & (
| {
/** The current value of the query. Undefined until `ready` is `true` */
get current(): undefined;
ready: false;
}
| {
/** The current value of the query. Undefined until `ready` is `true` */
get current(): T;
ready: true;
}
);
```
`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).
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.
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.
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/@sveltejs-kit#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.
## RequestHandler
A `(event: RequestEvent) => Response` function exported from a `+server.js` file that corresponds to an HTTP verb (`GET`, `PUT`, `PATCH`, etc) and handles requests with that method.
It receives `Params` as the first generic argument, which you can skip by using [generated types](/docs/kit/types#Generated-types) instead.
## RequestedEntry
A single entry yielded by [`requested`](/docs/kit/$app-server#requested)
when called with a regular `query`. `arg` is the validated argument (the input *after*
the query's schema validated and transformed it, if applicable); `query` is a
`RemoteQuery` bound to the client's original cache key, so `refresh()` / `set()` will
update the correct client entry.
- `input` the html chunk and the info if this is the last chunk
Applies custom transforms to HTML. If `done` is true, it's the final chunk. Chunks are not guaranteed to be well-formed HTML
(they could include an element's opening tag but not its closing tag, for example)
but they will always be split at sensible boundaries such as `%sveltekit.head%` or layout/page components.
Determines which headers should be included in serialized responses when a `load` function loads a resource with `fetch`.
By default, none will be included.
Determines which files should be preloaded. Files are preloaded via `` tags added to the
`` tag; if `output.linkHeaderPreload` is enabled, dynamically rendered pages use the
[`Link` response header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Link) instead.
By default, `js` and `css` files will be preloaded.
## RouteDefinition
```dts
interface RouteDefinition {/*…*/}
```
```dts
id: string;
```
```dts
api: {
methods: Array;
};
```
```dts
page: {
methods: Array>;
};
```
```dts
pattern: RegExp;
```
```dts
prerender: PrerenderOption;
```
```dts
segments: RouteSegment[];
```
```dts
methods: Array;
```
```dts
config: Config;
```
## SSRManifest
Information required to instantiate a new `Server` instance.
```dts
interface SSRManifest {/*…*/}
```
```dts
appDir: string;
```
The directory where SvelteKit keeps its stuff, including static assets (such as JS and CSS) and internally-used routes.
```dts
appPath: string;
```
The `base` and `appDir` settings combined without a leading slash.
```dts
assets: Set;
```
Static files from `config.files.assets` and the service worker (if any).
```dts
mimeTypes: Record;
```
## ServerInit
Available since 2.10.0
The [`init`](/docs/kit/hooks#init) will be invoked before the server responds to its first request
```dts
type ServerInit = () => MaybePromise;
```
## ServerInitOptions
```dts
interface ServerInitOptions {/*…*/}
```
```dts
env: Record;
```
A map of environment variables.
```dts
read?: (file: string) => MaybePromise;
```
A function that turns an asset filename into a `ReadableStream`. Required for the `read` export from `$app/server` to work.
## ServerLoad
The generic form of `PageServerLoad` and `LayoutServerLoad`. You should import those from `./$types` (see [generated types](/docs/kit/types#Generated-types))
rather than using `ServerLoad` directly.
```dts
type ServerLoad<
Params extends AppLayoutParams<'/'> =
AppLayoutParams<'/'>,
ParentData extends Record = Record<
string,
any
>,
OutputData extends Record | void = Record<
string,
any
> | void,
RouteId extends AppRouteId | null = AppRouteId | null
> = (
event: ServerLoadEvent
) => MaybePromise;
```
`await parent()` returns data from parent `+layout.server.js` `load` functions.
Be careful not to introduce accidental waterfalls when using `await parent()`. If for example you only want to merge parent data into the returned output, call it _after_ fetching your other data.
```dts
depends: (...deps: string[]) => void;
```
This function declares that the `load` function has a _dependency_ on one or more URLs or custom identifiers, which can subsequently be used with [`invalidate()`](/docs/kit/$app-navigation#invalidate) to cause `load` to rerun.
Most of the time you won't need this, as `fetch` calls `depends` on your behalf — it's only necessary if you're using a custom API client that bypasses `fetch`.
URLs can be absolute or relative to the page being loaded, and must be [encoded](https://developer.mozilla.org/en-US/docs/Glossary/percent-encoding).
Custom identifiers have to be prefixed with one or more lowercase letters followed by a colon to conform to the [URI specification](https://www.rfc-editor.org/rfc/rfc3986.html).
The following example shows how to use `depends` to register a dependency on a custom identifier, which is `invalidate`d after a button click, making the `load` function rerun.
```js
// @errors: 7031
/// file: src/routes/+page.js
let count = 0;
export async function load({ depends }) {
depends('increase:count');
return { count: count++ };
}
```
```html
/// file: src/routes/+page.svelte
{data.count}
```
```dts
untrack: (fn: () => T) => T;
```
Use this function to opt out of dependency tracking for everything that is synchronously called within the callback. Example:
```js
// @errors: 7031
/// file: src/routes/+page.js
export async function load({ untrack, url }) {
// Untrack url.pathname so that path changes don't trigger a rerun
if (untrack(() => url.pathname === '/')) {
return { message: 'Welcome!' };
}
}
```
```dts
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 server `load` function.
## Snapshot
Use the [`snapshot`](/docs/kit/$app-navigation#snapshot) helper from `$app/navigation` instead.
The type of `export const snapshot` exported from a page or layout component.
```dts
interface Snapshot {/*…*/}
```
```dts
capture: () => T;
```
```dts
restore: (snapshot: T) => void;
```
## Transport
Available since 2.11.0
The [`transport`](/docs/kit/hooks#transport) hook allows you to transport custom types across the server/client boundary.
Each transporter has a pair of `encode` and `decode` functions. On the server, `encode` determines whether a value is an instance of the custom type and, if so, returns a non-falsy encoding of the value which can be an object or an array (or `false` otherwise).
In the browser, `decode` turns the encoding back into an instance of the custom type.
```ts
import type { Transport } from '@sveltejs/kit';
declare class MyCustomType {
data: any
}
// hooks.js
export const transport: Transport = {
MyCustomType: {
encode: (value) => value instanceof MyCustomType && [value.data],
decode: ([data]) => new MyCustomType(data)
}
};
```
```dts
type Transport = Record;
```
## Transporter
A member of the [`transport`](/docs/kit/hooks#transport) hook.
```dts
interface Transporter<
T = any,
U =
any /* minus falsy values, but we can't properly express that */
> {/*…*/}
```
```dts
encode: (value: T) => false | U;
```
```dts
decode: (data: U) => T;
```
## ValidationError
A validation error thrown by `invalid`.
```dts
interface ValidationError {/*…*/}
```
```dts
issues: StandardSchemaV1.Issue[];
```
The validation issues
## Private types
The following are referenced by the public types documented above, but cannot be imported directly:
## AdapterEntry
```dts
interface AdapterEntry {/*…*/}
```
```dts
id: string;
```
A string that uniquely identifies an HTTP service (e.g. serverless function) and is used for deduplication.
For example, `/foo/a-[b]` and `/foo/[c]` are different routes, but would both
be represented in a Netlify _redirects file as `/foo/:param`, so they share an ID
A function that compares the candidate route with the current route to determine
if it should be grouped with the current route.
Use cases:
- Fallback pages: `/foo/[c]` is a fallback for `/foo/a-[b]`, and `/[...catchall]` is a fallback for all routes
- Grouping routes that share a common `config`: `/foo` should be deployed to the edge, `/bar` and `/baz` should be deployed to a serverless function
A function that is invoked once the entry has been created. This is where you
should write the function to the filesystem and generate redirect manifests.