`](../svelte/svelte-head). Guidance on how to write descriptive titles and descriptions, along with other suggestions on making content understandable by search engines, can be found on Google's [Lighthouse SEO audits](https://web.dev/lighthouse-seo/) documentation.
### Sitemaps
[Sitemaps](https://developers.google.com/search/docs/advanced/sitemaps/build-sitemap) help search engines prioritize pages within your site, particularly when you have a large amount of content. You can create a sitemap dynamically using an endpoint:
```js
/// file: src/routes/sitemap.xml/+server.js
export async function GET() {
return new Response(
`
`.trim(),
{
headers: {
'Content-Type': 'application/xml'
}
}
);
}
```
# @sveltejs/kit
```js
// @noErrors
import {
Server,
VERSION,
error,
fail,
invalid,
isActionFailure,
isHttpError,
isRedirect,
isValidationError,
json,
normalizeUrl,
redirect,
text
} from '@sveltejs/kit';
```
## Server
```dts
class Server {/*…*/}
```
```dts
constructor(manifest: SSRManifest);
```
```dts
init(options: ServerInitOptions): Promise
;
```
```dts
respond(request: Request, options: RequestOptions): Promise
;
```
## VERSION
```dts
const VERSION: string;
```
## 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.
```dts
function error(
status: {
status: number;
message: string;
} extends App.Error
? number
: never,
message?: string | undefined
): never;
```
```dts
function error(
status: number,
message: string,
properties: keyof Omit<
App.Error,
'status' | 'message'
> extends never
? never
: Omit
): never;
```
```dts
function error(
status: number,
properties: Omit
& {
status?: App.Error['status'];
}
): never;
```
## 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
```
```dts
function normalizeUrl(url: URL | string): {
url: URL;
wasNormalized: boolean;
denormalize: (url?: string | URL) => URL;
};
```
## 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)
```dts
function redirect(
status:
| 300
| 301
| 302
| 303
| 304
| 305
| 306
| 307
| 308
| ({} & number),
location: string | URL,
options?: {
external?: boolean | string[];
}
): never;
```
## text
use `new Response`
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.
```dts
type Action<
Params extends AppLayoutParams<'/'> =
AppLayoutParams<'/'>,
OutputData extends Record
| void = Record<
string,
any
> | void,
RouteId extends AppRouteId | null = AppRouteId | null
> = (
event: RequestEvent
) => MaybePromise;
```
## ActionFailure
```dts
interface ActionFailure
{/*…*/}
```
```dts
status: number;
```
```dts
[uniqueSymbol]: true;
```
## Actions
Shape of the `export const actions = {...}` object in `+page.server.js`.
See [form actions](/docs/kit/form-actions) for more information.
```dts
type Actions<
Params extends AppLayoutParams<'/'> =
AppLayoutParams<'/'>,
OutputData extends Record | void = Record<
string,
any
> | void,
RouteId extends AppRouteId | null = AppRouteId | null
> = Record>;
```
## 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.
```dts
adapt: (builder: Builder) => MaybePromise
;
```
- `builder` An object provided by SvelteKit that contains methods for adapting the app
This function is called after SvelteKit has built your app.
```dts
supports?: {/*…*/}
```
Checks called during dev and build to determine whether specific features will work in production with this adapter.
```dts
read?: (details: { config: Record
; route: { id: string } }) => boolean;
```
- `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`.
```dts
rimraf: (dir: string) => void;
```
- deprecated Use `fs.rmSync(dir, { force: true, recursive: true })` instead
Remove `dir` and all its contents.
```dts
mkdirp: (dir: string) => void;
```
- deprecated Use `fs.mkdirSync(dir, { recursive: true })` instead
Create `dir` and any required parent directories.
```dts
config: ValidatedConfig;
```
The fully resolved SvelteKit config.
```dts
prerendered: Prerendered;
```
Information about prerendered pages and assets, if any.
```dts
routes: RouteDefinition[];
```
An array of all routes (including prerendered)
```dts
createEntries?: (fn: (route: RouteDefinition) => AdapterEntry) => Promise
;
```
- `fn` A function that groups a set of routes into an entry point
- deprecated removed in 3.0. Use `builder.routes` instead
Create separate functions that map to one or more routes of your app.
```dts
findServerAssets: (routes: RouteDefinition[]) => string[];
```
Find all the assets imported by server files belonging to `routes`
```dts
generateFallback: (dest: string) => Promise
;
```
Generate a fallback page for a static webserver to use when no route is matched. Useful for single-page apps.
```dts
generateEnvModule: () => void;
```
Generate a module exposing public environment variables as `$app/env/public` if the app uses it.
```dts
generateManifest: (opts: { relativePath: string; routes?: RouteDefinition[] }) => string;
```
- `opts.relativePath` A relative path to the base directory of the server build output
Generate a server-side manifest to initialise the SvelteKit [server](/docs/kit/@sveltejs-kit#Server) with.
```dts
getBuildDirectory: (name: string) => string;
```
- `name` path to the file, relative to the build directory
Resolve a path to the `name` directory inside `outDir`, e.g. `/path/to/.svelte-kit/my-adapter`.
```dts
getClientDirectory: () => string;
```
Get the fully resolved path to the directory containing client-side assets, including the contents of your `static` directory.
```dts
getServerDirectory: () => string;
```
Get the fully resolved path to the directory containing server-side code.
```dts
getAppPath: () => string;
```
Get the application path including any configured `base` path, e.g. `my-base-path/_app`.
```dts
writeClient: (dest: string) => string[];
```
- `dest` the destination folder
- returns an array of files written to `dest`
Write client assets to `dest`.
```dts
writePrerendered: (dest: string) => string[];
```
- `dest` the destination folder
- returns an array of files written to `dest`
Write prerendered files to `dest`.
```dts
writeServer: (dest: string) => string[];
```
- `dest` the destination folder
- returns an array of files written to `dest`
Write server-side code to `dest`.
```dts
copy: (
from: string,
to: string,
opts?: {
filter?(basename: string): boolean;
replace?: Record
;
}
) => string[];
```
- `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
Copy a file or directory.
```dts
hasServerInstrumentationFile: () => boolean;
```
- returns true if the server instrumentation file exists, false otherwise
- available since v2.31.0
Check if the server instrumentation file exists.
```dts
instrument: (args: {
entrypoint: string;
instrumentation: string;
start?: string;
module?:
| {
exports: string[];
}
| {
generateText: (args: { instrumentation: string; start: string }) => string;
};
}) => void;
```
- `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.
```dts
compress: (directory: string) => Promise
;
```
- `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.
```dts
type ClientCaughtError = Exclude<
CaughtError,
{ kind: 'validation' }
>;
```
## ClientInit
Available since 2.10.0
The [`init`](/docs/kit/hooks#init) will be invoked once the app starts in the browser
```dts
type ClientInit = () => MaybePromise;
```
## Config
See the [configuration reference](/docs/kit/configuration) for details.
## 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.
## 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
```dts
interface Emulator {/*…*/}
```
```dts
platform?(details: { config: any; prerender: PrerenderOption }): MaybePromise
;
```
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
```dts
schema?: StandardSchemaV1
| ((value: string | undefined) => T | undefined);
```
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).
```dts
type Handle = (input: {
event: RequestEvent;
resolve: (
event: RequestEvent,
opts?: ResolveOptions
) => Promise;
}) => MaybePromise;
```
## 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.
```dts
type HandleClientError = (
input: ClientCaughtError & { event: NavigationEvent }
) => MaybePromise<
| AppErrorWithOptionalDefaults
| VoidIfNoRequiredAppErrorProperties
>;
```
## 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`.
```dts
type HandleFetch = (input: {
event: RequestEvent;
request: Request;
fetch: typeof fetch;
}) => MaybePromise;
```
## 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.
```dts
type HandleServerError<
Issue extends StandardSchemaV1.Issue =
StandardSchemaV1.Issue
> = (
input: CaughtError & { event: RequestEvent }
) => MaybePromise<
| AppErrorWithOptionalDefaults
| VoidIfNoRequiredAppErrorProperties
>;
```
## 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.
```dts
type InvalidField =
WillRecurseIndefinitely extends true
? Record
: NonNullable extends
| string
| number
| boolean
| File
? (message: string) => StandardSchemaV1.Issue
: NonNullable extends Array
? {
[K in number]: InvalidField;
} & ((message: string) => StandardSchemaV1.Issue)
: NonNullable extends RemoteFormInput
? {
[K in keyof T]-?: InvalidField;
} & ((
message: string
) => StandardSchemaV1.Issue)
: Record;
```
## 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.
```dts
depends: (...deps: Array<`${string}:${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}
Increase 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;
```
## NavigationEvent
```dts
interface NavigationEvent<
Params extends AppLayoutParams<'/'> =
AppLayoutParams<'/'>,
RouteId extends AppRouteId | null = AppRouteId | null
> {/*…*/}
```
```dts
params: Params;
```
The parameters of the current page - e.g. for a route like `/blog/[slug]`, a `{ slug: string }` object
```dts
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.
```dts
url: URL;
```
The URL of the current page
## PrerenderOption
```dts
type PrerenderOption = boolean | 'auto';
```
## QueryRequestedResult
```dts
type QueryRequestedResult = Iterable<
RequestedEntry
> &
AsyncIterable> & {
/**
* Call `refresh` on all queries selected by this `requested` invocation.
* This is identical to:
* ```ts
* import { requested } from '$app/server';
*
* for await (const { query } of requested(getPost, ...)) {
* void query.refresh();
* }
* ```
*/
refreshAll: () => Promise;
};
```
## Redirect
The object returned by the [`redirect`](/docs/kit/@sveltejs-kit#redirect) function.
```dts
interface Redirect {/*…*/}
```
```dts
status: 300 | 301 | 302 | 303 | 304 | 305 | 306 | 307 | 308;
```
The [HTTP status code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#redirection_messages), in the range 300-308.
```dts
location: string;
```
The location to redirect to.
## RemoteCommand
The type of a remote `command` function. See [Remote functions](/docs/kit/remote-functions#command) for full documentation.
```dts
type RemoteCommand = {
(
arg: undefined extends Input ? Input | void : Input
): Promise & {
updates(
...updates: RemoteQueryUpdate[]
): Promise;
};
/** The number of pending command executions */
get pending(): number;
};
```
## 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.
```dts
type RemoteFormEnhanceCallback<
Input extends RemoteFormInput | void =
RemoteFormInput | void,
Output = any
> = (
form: RemoteFormEnhanceInstance
) => MaybePromise;
```
## RemoteFormEnhanceInstance
The form instance as received inside an `enhance` callback. See [Remote functions](/docs/kit/remote-functions#form) for full documentation.
```dts
type RemoteFormEnhanceInstance<
Input extends RemoteFormInput | void =
RemoteFormInput | void,
Output = any
> = Omit<
RemoteForm ,
'enhance' | 'element'
> & {
readonly element: HTMLFormElement;
};
```
## 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;
```
## 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).
```dts
type RemoteLiveQueryFunction<
Input,
Output,
_Validated = Input
> = (
arg: undefined extends Input ? Input | void : Input
) => RemoteLiveQuery;
```
## RemotePrerenderFunction
The type of a remote `prerender` function. See [Remote functions](/docs/kit/remote-functions#prerender) for full documentation.
```dts
type RemotePrerenderFunction = (
arg: undefined extends Input ? Input | void : Input
) => RemoteResource;
```
## RemoteQuery
```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
*
*
* {
* await form.submit().updates(
* todos.withOverride((todos) => [...todos, { text: form.fields.text.value() }])
* );
* })}>
*
* Add Todo
*
* ```
*/
withOverride(
update: (current: T) => T
): RemoteQueryOverride;
};
```
## 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 RemoteQueryFunction<
Input,
Output,
_Validated = Input
> = (
arg: undefined extends Input ? Input | void : Input
) => RemoteQuery;
```
## RemoteQueryOverride
```dts
type RemoteQueryOverride = () => void;
```
## RemoteQueryUpdate
```dts
type RemoteQueryUpdate =
| RemoteQuery
| RemoteLiveQuery
| RemoteQueryFunction
| RemoteLiveQueryFunction
| RemoteQueryOverride;
```
## RemoteResource
```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;
}
);
```
## 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/@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.
```dts
type RequestHandler<
Params extends AppLayoutParams<'/'> =
AppLayoutParams<'/'>,
RouteId extends AppRouteId | null = AppRouteId | null
> = (
event: RequestEvent
) => MaybePromise;
```
## 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.
```dts
type RequestedEntry = {
arg: Validated;
query: RemoteQuery;
};
```
## RequestedResult
```dts
type RequestedResult =
| QueryRequestedResult
| LiveQueryRequestedResult;
```
## Reroute
Available since 2.3.0
The [`reroute`](/docs/kit/hooks#reroute) hook allows you to modify the URL before it is used to determine which route to render.
```dts
type Reroute = (event: {
url: URL;
fetch: typeof fetch;
}) => MaybePromise;
```
## ResolveOptions
```dts
interface ResolveOptions {/*…*/}
```
```dts
transformPageChunk?: (input: { html: string; done: boolean }) => MaybePromise
;
```
- `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.
```dts
filterSerializedResponseHeaders?: (name: string, value: string) => boolean;
```
- `name` header name
- `value` header value
Determines which headers should be included in serialized responses when a `load` function loads a resource with `fetch`.
By default, none will be included.
```dts
preload?: (input: { type: 'font' | 'css' | 'js' | 'asset'; path: string }) => boolean;
```
- `input` the type of the file and its path
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
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;
```
## ServerLoadEvent
```dts
interface ServerLoadEvent<
Params extends AppLayoutParams<'/'> =
AppLayoutParams<'/'>,
ParentData extends Record
= Record<
string,
any
>,
RouteId extends AppRouteId | null = AppRouteId | null
> extends RequestEvent {/*…*/}
```
```dts
parent: () => Promise
;
```
`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}
Increase 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
```dts
filter(route: RouteDefinition): boolean;
```
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
```dts
complete(entry: { generateManifest(opts: { relativePath: string }): string }): MaybePromise
;
```
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.
## Csp
```dts
namespace Csp {
type ActionSource = 'strict-dynamic' | 'report-sample';
type BaseSource =
| 'self'
| 'unsafe-eval'
| 'unsafe-hashes'
| 'unsafe-inline'
| 'unsafe-allow-redirects'
| 'unsafe-webtransport-hashes'
| 'wasm-unsafe-eval'
| 'trusted-types-eval'
| 'none';
type CryptoSource =
`${'nonce' | 'sha256' | 'sha384' | 'sha512'}-${string}`;
type FrameSource =
| HostSource
| SchemeSource
| 'self'
| 'none';
type HostNameScheme = `${string}.${string}` | 'localhost';
type HostSource =
`${HostProtocolSchemes}${HostNameScheme}${PortScheme}`;
type HostProtocolSchemes = `${string}://` | '';
type HttpDelineator = '/' | '?' | '#' | '\\';
type PortScheme = `:${number}` | '' | ':*';
type SchemeSource =
| 'http:'
| 'https:'
| 'ws:'
| 'wss:'
| 'data:'
| 'mediastream:'
| 'blob:'
| 'filesystem:'
| (`${string}:` & {});
type Source =
| HostSource
| SchemeSource
| CryptoSource
| BaseSource;
type Sources = Source[];
}
```
## CspDirectives
```dts
interface CspDirectives {/*…*/}
```
```dts
'child-src'?: Csp.Sources;
```
```dts
'default-src'?: Array
;
```
```dts
'frame-src'?: Csp.Sources;
```
```dts
'worker-src'?: Csp.Sources;
```
```dts
'connect-src'?: Csp.Sources;
```
```dts
'font-src'?: Csp.Sources;
```
```dts
'img-src'?: Csp.Sources;
```
```dts
'manifest-src'?: Csp.Sources;
```
```dts
'media-src'?: Csp.Sources;
```
```dts
'object-src'?: Csp.Sources;
```
```dts
'prefetch-src'?: Csp.Sources;
```
```dts
'script-src'?: Array
;
```
```dts
'script-src-elem'?: Csp.Sources;
```
```dts
'script-src-attr'?: Csp.Sources;
```
```dts
'style-src'?: Array
;
```
```dts
'style-src-elem'?: Csp.Sources;
```
```dts
'style-src-attr'?: Csp.Sources;
```
```dts
'base-uri'?: Array
;
```
```dts
sandbox?: Array<
| 'allow-downloads-without-user-activation'
| 'allow-forms'
| 'allow-modals'
| 'allow-orientation-lock'
| 'allow-pointer-lock'
| 'allow-popups'
| 'allow-popups-to-escape-sandbox'
| 'allow-presentation'
| 'allow-same-origin'
| 'allow-scripts'
| 'allow-storage-access-by-user-activation'
| 'allow-top-navigation'
| 'allow-top-navigation-by-user-activation'
>;
```
```dts
'form-action'?: Array
;
```
```dts
'frame-ancestors'?: Array
;
```
```dts
'navigate-to'?: Array
;
```
```dts
'report-uri'?: string[];
```
```dts
'report-to'?: string[];
```
```dts
'require-trusted-types-for'?: Array<'script'>;
```
```dts
'trusted-types'?: Array<'none' | 'allow-duplicates' | '*' | string>;
```
```dts
'upgrade-insecure-requests'?: boolean;
```
```dts
'require-sri-for'?: Array<'script' | 'style' | 'script style'>;
```
```dts
'block-all-mixed-content'?: boolean;
```
```dts
'plugin-types'?: Array<`${string}/${string}` | 'none'>;
```
```dts
referrer?: Array<
| 'no-referrer'
| 'no-referrer-when-downgrade'
| 'origin'
| 'origin-when-cross-origin'
| 'same-origin'
| 'strict-origin'
| 'strict-origin-when-cross-origin'
| 'unsafe-url'
| 'none'
>;
```
## DeepPartial
```dts
type DeepPartial
= T extends
| Record
| unknown[]
? {
[K in keyof T]?: T[K] extends
| Record
| unknown[]
? DeepPartial
: T[K];
}
: T | undefined;
```
## HasNonOptionalBoolean
```dts
type HasNonOptionalBoolean =
IsAny extends true
? never
: [T] extends [boolean]
? true
: T extends Array
? HasNonOptionalBoolean
: T extends Record
? {
[K in keyof T]: HasNonOptionalBoolean;
}[keyof T]
: never;
```
## HttpMethod
```dts
type HttpMethod =
| 'GET'
| 'HEAD'
| 'POST'
| 'PUT'
| 'DELETE'
| 'PATCH'
| 'OPTIONS';
```
## IsAny
```dts
type IsAny = 0 extends 1 & T ? true : false;
```
## Logger
```dts
interface Logger {/*…*/}
```
```dts
(msg: string): void;
```
```dts
success(msg: string): void;
```
```dts
error(msg: string): void;
```
Print a bold red message to stderr
```dts
warn(msg: string): void;
```
Print a bold yellow message to stderr
```dts
minor(msg: string): void;
```
Print faded text to stdout if `verbose === true`
```dts
info(msg: string): void;
```
Print to stdout if `verbose === true`
```dts
err(msg: string): void;
```
Print to stderr without formatting
```dts
prettyError(error: unknown, caller?: string): void;
```
Print a bold red message, followed by a stack trace for each error (following `.cause` chains)
## MaybePromise
```dts
type MaybePromise = T | Promise;
```
## PrerenderEntryGeneratorMismatchHandler
```dts
interface PrerenderEntryGeneratorMismatchHandler {/*…*/}
```
```dts
(details: { generatedFromId: string; entry: string; matchedId: string; message: string }): void;
```
## PrerenderEntryGeneratorMismatchHandlerValue
```dts
type PrerenderEntryGeneratorMismatchHandlerValue =
| 'fail'
| 'warn'
| 'ignore'
| PrerenderEntryGeneratorMismatchHandler;
```
## PrerenderHttpErrorHandler
```dts
interface PrerenderHttpErrorHandler {/*…*/}
```
```dts
(details: {
status: number;
path: string;
referrer: string | null;
referenceType: 'linked' | 'fetched';
message: string;
}): void;
```
## PrerenderHttpErrorHandlerValue
```dts
type PrerenderHttpErrorHandlerValue =
| 'fail'
| 'warn'
| 'ignore'
| PrerenderHttpErrorHandler;
```
## PrerenderInvalidUrlHandler
```dts
interface PrerenderInvalidUrlHandler {/*…*/}
```
```dts
(details: { href: string; referrer: string | null; message: string }): void;
```
## PrerenderInvalidUrlHandlerValue
```dts
type PrerenderInvalidUrlHandlerValue =
| 'fail'
| 'warn'
| 'ignore'
| PrerenderInvalidUrlHandler;
```
## PrerenderMap
```dts
type PrerenderMap = Map;
```
## PrerenderMissingIdHandler
```dts
interface PrerenderMissingIdHandler {/*…*/}
```
```dts
(details: { path: string; id: string; referrers: string[]; message: string }): void;
```
## PrerenderMissingIdHandlerValue
```dts
type PrerenderMissingIdHandlerValue =
| 'fail'
| 'warn'
| 'ignore'
| PrerenderMissingIdHandler;
```
## PrerenderOption
```dts
type PrerenderOption = boolean | 'auto';
```
## PrerenderUnseenRoutesHandler
```dts
interface PrerenderUnseenRoutesHandler {/*…*/}
```
```dts
(details: { routes: string[]; message: string }): void;
```
## PrerenderUnseenRoutesHandlerValue
```dts
type PrerenderUnseenRoutesHandlerValue =
| 'fail'
| 'warn'
| 'ignore'
| PrerenderUnseenRoutesHandler;
```
## Prerendered
```dts
interface Prerendered {/*…*/}
```
```dts
pages: Map<
string,
{
/** The location of the .html file relative to the output directory */
file: string;
}
>;
```
A map of `path` to `{ file }` objects, where a path like `/foo` corresponds to `foo.html` and a path like `/bar/` corresponds to `bar/index.html`.
```dts
assets: Map<
string,
{
/** The MIME type of the asset */
type: string;
}
>;
```
A map of `path` to `{ type }` objects.
```dts
redirects: Map<
string,
{
status: number;
location: string;
}
>;
```
A map of redirects encountered during prerendering.
```dts
paths: string[];
```
An array of prerendered paths (without trailing slashes, regardless of the trailingSlash config)
## RequestOptions
```dts
interface RequestOptions {/*…*/}
```
```dts
getClientAddress(): string;
```
```dts
platform?: App.Platform;
```
## RouteSegment
```dts
interface RouteSegment {/*…*/}
```
```dts
content: string;
```
```dts
dynamic: boolean;
```
```dts
rest: boolean;
```
## TrailingSlash
```dts
type TrailingSlash = 'never' | 'always' | 'ignore';
```
# @sveltejs/kit/env
```js
// @noErrors
import { defineEnvVars } from '@sveltejs/kit/env';
```
## defineEnvVars
Utility for defining [environment variables](/docs/kit/environment-variables),
which are made available via `$app/env/public` and `$app/env/private`.
```js
// @errors: 7031
import { defineEnvVars } from '@sveltejs/kit/env';
import * as v from 'valibot';
export const variables = defineEnvVars({
API_URL: {
schema: v.pipe(v.string(), v.url())
},
PORT: {
schema: (value) => {
if (value === undefined) return 3000;
const port = Number(value);
if (!Number.isInteger(port)) throw new Error('PORT must be an integer');
return port;
}
}
});
```
```dts
function defineEnvVars<
T extends Record>
>(variables: T): DefinedEnvVars;
```
# @sveltejs/kit/hooks
```js
// @noErrors
import { sequence } from '@sveltejs/kit/hooks';
```
## sequence
A helper function for sequencing multiple `handle` calls in a middleware-like manner.
The behavior for the `handle` options is as follows:
- `transformPageChunk` is applied in reverse order and merged
- `preload` is applied in forward order, the first option "wins" and no `preload` options after it are called
- `filterSerializedResponseHeaders` behaves the same as `preload`
```js
// @errors: 7031
/// file: src/hooks.server.js
import { sequence } from '@sveltejs/kit/hooks';
/** @type {import('@sveltejs/kit').Handle} */
async function first({ event, resolve }) {
console.log('first pre-processing');
const result = await resolve(event, {
transformPageChunk: ({ html }) => {
// transforms are applied in reverse order
console.log('first transform');
return html;
},
preload: () => {
// this one wins as it's the first defined in the chain
console.log('first preload');
return true;
}
});
console.log('first post-processing');
return result;
}
/** @type {import('@sveltejs/kit').Handle} */
async function second({ event, resolve }) {
console.log('second pre-processing');
const result = await resolve(event, {
transformPageChunk: ({ html }) => {
console.log('second transform');
return html;
},
preload: () => {
console.log('second preload');
return true;
},
filterSerializedResponseHeaders: () => {
// this one wins as it's the first defined in the chain
console.log('second filterSerializedResponseHeaders');
return true;
}
});
console.log('second post-processing');
return result;
}
export const handle = sequence(first, second);
```
The example above would print:
```
first pre-processing
first preload
second pre-processing
second filterSerializedResponseHeaders
second transform
first transform
second post-processing
first post-processing
```
Calling `resolve` invokes the next handler in the sequence (or SvelteKit itself, if it is the last one). To pass data between handlers, use `event.locals`.
```dts
function sequence(...handlers: Handle[]): Handle;
```
# @sveltejs/kit/node
```js
// @noErrors
import {
createReadableStream,
getRequest,
setResponse
} from '@sveltejs/kit/node';
```
## createReadableStream
Available since 2.4.0
Converts a file on disk to a readable stream
```dts
function createReadableStream(file: string): ReadableStream;
```
## getRequest
```dts
function getRequest({
request,
base,
bodySizeLimit
}: {
request: import('http').IncomingMessage;
base: string;
bodySizeLimit?: number;
}): Request;
```
## setResponse
```dts
function setResponse(
res: import('http').ServerResponse,
response: Response
): void;
```
# @sveltejs/kit/params
```js
// @noErrors
import { defineParams } from '@sveltejs/kit/params';
```
## defineParams
Define [parameter matchers](/docs/kit/advanced-routing#Matching) for your app.
```dts
function defineParams<
T extends Record
>(definitions: T): DefinedParams;
```
## DefinedParams
The return type of [`defineParams`](/docs/kit/@sveltejs-kit-params#defineParams).
```dts
type DefinedParams<
T extends Record
> = {
readonly [K in keyof T]: ParamEntry;
};
```
## MatcherParam
Extracts the param type from a matcher.
```dts
type MatcherParam
> =
M extends StandardSchemaV1
? Inner extends ParamValue
? Inner
: Inner extends StandardSchemaV1
? StandardSchemaV1.InferOutput extends ParamValue
? StandardSchemaV1.InferOutput
: never
: never
: never;
```
## ParamDefinition
A param matcher definition passed to [`defineParams`](/docs/kit/@sveltejs-kit-params#defineParams).
```dts
type ParamDefinition =
| ((param: string) => ParamValue | undefined)
| StandardSchemaV1;
```
## ParamMatcher
The shape of a param matcher. See [matching](/docs/kit/advanced-routing#Matching) for more info.
```dts
type ParamMatcher = StandardSchemaV1<
string,
Output
>;
```
## ParamValue
A value that can be parsed from a URL param and losslessly encoded with `String(...)`.
```dts
type ParamValue = string | number | boolean | bigint;
```
# @sveltejs/kit/vite
```js
// @noErrors
import { sveltekit } from '@sveltejs/kit/vite';
```
## sveltekit
Returns the SvelteKit Vite plugins.
Any options that don't belong to SvelteKit are passed through to `vite-plugin-svelte`.
Since version 3.0.0 you must pass [configuration](configuration) directly.
Since version 2.62.0 you can pass configuration directly, in which case `svelte.config.js` is ignored.
```dts
function sveltekit(
config?: KitConfig &
Omit
&
Pick
): Promise;
```
# $app/env
```js
// @noErrors
import { browser, building, dev, version } from '$app/env';
```
## browser
`true` if the app is running in the browser.
```dts
const browser: boolean;
```
## building
SvelteKit analyses your app during the `build` step by running it. During this process, `building` is `true`. This also applies during prerendering.
```dts
const building: boolean;
```
## dev
Whether the dev server is running. This is not guaranteed to correspond to `NODE_ENV` or `MODE`.
```dts
const dev: boolean;
```
## version
The value of `config.version.name`.
```dts
const version: string;
```
# $app/env/private
Private [environment variables](environment-variables) defined in `src/env.ts` (or `src/env.js`).
To use this module, you must enable the `experimental.explicitEnvironmentVariables` flag in your project configuration.
# $app/env/public
Public [environment variables](environment-variables) defined in `src/env.ts` (or `src/env.js`).
To use this module, you must enable the `experimental.explicitEnvironmentVariables` flag in your project configuration.
# $app/forms
```js
// @noErrors
import { applyAction, deserialize, enhance } from '$app/forms';
```
## applyAction
Updates the `form` property of the current page with the given data and updates `page.status`.
In case of an error, it renders the nearest error page. In case of a redirect, it navigates to
the redirect location.
```dts
function applyAction<
Success extends Record | undefined,
Failure extends Record | undefined
>(result: ActionResult): Promise;
```
## deserialize
Use this function to deserialize the response from a form submission.
Usage:
```js
// @errors: 7031
import { deserialize } from '$app/forms';
async function handleSubmit(event) {
const response = await fetch('/form?/action', {
method: 'POST',
body: new FormData(event.target)
});
const result = deserialize(await response.text());
// ...
}
```
```dts
function deserialize<
Success extends Record | undefined,
Failure extends Record | undefined
>(result: string): ActionResult;
```
## enhance
This action enhances a `` element that otherwise would work without JavaScript.
The `submit` function is called upon submission with the given FormData and the `action` that should be triggered.
If `cancel` is called, the form will not be submitted.
You can use the abort `controller` to cancel the submission in case another one starts.
If a function is returned, that function is called with the response from the server.
If nothing is returned, the fallback will be used.
If this function or its return value isn't set, it emulates the browser-native behaviour, just without the full-page reload. It
- resets the ` ` element and refreshes all data in case of a successful submission with no redirect response
- updates the `form` prop, `page.form` and `page.status` if the action is on the same page as the form
- navigates to the page the submission lands on — populating that page's `form` prop and `page.status` — on success and failure if that isn't the current page, just as a native form submission would, but with the `?/actionName` param stripped from the destination URL
- redirects in case of a redirect response
- renders the nearest error page in case of an unexpected error — the one nearest the action's route, if the action is on a different page
If you provide a custom function with a callback and want to use the default behavior, invoke `update` in your callback.
It accepts an options object
- `reset: false` if you don't want the ` ` values to be reset after a successful submission
- `refreshAll` to control whether all data is refreshed after submission; it defaults to `true` for successes and `false` for failures
- `navigate: false` to apply non-redirect results to the current page rather than navigating to `result.location`; redirects are always followed
```dts
function enhance<
Success extends Record | undefined,
Failure extends Record | undefined
>(
form_element: HTMLFormElement,
submit?: SubmitFunction
): {
destroy(): void;
};
```
## ActionResult
When calling a form action via fetch, the response will be one of these shapes.
```svelte
{
return ({ result }) => {
// result is of type ActionResult
};
}}
```
Success and failure results carry the root-relative `pathname + search` of the action URL, with
the `?/actionName` parameter removed. Redirect results carry the redirect target. Server-generated
error results also carry the action location, while client-generated errors such as network
failures do not. `update` uses this location to emulate native form navigation.
```dts
type ActionResult<
Success extends Record | undefined =
Record,
Failure extends Record | undefined =
Record
> =
| {
type: 'success';
status: number;
data?: Success;
location: string;
}
| {
type: 'failure';
status: number;
data?: Failure;
location: string;
}
| { type: 'redirect'; status: number; location: string }
| {
type: 'error';
status?: number;
error: App.Error;
location?: string;
};
```
## SubmitFunction
```dts
type SubmitFunction<
Success extends Record | undefined =
Record,
Failure extends Record | undefined =
Record
> = (input: {
action: URL;
formData: FormData;
formElement: HTMLFormElement;
controller: AbortController;
submitter: HTMLElement | null;
cancel: () => void;
}) => MaybePromise<
| void
| ((opts: {
formData: FormData;
formElement: HTMLFormElement;
action: URL;
result: ActionResult;
/**
* Call this to get the default behavior of a form submission response.
* @param options Set `reset: false` if you don't want the `` values to be reset after a successful submission. `refreshAll` defaults to `true` for successful results and `false` for failures. When the submission navigates, setting it to `false` still runs the destination's `load` functions but may reuse shared layout data. Set `navigate: false` to apply non-redirect results to the current page instead of navigating to `result.location`. Redirects are always followed.
*/
update: (options?: {
reset?: boolean;
refreshAll?: boolean;
navigate?: boolean;
/** @deprecated Use `refreshAll` instead. */
invalidateAll?: boolean;
}) => Promise;
}) => MaybePromise)
>;
```
# $app/manifest
```js
// @noErrors
import { assets, immutable, prerendered, routes } from '$app/manifest';
```
This module is available to [service workers](/docs/kit/service-workers) and other contexts.
It exports information about the build output, static files, prerendered pages, and routes.
## assets
An array of `{ path: AssetPath }` objects representing the files in your `static` directory, or whatever directory is specified by `config.files.assets`.
The path is relative to the [base path](/docs/kit/configuration#paths), and can be used with [`asset(...)`](/docs/kit/$app-paths#asset).
```dts
const assets: Array<{
path: import('$app/types').AssetPath;
}>;
```
## immutable
An array of `{ path: string }` objects representing the files generated by Vite.
The path is relative to the [base path](/docs/kit/configuration#paths), and is intended for use with `cache.add(...)` inside a [service worker](/docs/kit/service-workers).
During development, this is an empty array.
```dts
const immutable: Array<{ path: string }>;
```
## prerendered
An array of `{ path: Path }` objects representing prerendered pages and endpoints, relative to the [base path](/docs/kit/configuration#paths).
During development, this is an empty array.
```dts
const prerendered: Array<{
path: import('$app/types').Path;
}>;
```
## routes
An array of objects representing the routes in your app. Only routes that the router can match
are included — directories that merely hold a `+layout` are not routes of their own.
Each object has an `id`, plus `page` and `endpoint` booleans describing whether the route has a
`+page` and/or a `+server`. Both are `true` for a route that has both, so the capabilities can
be filtered independently:
```js
// @errors: 7031
import { routes } from '$app/manifest';
const pages = routes.filter((route) => route.page);
const endpoints = routes.filter((route) => route.endpoint);
```
```dts
const routes: ManifestRoute[];
```
## ManifestRoute
A route in your app, along with its capabilities. `page` indicates the presence of a `+page`,
while `endpoint` indicates the presence of a `+server`. Both are `true` when both files exist.
```dts
type ManifestRoute =
| {
id: Exclude<
import('$app/types').PageRouteId,
import('$app/types').EndpointRouteId
>;
page: true;
endpoint: false;
}
| {
id: Exclude<
import('$app/types').EndpointRouteId,
import('$app/types').PageRouteId
>;
page: false;
endpoint: true;
}
| {
id: Extract<
import('$app/types').PageRouteId,
import('$app/types').EndpointRouteId
>;
page: true;
endpoint: true;
};
```
# $app/navigation
```js
// @noErrors
import {
afterNavigate,
beforeNavigate,
disableScrollHandling,
goto,
invalidate,
invalidateAll,
onNavigate,
preloadCode,
preloadData,
pushState,
refreshAll,
replaceState,
snapshot
} from '$app/navigation';
```
## afterNavigate
A lifecycle function that runs the supplied `callback` when the current component mounts, and also whenever we navigate to a URL.
`afterNavigate` must be called during a component initialization. It remains active as long as the component is mounted.
```dts
function afterNavigate(
callback: (navigation: AfterNavigate) => void
): void;
```
## beforeNavigate
A navigation interceptor that triggers before we navigate to a URL, whether by clicking a link, calling `goto(...)`, or using the browser back/forward controls.
Calling `cancel()` will prevent the navigation from completing. If `navigation.type === 'leave'` — meaning the user is navigating away from the app (or closing the tab) — calling `cancel` will trigger the native browser unload confirmation dialog. In this case, the navigation may or may not be cancelled depending on the user's response.
When a navigation isn't to a SvelteKit-owned route (and therefore controlled by SvelteKit's client-side router), `navigation.to.route.id` will be `null`.
If the navigation will (if not cancelled) cause the document to unload — in other words `'leave'` navigations and `'link'` navigations where `navigation.to.route === null` — `navigation.willUnload` is `true`.
`beforeNavigate` must be called during a component initialization. It remains active as long as the component is mounted.
```dts
function beforeNavigate(
callback: (navigation: BeforeNavigate) => void
): void;
```
## disableScrollHandling
If called when the page is being updated following a navigation (in `onMount` or `afterNavigate` or an action, for example), this disables SvelteKit's built-in scroll handling.
This is generally discouraged, since it breaks user expectations.
```dts
function disableScrollHandling(): void;
```
## goto
Allows you to navigate programmatically to a given route, with control over details such as whether scroll and focus are reset
(as they would be with a regular navigation) or preserved.
Returns a Promise that resolves when SvelteKit navigates (or fails to navigate, in which case the promise rejects) or the state change has been applied.
`goto` is intended for navigations to routes that belong to the app, and will reject if a route cannot be resolved.
For external URLs, use `window.location = url` to perform a full-page navigation instead of calling `goto(url)`.
```dts
function goto(
url: string | URL,
opts?: GotoOptions
): Promise;
```
## invalidate
Causes any `load` functions belonging to the currently active page to re-run if they depend on the `url` in question, via `fetch` or `depends`. Returns a `Promise` that resolves when the page is subsequently updated.
If the argument is given as a `string` or `URL`, it must resolve to the same URL that was passed to `fetch` or `depends` (including query parameters).
To create a custom identifier, use a string beginning with `[a-z]+:` (e.g. `custom:state`) — this is a valid URL.
The `function` argument can be used define a custom predicate. It receives the full `URL` and causes `load` to rerun if `true` is returned.
This can be useful if you want to invalidate based on a pattern instead of a exact match.
```ts
// Example: Match '/path' regardless of the query parameters
import { invalidate } from '$app/navigation';
invalidate((url) => url.pathname === '/path');
```
```dts
function invalidate(
resource: string | URL | ((url: URL) => boolean),
keepState?: boolean
): Promise;
```
## invalidateAll
Use [`refreshAll`](/docs/kit/$app-navigation#refreshAll) instead. Unlike `invalidateAll`, `refreshAll` does not reset `page.state`.
Causes all `load` and `query` functions belonging to the currently active page to re-run. Returns a `Promise` that resolves when the page is subsequently updated.
Note that this resets `page.state` to an empty object. If you want to preserve `page.state` (for example when using [shallow routing](/docs/kit/shallow-routing)), use `refreshAll` instead.
```dts
function invalidateAll(): Promise;
```
## onNavigate
A lifecycle function that runs the supplied `callback` immediately before we navigate to a new URL except during full-page navigations.
If you return a `Promise`, SvelteKit will wait for it to resolve before completing the navigation. This allows you to — for example — use `document.startViewTransition`. Avoid promises that are slow to resolve, since navigation will appear stalled to the user.
If a function (or a `Promise` that resolves to a function) is returned from the callback, it will be called once the DOM has updated.
`onNavigate` must be called during a component initialization. It remains active as long as the component is mounted.
```dts
function onNavigate(
callback: (
navigation: OnNavigate
) => MaybePromise<(() => void) | void>
): void;
```
## preloadCode
Programmatically imports the code for routes that haven't yet been fetched.
Typically, you might call this to speed up subsequent navigation.
Takes a route ID such as `/about` or `/blog/[slug]`. Unlike pathnames, route IDs
are never prefixed with the app's [base path](/docs/kit/configuration#paths).
If you have a pathname rather than a route ID, you can convert it with
[`match`](/docs/kit/$app-paths#match) from `$app/paths`:
```js
// @errors: 7031
import { match } from '$app/paths';
import { preloadCode } from '$app/navigation';
const matched = await match('/blog/hello-world');
if (matched) await preloadCode(matched.id);
```
Unlike `preloadData`, this won't call `load` functions.
Returns a Promise that resolves when the modules have been imported.
```dts
function preloadCode(
id: import('$app/types').RouteId
): Promise;
```
## preloadData
Programmatically preloads the given page, which means
1. ensuring that the code for the page is loaded, and
2. calling the page's load function with the appropriate options.
This is the same behaviour that SvelteKit triggers when the user taps or mouses over an `` element with `data-sveltekit-preload-data`.
If the next navigation is to `href`, the values returned from load will be used, making navigation instantaneous.
Returns a Promise that resolves with the result of running the new route's `load` functions once the preload is complete.
```dts
function preloadData(href: string): Promise<
(
| {
type: 'loaded';
data: Record;
}
| {
type: 'redirect';
location: string;
}
| {
type: 'error';
error: App.Error;
}
) & {
status: number;
}
>;
```
## pushState
Use `goto(url, { state, shallow: true })` instead.
Programmatically create a new history entry with the given `page.state`. Used for [shallow routing](/docs/kit/shallow-routing).
```dts
function pushState(
url: string | URL,
state: App.PageState
): Promise;
```
## refreshAll
Causes all currently active remote functions to refresh, and all `load` functions belonging to the currently active page to re-run.
Returns a `Promise` that resolves when the page is subsequently updated.
```dts
function refreshAll(): Promise;
```
## replaceState
Use `goto(url, { state, shallow: true, replace: true })` instead.
Programmatically replace the current history entry with the given `page.state`. Used for [shallow routing](/docs/kit/shallow-routing).
```dts
function replaceState(
url: string | URL,
state: App.PageState
): Promise;
```
## snapshot
A lifecycle function that captures state before navigating and restores it when traversing history.
By default, the snapshot `id` is generated from the call site. Pass an explicit `id` to keep snapshots stable across deployments or distinguish multiple uses of a shared helper.
The optional `reset` callback runs on navigations where there is no captured value to restore, such as when a new history entry is created. Captured values are serialized with the app's transport hook.
`snapshot` must be called during a component initialization. It remains active as long as the component is mounted.
```dts
function snapshot(options: {
id?: string;
capture: () => T;
restore: (value: T) => void;
reset?: () => void;
}): void;
```
## AfterNavigate
The argument passed to [`afterNavigate`](/docs/kit/$app-navigation#afterNavigate) callbacks.
```dts
type AfterNavigate = (Navigation | NavigationEnter) & {
type: Exclude;
/**
* Since `afterNavigate` callbacks are called after a navigation completes, they will never be called with a navigation that unloads the page.
*/
willUnload: false;
};
```
## BeforeNavigate
The argument passed to [`beforeNavigate`](/docs/kit/$app-navigation#beforeNavigate) callbacks.
```dts
type BeforeNavigate = Navigation & {
/**
* Call this to prevent the navigation from starting.
*/
cancel: () => void;
};
```
## GotoOptions
```dts
interface GotoOptions {/*…*/}
```
```dts
replace?: boolean;
```
- default `false`
If `true`, replaces the current history entry rather than creating a new one.
```dts
replaceState?: boolean;
```
- deprecated Use `replace` instead.
```dts
shallow?: boolean;
```
- default `false`
If `true`, updates the URL and `page.state` without navigating.
```dts
reset?: boolean;
```
- default `true, or false when `shallow` is true`
If `true`, resets the scroll position (to the top of the page, or to the element
matching the URL's `#hash` if there is one) and resets focus (to the ``, or the
`autofocus` element if there is one) once the navigation completes.
If `false`, the current scroll position and focused element are left alone.
```dts
refreshAll?: boolean;
```
- default `false`
If `true`, reruns all `load` functions and queries of the page.
```dts
invalidate?: Array
boolean)>;
```
Causes any `load` functions to rerun if they depend on one of the URLs.
```dts
invalidateAll?: boolean;
```
- deprecated Use `refreshAll` instead.
```dts
state?: App.PageState;
```
An optional object that will be available as `page.state`.
```dts
persistState?: boolean;
```
- default `false`
If `true`, `page.state` will be restored after a full page reload.
## Navigation
```dts
type Navigation =
| NavigationExternal
| NavigationFormSubmit
| NavigationPopState
| NavigationLink;
```
## NavigationBase
```dts
interface NavigationBase {/*…*/}
```
```dts
type: NavigationType;
```
The type of navigation:
- `enter`: The app has hydrated/started
- `form`: The user submitted a `
`
- `goto`: Navigation was triggered by a `goto(...)` call or a redirect
- `leave`: The app is being left either because the tab is being closed or a navigation to a different document is occurring
- `link`: Navigation was triggered by a link click
- `popstate`: Navigation was triggered by back/forward navigation
```dts
shallow: boolean;
```
Whether this is a shallow navigation.
```dts
from: NavigationTarget | null;
```
Where navigation was triggered from
```dts
to: NavigationTarget | null;
```
Where navigation is going to/has gone to
```dts
willUnload: boolean;
```
Whether or not the navigation will result in the page being unloaded (i.e. not a client-side navigation).
```dts
complete: Promise
;
```
A promise that resolves once the navigation is complete, and rejects if the navigation
fails or is aborted. In the case of a `willUnload` navigation, the promise will never resolve
## NavigationEnter
The navigation that occurs when the app starts/hydrates
```dts
interface NavigationEnter extends NavigationBase {/*…*/}
```
```dts
type: 'enter';
```
```dts
delta?: undefined;
```
In case of a history back/forward navigation, the number of steps to go back/forward
```dts
event?: undefined;
```
Dispatched `Event` object when navigation occurred by `popstate` or `link`.
## NavigationExternal
```dts
type NavigationExternal = NavigationGoto | NavigationLeave;
```
## NavigationFormSubmit
A navigation triggered by a ``
```dts
interface NavigationFormSubmit extends NavigationBase {/*…*/}
```
```dts
event: SubmitEvent;
```
The `SubmitEvent` that caused the navigation
## NavigationGoto
A navigation triggered by a `goto(...)` call or a redirect
```dts
interface NavigationGoto extends NavigationBase {/*…*/}
```
## NavigationLeave
A navigation triggered by the tab being closed, or the user navigating to a different document
```dts
interface NavigationLeave extends NavigationBase {/*…*/}
```
```dts
type: 'leave';
```
## NavigationLink
A navigation triggered by a link click
```dts
interface NavigationLink extends NavigationBase {/*…*/}
```
```dts
event: PointerEvent;
```
The `PointerEvent` that caused the navigation
## NavigationPopState
A navigation triggered by back/forward navigation
```dts
interface NavigationPopState extends NavigationBase {/*…*/}
```
```dts
type: 'popstate';
```
```dts
delta: number;
```
In case of a history back/forward navigation, the number of steps to go back/forward
```dts
event: PopStateEvent;
```
The `PopStateEvent` that caused the navigation
## NavigationTarget
Information about the target of a specific navigation.
```dts
interface NavigationTarget<
Params extends AppLayoutParams<'/'> =
AppLayoutParams<'/'>,
RouteId extends AppRouteId | null = AppRouteId | null
> {/*…*/}
```
```dts
params: Params | null;
```
Parameters of the target page - e.g. for a route like `/blog/[slug]`, a `{ slug: string }` object.
Is `null` if the target is not part of the SvelteKit app (could not be resolved to a route).
```dts
route: {/*…*/}
```
Info about the target route
```dts
id: RouteId | null;
```
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.
```dts
url: URL;
```
The URL that is navigated to
```dts
scroll: { x: number; y: number } | null;
```
The scroll position associated with this navigation.
For the `from` target, this is the scroll position at the moment of navigation.
For the `to` target, this represents the scroll position that will be or was restored:
- In `beforeNavigate` and `onNavigate`, this is only available for `popstate` navigations (back/forward button)
and will be `null` for other navigation types, since the final scroll position isn't known
ahead of time.
- In `afterNavigate`, this is always the scroll position that was applied after the navigation
completed.
## NavigationType
- `enter`: The app has hydrated/started
- `form`: The user submitted a ` `
- `goto`: Navigation was triggered by a `goto(...)` call or a redirect
- `leave`: The app is being left either because the tab is being closed or a navigation to a different document is occurring
- `link`: Navigation was triggered by a link click
- `popstate`: Navigation was triggered by back/forward navigation
```dts
type NavigationType =
| 'enter'
| 'form'
| 'leave'
| 'link'
| 'goto'
| 'popstate';
```
## OnNavigate
The argument passed to [`onNavigate`](/docs/kit/$app-navigation#onNavigate) callbacks.
```dts
type OnNavigate = Navigation & {
type: Exclude;
/**
* Since `onNavigate` callbacks are called immediately before a client-side navigation, they will never be called with a navigation that unloads the page.
*/
willUnload: false;
};
```
# $app/paths
```js
// @noErrors
import { asset, match, resolve } from '$app/paths';
```
## asset
Available since 2.26
Resolve the URL of an asset in your `static` directory, by prefixing it with [`config.paths.assets`](/docs/kit/configuration#paths) if configured, or otherwise by prefixing it with the base path.
During server rendering, the base path is relative and depends on the page currently being rendered.
```svelte
```
```dts
function asset(file: AssetPath): string;
```
## match
Available since 2.52.0
Match a path or URL to a route ID and extracts any parameters.
```js
// @errors: 7031
import { match } from '$app/paths';
const route = await match('blog/hello-world');
if (route?.id === '/blog/[slug]') {
const slug = route.params.slug;
const response = await fetch(`/api/posts/${slug}`);
const post = await response.json();
}
```
```dts
function match(url: URL | string): Promise<
| {
[K in RouteId]: {
id: K;
params: RouteParams;
};
}[RouteId]
| null
>;
```
## resolve
Available since 2.26
Resolve a pathname by prefixing it with the base path, if any, or resolve a route ID by populating dynamic segments with parameters.
During server rendering, the base path is relative and depends on the page currently being rendered.
```js
// @errors: 7031
import { resolve } from '$app/paths';
// using a pathname
const resolved = resolve(`blog/hello-world`);
// using a route ID plus parameters
const resolved = resolve('/blog/[slug]', {
slug: 'hello-world'
});
```
```dts
function resolve<
T extends
| RouteIdWithSearchOrHash
| PathnameWithSearchOrHash
>(...args: ResolveArgs): ResolvedPathname;
```
> `base`, `assets`, and `resolveRoute` were removed in 3.0
# $app/server
```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;
```
## 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
>;
}
```
# $app/service-worker
This module can only be imported in service workers.
```js
// @noErrors
import { self } from '$app/service-worker';
```
## self
The execution context of a service worker. This export exists to make it easier to
use service workers with the correct types, provided the importing module is governed
by a `tsconfig.json` that extends [`$app/tsconfig/service-worker`](/docs/kit/$app-tsconfig-service-worker).
```dts
const self: ServiceWorkerGlobalScope;
```
# $app/state
SvelteKit makes three read-only state objects available via the `$app/state` module — `page`, `navigating` and `updated`.
```js
// @noErrors
import { navigating, page, updated } from '$app/state';
```
## navigating
A read-only object representing an in-progress navigation, with `from`, `to`, `type` and (if `type === 'popstate'`) `delta` properties.
Values are `null` when no navigation is occurring, or during server rendering.
```dts
const navigating:
| Navigation
| {
from: null;
to: null;
type: null;
willUnload: null;
delta: null;
complete: null;
};
```
## page
A read-only reactive object with information about the current page, serving several use cases:
- retrieving the combined `data` of all pages/layouts anywhere in your component tree (also see [loading data](/docs/kit/load))
- retrieving the current value of the `form` prop anywhere in your component tree (also see [form actions](/docs/kit/form-actions))
- retrieving the page state that was set through `goto` (also see [goto](/docs/kit/$app-navigation#goto) and [shallow routing](/docs/kit/shallow-routing))
- retrieving metadata such as the URL you're on, the current route and its parameters, the target of a shallow navigation, and whether or not there was an error
```svelte
Currently at {page.url.pathname}
{#if page.error}
Problem detected
{:else}
All systems operational
{/if}
```
Changes to `page` are available exclusively with runes. (The legacy reactivity syntax will not reflect any changes)
```svelte
```
On the server, values can only be read during rendering (in other words _not_ in e.g. `load` functions). In the browser, the values can be read at any time.
```dts
const page: Page;
```
## updated
A read-only reactive value that's initially `false`. SvelteKit checks for new versions on data, remote, and form action responses (via the `x-sveltekit-version` header), when the tab regains focus or becomes visible, and on a poll interval (see [`version.pollInterval`](/docs/kit/configuration#version)). `updated.current` is set to `true` when a new version is detected. `updated.check()` will force an immediate check, regardless of polling.
```dts
const updated: {
get current(): boolean;
check(): Promise;
};
```
## Page
The shape of the [`page`](/docs/kit/$app-state#page) reactive object.
```dts
interface Page<
Params extends AppLayoutParams<'/'> =
AppLayoutParams<'/'>,
RouteId extends AppRouteId | null = AppRouteId | null
> {/*…*/}
```
```dts
url: ReadonlyURL & { readonly pathname: ResolvedPathname | (string & {}) };
```
The URL of the current page.
```dts
params: Params;
```
The parameters of the current page - e.g. for a route like `/blog/[slug]`, a `{ slug: string }` object.
```dts
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.
```dts
status: number;
```
HTTP status code of the current page.
```dts
error: App.Error | null;
```
The error object of the current page, if any. Filled from the `handleError` hooks.
```dts
data: App.PageData & Record
;
```
The merged result of all data from all `load` functions on the current page. You can type a common denominator through `App.PageData`.
```dts
state: App.PageState;
```
The page state, which can be manipulated using [`goto`](/docs/kit/$app-navigation#goto) from `$app/navigation`.
```dts
shallow: {
/** Parameters of the target route, or `null` if the URL does not resolve to a route. */
params: AppLayoutParams<'/'> | null;
/** Info about the target route, or `null` if the URL does not resolve to a route. */
route: { id: AppRouteId } | null;
/** The normalized URL passed to `goto(..., { shallow: true })`. */
url: ReadonlyURL;
} | null;
```
Information about the target of the current shallow navigation, or `null` if no shallow navigation has occurred.
```dts
form: any;
```
Filled only after a form submission. See [form actions](/docs/kit/form-actions) for more info.
## ReadonlyURL
```dts
type ReadonlyURL = Readonly<
Omit & {
searchParams: ReadonlyURLSearchParams;
}
>;
```
## ReadonlyURLSearchParams
```dts
type ReadonlyURLSearchParams = Omit<
URLSearchParams,
'set' | 'append' | 'delete' | 'sort'
>;
```
# $app/tsconfig
This module contains TypeScript configuration tailored for your app. Your own config should extend it — a typical `tsconfig.json` looks like this:
```json
/// file: tsconfig.json
{
"extends": "$app/tsconfig",
"include": ["src", "test"],
"exclude": ["src/service-worker"]
}
```
You can extend this configuration with your own `compilerOptions`. Overriding the following properties may cause things to break — SvelteKit will warn you if this happens:
- `paths` — this is derived from the (deprecated) [`alias`](configuration#alias) config option, together with any [subpath imports](https://nodejs.org/api/packages.html#subpath-imports) specified in your `package.json`, to align behaviour between Vite and TypeScript. Ideally, configure subpath imports rather than using `paths` directly
- `types` — your app needs to be able to 'see' generated module declarations for things like [environment variables](environment-variables), and as such this array must include `"$app/types"`
- `isolatedModules` — must be `true`, as Vite compiles modules one at a time
- `verbatimModuleSyntax` — must be `true`, so that you can safely use type imports in `.svelte` files
Note that the example configuration above excludes `src/service-worker`, because service workers need to be in their own TypeScript project. If you are using a service worker, create a `src/service-worker/tsconfig.json` that extends [`$app/tsconfig/service-worker`]($app-tsconfig-service-worker).
# $app/tsconfig/service-worker
This module contains TypeScript configuration tailored for your service worker:
```json
/// file: src/service-worker/tsconfig.json
{
"extends": "$app/tsconfig/service-worker"
}
```
You can extend this configuration with your own `compilerOptions`, adhering to the same restrictions as [`$app/tsconfig`]($app-tsconfig).
# $app/types
This module contains generated types for the routes in your app.
Available since 2.26
```js
// @noErrors
import type { RouteId, PageRouteId, EndpointRouteId, RouteParams, LayoutParams } from '$app/types';
```
## AssetPath
A union of all the filenames of assets contained in your `static` directory, relative to the `base` path.
```dts
type AssetPath = 'favicon.png' | 'robots.txt' | (string & {});
```
## RouteId
A union of all the route IDs in your app — the union of `PageRouteId` and `EndpointRouteId`. Used for `page.route.id` and `event.route.id`.
```dts
type RouteId = '/' | '/my-route' | '/my-other-route/[param]' | '/my-endpoint';
```
## PageRouteId
A union of the route IDs in your app that have a `+page`.
A route ID can be in both `PageRouteId` and `EndpointRouteId`, if its directory contains both a `+page` and a `+server`. In the example below, `/my-route` has both.
```dts
type PageRouteId = '/' | '/my-route' | '/my-other-route/[param]';
```
## EndpointRouteId
A union of the route IDs in your app that have a `+server`.
A route ID can be in both `PageRouteId` and `EndpointRouteId`, if its directory contains both a `+page` and a `+server`. In the example below, `/my-route` has both.
```dts
type EndpointRouteId = '/my-route' | '/my-endpoint';
```
## Path
A union of all valid paths in your app, relative to the `base` path.
```dts
type Path = '' | 'my-route' | `my-other-route/${string}` & {};
```
## ResolvedPathname
Similar to `Path`, but prefixed with a [base path](configuration#paths). Used for `page.url.pathname`.
```dts
type ResolvedPathname = `${'' | `/${string}`}/` | `${'' | `/${string}`}/my-route` | `${'' | `/${string}`}/my-other-route/${string}` | {};
```
## RouteParams
A utility for getting the parameters associated with a given route.
```ts
// @errors: 2552
type BlogParams = RouteParams<'/blog/[slug]'>; // { slug: string }
```
```dts
type RouteParams = { /* generated */ } | Record;
```
## LayoutParams
A utility for getting the parameters associated with a given layout, which is similar to `RouteParams` but also includes optional parameters for any child route. It accepts the route ID of any directory containing a layout, including layout-only directories that are not part of `RouteId`.
```dts
type LayoutParams = { /* generated */ };
```
# #lib
When scaffolding a new SvelteKit project through the [`sv` CLI](/docs/cli/overview), it automatically creates a `#lib` import alias for your `src/lib` directory, by adding the following to your `package.json`:
```json
{
"imports": {
"#lib": "./src/lib/index.js",
"#lib/*": "./src/lib/*"
}
}
```
The `#` prefix leverages Node's built-in [subpath imports](https://nodejs.org/api/packages.html#subpath-imports) feature, which reserves `#` for package-internal aliases. Vite and TypeScript both resolve these natively.
> Previously, this alias was `$lib` and was automatically configured by SvelteKit. It is now `#lib` and must be declared in your `package.json` `imports` field. `import { foo } from '$lib/foo.js'` becomes `import { foo } from '#lib/foo.js'`.
```svelte
A reusable component
```
```svelte
```
# Configuration
Your project's configuration lives in the `vite.config.js` file at the root of your project. You can pass your configuration to the `sveltekit` plugin, along with the Svelte compiler options:
```js
// TODO: remove this and install @sveltejs/adapter-auto in svelte.dev to get the types
// @filename: ambient.d.ts
declare module '@sveltejs/adapter-auto' {
const plugin: () => import('@sveltejs/kit').Adapter;
export default plugin;
}
// @filename: index.js
// ---cut---
/// file: vite.config.js
import adapter from '@sveltejs/adapter-auto';
import { sveltekit } from '@sveltejs/kit/vite';
import { defineConfig } from 'vite';
export default defineConfig({
plugins: [
sveltekit({
compilerOptions: {
experimental: {
async: true
}
},
adapter: adapter(),
experimental: {
remoteFunctions: true
}
})
]
});
```
As well as SvelteKit, the plugin options are used by other tooling that integrates with Svelte such as editor extensions.
Any options that don't belong to SvelteKit are passed through to [`vite-plugin-svelte`](https://github.com/sveltejs/vite-plugin-svelte/blob/main/docs/config.md), so you can set options like `inspector` here too. The `experimental` namespace is shared — SvelteKit reads its own flags and forwards the rest.
> Prior to SvelteKit 3, config lived in a `svelte.config.js` file, which is no longer supported. The ability to configure SvelteKit via `vite.config.js` was added in version 2.62.
## KitConfig
An extension of [`vite-plugin-svelte`'s options](https://github.com/sveltejs/vite-plugin-svelte/blob/main/docs/config.md#config-file).
## adapter
- default `undefined`
Your [adapter](/docs/kit/adapters) is run when executing `vite build`. It determines how the output is converted for different platforms.
## alias
- deprecated
- default `{}`
An object containing zero or more aliases used to replace values in `import` statements. These aliases are automatically passed to Vite and TypeScript.
This option is deprecated. Use [subpath imports](/docs/kit/$lib) instead.
## appDir
- default `"_app"`
The directory where SvelteKit keeps its stuff, including static assets (such as JS and CSS) and internally-used routes.
If `paths.assets` is specified, there will be two app directories — `${paths.assets}/${appDir}` and `${paths.base}/${appDir}`.
## csp
[Content Security Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy) configuration. CSP helps to protect your users against cross-site scripting (XSS) attacks, by limiting the places resources can be loaded from. For example, a configuration like this...
```js
// @errors: 7031
/// file: vite.config.js
import { sveltekit } from '@sveltejs/kit/vite';
import { defineConfig } from 'vite';
export default defineConfig({
plugins: [
sveltekit({
csp: {
directives: {
'script-src': ['self']
},
// must be specified with either the `report-uri` or `report-to` directives, or both
reportOnly: {
'script-src': ['self'],
'report-uri': ['/']
}
}
})
]
});
```
...would prevent scripts loading from external sites. SvelteKit will augment the specified directives with nonces or hashes (depending on `mode`) for any inline styles and scripts it generates.
To add a nonce for scripts and links manually included in `src/app.html`, you may use the placeholder `%sveltekit.nonce%` (for example `
```