SvelteKit • Reference
@sveltejs/kit
On this page
- Adapter
- LoadProperties
- AwaitedActions
- ActionFailure
- Builder
- Config
- Cookies
- Emulator
- KitConfig
- Handle
- HandleServerError
- HandleValidationError
- HandleClientError
- HandleFetch
- ServerInit
- ClientInit
- Reroute
- Transport
- Transporter
- Load
- LoadEvent
- NavigationEvent
- NavigationTarget
- NavigationType
- NavigationBase
- NavigationEnter
- NavigationExternal
- NavigationGoto
- NavigationLeave
- NavigationFormSubmit
- NavigationPopState
- NavigationLink
- Navigation
- BeforeNavigate
- OnNavigate
- AfterNavigate
- Page
- ParamMatcher
- RequestedEntry
- LiveRequestedEntry
- QueryRequestedResult
- LiveQueryRequestedResult
- RequestedResult
- RequestEvent
- RequestHandler
- ResolveOptions
- RouteDefinition
- Server
- ServerInitOptions
- SSRManifest
- ServerLoad
- ServerLoadEvent
- Action
- Actions
- ActionResult
- HttpError
- Redirect
- SubmitFunction
- Snapshot
- RemoteFormFieldType
- RemoteFormFieldValue
- RemoteFormField
- RemoteFormFields
- RemoteFormInput
- RemoteFormIssue
- InvalidField
- ValidationError
- RemoteFormEnhanceInstance
- RemoteFormEnhanceCallback
- RemoteForm
- RemoteCommand
- RemoteQueryUpdate
- RemoteResource
- RemoteQuery
- RemoteLiveQuery
- RemoteQueryOverride
- RemotePrerenderFunction
- RemoteQueryFunction
- RemoteLiveQueryFunction
- EnvVarConfig
- PrerenderOption
- error
- isHttpError
- redirect
- isRedirect
- json
- text
- fail
- isActionFailure
- invalid
- isValidationError
- normalizeUrl
- LessThan
- NumericRange
- VERSION
- Private types
- Adapter
- LoadProperties
- AwaitedActions
- ActionFailure
- Builder
- Config
- Cookies
- Emulator
- KitConfig
- Handle
- HandleServerError
- HandleValidationError
- HandleClientError
- HandleFetch
- ServerInit
- ClientInit
- Reroute
- Transport
- Transporter
- Load
- LoadEvent
- NavigationEvent
- NavigationTarget
- NavigationType
- NavigationBase
- NavigationEnter
- NavigationExternal
- NavigationGoto
- NavigationLeave
- NavigationFormSubmit
- NavigationPopState
- NavigationLink
- Navigation
- BeforeNavigate
- OnNavigate
- AfterNavigate
- Page
- ParamMatcher
- RequestedEntry
- LiveRequestedEntry
- QueryRequestedResult
- LiveQueryRequestedResult
- RequestedResult
- RequestEvent
- RequestHandler
- ResolveOptions
- RouteDefinition
- Server
- ServerInitOptions
- SSRManifest
- ServerLoad
- ServerLoadEvent
- Action
- Actions
- ActionResult
- HttpError
- Redirect
- SubmitFunction
- Snapshot
- RemoteFormFieldType
- RemoteFormFieldValue
- RemoteFormField
- RemoteFormFields
- RemoteFormInput
- RemoteFormIssue
- InvalidField
- ValidationError
- RemoteFormEnhanceInstance
- RemoteFormEnhanceCallback
- RemoteForm
- RemoteCommand
- RemoteQueryUpdate
- RemoteResource
- RemoteQuery
- RemoteLiveQuery
- RemoteQueryOverride
- RemotePrerenderFunction
- RemoteQueryFunction
- RemoteLiveQueryFunction
- EnvVarConfig
- PrerenderOption
- error
- isHttpError
- redirect
- isRedirect
- json
- text
- fail
- isActionFailure
- invalid
- isValidationError
- normalizeUrl
- LessThan
- NumericRange
- VERSION
import {
Action,
ActionFailure,
ActionResult,
Actions,
Adapter,
AfterNavigate,
AwaitedActions,
BeforeNavigate,
Builder,
ClientInit,
Config,
Cookies,
Emulator,
EnvVarConfig,
error,
fail,
Handle,
HandleClientError,
HandleFetch,
HandleServerError,
HandleValidationError,
HttpError,
invalid,
InvalidField,
isActionFailure,
isHttpError,
isRedirect,
isValidationError,
json,
KitConfig,
LessThan,
LiveQueryRequestedResult,
LiveRequestedEntry,
Load,
LoadEvent,
LoadProperties,
Navigation,
NavigationBase,
NavigationEnter,
NavigationEvent,
NavigationExternal,
NavigationFormSubmit,
NavigationGoto,
NavigationLeave,
NavigationLink,
NavigationPopState,
NavigationTarget,
NavigationType,
normalizeUrl,
NumericRange,
OnNavigate,
Page,
ParamMatcher,
PrerenderOption,
QueryRequestedResult,
redirect,
Redirect,
RemoteCommand,
RemoteForm,
RemoteFormEnhanceCallback,
RemoteFormEnhanceInstance,
RemoteFormField,
RemoteFormFields,
RemoteFormFieldType,
RemoteFormFieldValue,
RemoteFormInput,
RemoteFormIssue,
RemoteLiveQuery,
RemoteLiveQueryFunction,
RemotePrerenderFunction,
RemoteQuery,
RemoteQueryFunction,
RemoteQueryOverride,
RemoteQueryUpdate,
RemoteResource,
RequestedEntry,
RequestedResult,
RequestEvent,
RequestHandler,
Reroute,
ResolveOptions,
RouteDefinition,
Server,
ServerInit,
ServerInitOptions,
ServerLoad,
ServerLoadEvent,
Snapshot,
SSRManifest,
SubmitFunction,
text,
Transport,
Transporter,
ValidationError,
VERSION
} from '@sveltejs/kit';Adapter
Adapters are responsible for taking the production build and turning it into something that can be deployed to a platform of your choosing.
export interface Adapter {/*…*/}name: string;The name of the adapter, using for logging. Will typically correspond to the package name.
adapt: (builder: Builder) => MaybePromise<void>;This function is called after SvelteKit has built your app.
supports?: {
/**
* Test support for `read` from `$app/server`.
* @param details.config The merged adapter-specific route config exported from the route with `export const config`
*/
read?: (details: { config: any; route: { id: string } }) => boolean;
/**
* Test support for `instrumentation.server.js`. To pass, the adapter must support running `instrumentation.server.js` prior to the application code.
* @since 2.31.0
*/
instrumentation?: () => boolean;
};Checks called during dev and build to determine whether specific features will work in production with this adapter.
emulate?: () => MaybePromise<Emulator>;Creates an Emulator, which allows the adapter to influence the environment
during dev, build and prerendering.
LoadProperties
export type type LoadProperties<input extends Record<string, any> | void> = input extends void ? undefined : input extends Record<string, any> ? input : unknowntype LoadProperties<input extends Record<string, any> | void> = input extends void ? undefined : input extends Record<string, any> ? input : unknownLoadProperties<function (type parameter) input in type LoadProperties<input extends Record<string, any> | void>function (type parameter) input in type LoadProperties<input extends Record<string, any> | void>input extends type Record<K extends keyof any, T> = { [P in K]: T; }Construct a type with a set of properties K of type T
type Record<K extends keyof any, T> = { [P in K]: T; }Construct a type with a set of properties K of type T
Record<string, any> | void> = function (type parameter) input in type LoadProperties<input extends Record<string, any> | void>function (type parameter) input in type LoadProperties<input extends Record<string, any> | void>input extends void
? undefined // needs to be undefined, because void will break intellisense
: function (type parameter) input in type LoadProperties<input extends Record<string, any> | void>function (type parameter) input in type LoadProperties<input extends Record<string, any> | void>input extends type Record<K extends keyof any, T> = { [P in K]: T; }Construct a type with a set of properties K of type T
type Record<K extends keyof any, T> = { [P in K]: T; }Construct a type with a set of properties K of type T
Record<string, any>
? function (type parameter) input in type LoadProperties<input extends Record<string, any> | void>function (type parameter) input in type LoadProperties<input extends Record<string, any> | void>input
: unknown;AwaitedActions
export type AwaitedActions<T extends Record<string, (...args: any) => any>> = OptionalUnion<
{
[Key in keyof T]: UnpackValidationError<Awaited<ReturnType<T[Key]>>>;
}[keyof T]
>;ActionFailure
export interface interface ActionFailure<T = undefined>interface ActionFailure<T = undefined>ActionFailure<function (type parameter) T in ActionFailure<T = undefined>function (type parameter) T in ActionFailure<T = undefined>T = undefined> {/*…*/}status: number;data: T;[uniqueSymbol]: true;Builder
This object is passed to the adapt function of adapters.
It contains various methods and properties that are useful for adapting the app.
export interface Builder {/*…*/}log: Logger;Print messages to the console. log.info and log.minor are silent unless Vite's logLevel is info.
rimraf: (dir: string) => void;Remove dir and all its contents.
mkdirp: (dir: string) => void;Create dir and any required parent directories.
config: ValidatedConfig;The fully resolved Svelte config.
prerendered: Prerendered;Information about prerendered pages and assets, if any.
routes: RouteDefinition[];An array of all routes (including prerendered)
createEntries: (fn: (route: RouteDefinition) => AdapterEntry) => Promise<void>;Create separate functions that map to one or more routes of your app.
findServerAssets: (routes: RouteDefinition[]) => string[];Find all the assets imported by server files belonging to routes
generateFallback: (dest: stringdest: stringdest: string) => var Promise: PromiseConstructorRepresents the completion of an asynchronous operation
var Promise: PromiseConstructorRepresents the completion of an asynchronous operation
Promise<void>;Generate a fallback page for a static webserver to use when no route is matched. Useful for single-page apps.
generateEnvModule: () => void;Generate a module exposing build-time environment variables as $env/dynamic/public or $app/env/public if the app uses it.
generateManifest: (opts: { relativePath: string; routes?: RouteDefinition[] }) => string;Generate a server-side manifest to initialise the SvelteKit server with.
getBuildDirectory: (name: string) => string;Resolve a path to the name directory inside outDir, e.g. /path/to/.svelte-kit/my-adapter.
getClientDirectory: () => string;Get the fully resolved path to the directory containing client-side assets, including the contents of your static directory.
getServerDirectory: () => string;Get the fully resolved path to the directory containing server-side code.
getAppPath: () => string;Get the application path including any configured base path, e.g. my-base-path/_app.
writeClient: (dest: string) => string[];Write client assets to dest.
writePrerendered: (dest: string) => string[];Write prerendered files to dest.
writeServer: (dest: string) => string[];Write server-side code to dest.
copy: (
from: string,
to: string,
opts?: {
filter?(basename: string): boolean;
replace?: Record<string, string>;
}
) => string[];Copy a file or directory.
hasServerInstrumentationFile: () => boolean;Check if the server instrumentation file exists.
instrument: (args: {
entrypoint: string;
instrumentation: string;
start?: string;
module?:
| {
exports: string[];
}
| {
generateText: (args: { instrumentation: string; start: string }) => string;
};
}) => void;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
tlaisfalse, OTEL auto-instrumentation may not work properly. Use it if your environment supports it. - Use
hasServerInstrumentationFileto check if the user has a server instrumentation file; if they don't, you shouldn't do this.
compress: (directory: stringdirectory: stringdirectory: string) => var Promise: PromiseConstructorRepresents the completion of an asynchronous operation
var Promise: PromiseConstructorRepresents the completion of an asynchronous operation
Promise<void>;Compress files in directory with gzip and brotli, where appropriate. Generates .gz and .br files alongside the originals.
Config
An extension of vite-plugin-svelte's options.
export interface Config extends SvelteConfig {/*…*/}kit?: KitConfig;SvelteKit options.
[key: string]: any;Any additional options required by tooling that integrates with Svelte.
Cookies
export interface Cookies {/*…*/}get: (name: string, opts?: import('cookie').CookieParseOptions) => string | undefined;Gets a cookie that was previously set with cookies.set, or from the request headers.
getAll: (opts?: import('cookie').CookieParseOptions) => Array<{ name: string; value: string }>;Gets all cookies that were previously set with cookies.set, or from the request headers.
set: (
name: string,
value: string,
opts: import('cookie').CookieSerializeOptions & { path: string }
) => void;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 and secure options are true by default (except on http://localhost, where secure is false), and must be explicitly disabled if you want cookies to be readable by client-side JavaScript and/or transmitted over HTTP. The sameSite option defaults to lax.
You must specify a path for the cookie. In most cases you should explicitly set path: '/' to make the cookie available throughout your app. You can use relative paths, or set path: '' to make the cookie only available on the current path and its children
delete: (name: string, opts: import('cookie').CookieSerializeOptions & { path: string }) => void;Deletes a cookie by setting its value to an empty string and setting the expiry date in the past.
You must specify a path for the cookie. In most cases you should explicitly set path: '/' to make the cookie available throughout your app. You can use relative paths, or set path: '' to make the cookie only available on the current path and its children
serialize: (
name: string,
value: string,
opts: import('cookie').CookieSerializeOptions & { path: string }
) => string;Serialize a cookie name-value pair into a Set-Cookie header string, but don't apply it to the response.
The httpOnly and secure options are true by default (except on http://localhost, where secure is false), and must be explicitly disabled if you want cookies to be readable by client-side JavaScript and/or transmitted over HTTP. The sameSite option defaults to lax.
You must specify a path for the cookie. In most cases you should explicitly set path: '/' to make the cookie available throughout your app. You can use relative paths, or set path: '' to make the cookie only available on the current path and its children
Emulator
A collection of functions that influence the environment during dev, build and prerendering
export interface Emulator {/*…*/}platform?(details: { config: any; prerender: PrerenderOption }): MaybePromise<App.Platform>;A function that is called with the current route config and prerender option
and returns an App.Platform object
KitConfig
export interface KitConfig {/*…*/}adapter?: Adapter;Your adapter is run when executing vite build. It determines how the output is converted for different platforms.
alias?: Record<string, string>;An object containing zero or more aliases used to replace values in import statements. These aliases are automatically passed to Vite and TypeScript.
/// type: import('@sveltejs/kit').Config
const const config: {
kit: {
alias: {
'my-file': string;
'my-directory': string;
'my-directory/*': string;
};
};
}
const config: {
kit: {
alias: {
'my-file': string;
'my-directory': string;
'my-directory/*': string;
};
};
}
config = {
kit: {
alias: {
'my-file': string;
'my-directory': string;
'my-directory/*': string;
};
}
kit: {
alias: {
'my-file': string;
'my-directory': string;
'my-directory/*': string;
};
}
kit: {
alias: {
'my-file': string;
'my-directory': string;
'my-directory/*': string;
}
alias: {
'my-file': string;
'my-directory': string;
'my-directory/*': string;
}
alias: {
// this will match a file
'my-file': 'path/to/my-file.js',
// this will match a directory and its contents
// (`my-directory/x` resolves to `path/to/my-directory/x`)
'my-directory': 'path/to/my-directory',
// an alias ending /* will only match
// the contents of a directory, not the directory itself
'my-directory/*': 'path/to/my-directory/*'
}
}
};You will need to run
npm run devto have SvelteKit automatically generate the required alias configuration injsconfig.jsonortsconfig.json.
appDir?: string;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?: {
/**
* Whether to use hashes or nonces to restrict `<script>` and `<style>` elements. `'auto'` will use hashes for prerendered pages, and nonces for dynamically rendered pages.
*/
mode?: 'hash' | 'nonce' | 'auto';
/**
* Directives that will be added to `Content-Security-Policy` headers.
*/
directives?: CspDirectives;
/**
* Directives that will be added to `Content-Security-Policy-Report-Only` headers.
*/
reportOnly?: CspDirectives;
};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...
/// type: import('@sveltejs/kit').Config
const const config: {
kit: {
csp: {
directives: {
'script-src': string[];
};
reportOnly: {
'script-src': string[];
'report-uri': string[];
};
};
};
}
const config: {
kit: {
csp: {
directives: {
'script-src': string[];
};
reportOnly: {
'script-src': string[];
'report-uri': string[];
};
};
};
}
config = {
kit: {
csp: {
directives: {
'script-src': string[];
};
reportOnly: {
'script-src': string[];
'report-uri': string[];
};
};
}
kit: {
csp: {
directives: {
'script-src': string[];
};
reportOnly: {
'script-src': string[];
'report-uri': string[];
};
};
}
kit: {
csp: {
directives: {
'script-src': string[];
};
reportOnly: {
'script-src': string[];
'report-uri': string[];
};
}
csp: {
directives: {
'script-src': string[];
};
reportOnly: {
'script-src': string[];
'report-uri': string[];
};
}
csp: {
directives: {
'script-src': string[];
}
directives: {
'script-src': string[];
}
directives: {
'script-src': ['self']
},
// must be specified with either the `report-uri` or `report-to` directives, or both
reportOnly: {
'script-src': string[];
'report-uri': string[];
}
reportOnly: {
'script-src': string[];
'report-uri': string[];
}
reportOnly: {
'script-src': ['self'],
'report-uri': ['/']
}
}
}
};
export default const config: {
kit: {
csp: {
directives: {
'script-src': string[];
};
reportOnly: {
'script-src': string[];
'report-uri': string[];
};
};
};
}
const config: {
kit: {
csp: {
directives: {
'script-src': string[];
};
reportOnly: {
'script-src': string[];
'report-uri': string[];
};
};
};
}
config;...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 <script nonce="%sveltekit.nonce%">).
When pages are prerendered, the CSP header is added via a <meta http-equiv> tag (note that in this case, frame-ancestors, report-uri and sandbox directives will be ignored).
When
modeis'auto', SvelteKit will use nonces for dynamically rendered pages and hashes for prerendered pages. Using nonces with prerendered pages is insecure and therefore forbidden.
Note that most Svelte transitions work by creating an inline
<style>element. If you use these in your app, you must either leave thestyle-srcdirective unspecified or addunsafe-inline.
If this level of configuration is insufficient and you have more dynamic requirements, you can use the handle hook to roll your own CSP.
csrf?: {
/**
* Whether to check the incoming `origin` header for `POST`, `PUT`, `PATCH`, or `DELETE` form submissions and verify that it matches the server's origin.
*
* To allow people to make `POST`, `PUT`, `PATCH`, or `DELETE` requests with a `Content-Type` of `application/x-www-form-urlencoded`, `multipart/form-data`, or `text/plain` to your app from other origins, you will need to disable this option. Be careful!
* @default true
* @deprecated Use `trustedOrigins: ['*']` instead
*/
checkOrigin?: boolean;
/**
* An array of origins that are allowed to make cross-origin form submissions to your app.
*
* Each origin should be a complete origin including protocol (e.g., `https://payment-gateway.com`).
* This is useful for allowing trusted third-party services like payment gateways or authentication providers to submit forms to your app.
*
* If the array contains `'*'`, all origins will be trusted. This is generally not recommended!
*
* > [!NOTE] Only add origins you completely trust, as this bypasses CSRF protection for those origins.
*
* CSRF checks only apply in production, not in local development.
* @default []
* @example ['https://checkout.stripe.com', 'https://accounts.google.com']
*/
trustedOrigins?: string[];
};Protection against cross-site request forgery (CSRF) attacks.
embedded?: boolean;Whether or not the app is embedded inside a larger app. If true, SvelteKit will add its event listeners related to navigation etc on the parent of %sveltekit.body% instead of window, and will pass params from the server rather than inferring them from location.pathname.
Note that it is generally not supported to embed multiple SvelteKit apps on the same page and use client-side SvelteKit features within them (things such as pushing to the history state assume a single instance).
env?: {
/**
* The directory to search for `.env` files.
* @default "."
*/
dir?: string;
/**
* A prefix that signals that an environment variable is safe to expose to client-side code. See [`$env/static/public`](https://svelte.dev/docs/kit/$env-static-public) and [`$env/dynamic/public`](https://svelte.dev/docs/kit/$env-dynamic-public). Note that Vite's [`envPrefix`](https://vitejs.dev/config/shared-options.html#envprefix) must be set separately if you are using Vite's environment variable handling - though use of that feature should generally be unnecessary.
* @default "PUBLIC_"
*/
publicPrefix?: string;
/**
* A prefix that signals that an environment variable is unsafe to expose to client-side code. Environment variables matching neither the public nor the private prefix will be discarded completely. See [`$env/static/private`](https://svelte.dev/docs/kit/$env-static-private) and [`$env/dynamic/private`](https://svelte.dev/docs/kit/$env-dynamic-private).
* @default ""
* @since 1.21.0
*/
privatePrefix?: string;
};Environment variable configuration
experimental?: {
/**
* Whether to enable explicit environment variables using `src/env.js` or `src/env.ts`.
* @since 2.63.0
* @default false
*/
explicitEnvironmentVariables?: boolean;
/**
* Options for enabling server-side [OpenTelemetry](https://opentelemetry.io/) tracing for SvelteKit operations including the [`handle` hook](https://svelte.dev/docs/kit/hooks#handle), [`load` functions](https://svelte.dev/docs/kit/load), [form actions](https://svelte.dev/docs/kit/form-actions), and [remote functions](https://svelte.dev/docs/kit/remote-functions).
* @default { server: false, serverFile: false }
* @since 2.31.0
*/
tracing?: {
/**
* Enables server-side [OpenTelemetry](https://opentelemetry.io/) span emission for SvelteKit operations including the [`handle` hook](https://svelte.dev/docs/kit/hooks#handle), [`load` functions](https://svelte.dev/docs/kit/load), [form actions](https://svelte.dev/docs/kit/form-actions), and [remote functions](https://svelte.dev/docs/kit/remote-functions).
* @default false
* @since 2.31.0
*/
server?: boolean;
};
/**
* @since 2.31.0
*/
instrumentation?: {
/**
* Enables `instrumentation.server.js` for tracing and observability instrumentation.
* @default false
* @since 2.31.0
*/
server?: boolean;
};
/**
* Whether to enable the experimental remote functions feature. This feature is not yet stable and may be changed or removed at any time.
* @default false
*/
remoteFunctions?: boolean;
/**
* Whether to enable the experimental forked preloading feature using Svelte's fork API.
* @default false
*/
forkPreloads?: boolean;
/**
* Whether to enable the experimental handling of rendering errors.
* When enabled, `<svelte:boundary>` is used to wrap components at each level
* where there's an `+error.svelte`, rendering the error page if the component fails.
* In addition, error boundaries also work on the server and the error object goes through `handleError`.
* @default false
*/
handleRenderingErrors?: boolean;
};Experimental features. Here be dragons. These are not subject to semantic versioning, so breaking changes or removal can happen in any release.
files?: {
/**
* The location of your source code.
* @deprecated this feature is still supported, but it's generally recommended to use [monorepos](https://levelup.video/tutorials/monorepos-with-pnpm) instead
* @default "src"
* @since 2.28
*/
src?: string;
/**
* A place to put static files that should have stable URLs and undergo no processing, such as `favicon.ico` or `manifest.json`.
* @deprecated this feature is still supported, but it's generally recommended to use [monorepos](https://levelup.video/tutorials/monorepos-with-pnpm) instead
* @default "static"
*/
assets?: string;
hooks?: {
/**
* The location of your client [hooks](https://svelte.dev/docs/kit/hooks).
* @deprecated this feature is still supported, but it's generally recommended to use [monorepos](https://levelup.video/tutorials/monorepos-with-pnpm) instead
* @default "src/hooks.client"
*/
client?: string;
/**
* The location of your server [hooks](https://svelte.dev/docs/kit/hooks).
* @deprecated this feature is still supported, but it's generally recommended to use [monorepos](https://levelup.video/tutorials/monorepos-with-pnpm) instead
* @default "src/hooks.server"
*/
server?: string;
/**
* The location of your universal [hooks](https://svelte.dev/docs/kit/hooks).
* @deprecated this feature is still supported, but it's generally recommended to use [monorepos](https://levelup.video/tutorials/monorepos-with-pnpm) instead
* @default "src/hooks"
* @since 2.3.0
*/
universal?: string;
};
/**
* Your app's internal library, accessible throughout the codebase as `$lib`.
* @deprecated this feature is still supported, but it's generally recommended to use [monorepos](https://levelup.video/tutorials/monorepos-with-pnpm) instead
* @default "src/lib"
*/
lib?: string;
/**
* A directory containing [parameter matchers](https://svelte.dev/docs/kit/advanced-routing#Matching).
* @deprecated this feature is still supported, but it's generally recommended to use [monorepos](https://levelup.video/tutorials/monorepos-with-pnpm) instead
* @default "src/params"
*/
params?: string;
/**
* The files that define the structure of your app (see [Routing](https://svelte.dev/docs/kit/routing)).
* @deprecated this feature is still supported, but it's generally recommended to use [monorepos](https://levelup.video/tutorials/monorepos-with-pnpm) instead
* @default "src/routes"
*/
routes?: string;
/**
* The location of your service worker's entry point (see [Service workers](https://svelte.dev/docs/kit/service-workers)).
* @deprecated this feature is still supported, but it's generally recommended to use [monorepos](https://levelup.video/tutorials/monorepos-with-pnpm) instead
* @default "src/service-worker"
*/
serviceWorker?: string;
/**
* The location of the template for HTML responses.
* @deprecated this feature is still supported, but it's generally recommended to use [monorepos](https://levelup.video/tutorials/monorepos-with-pnpm) instead
* @default "src/app.html"
*/
appTemplate?: string;
/**
* The location of the template for fallback error responses.
* @deprecated this feature is still supported, but it's generally recommended to use [monorepos](https://levelup.video/tutorials/monorepos-with-pnpm) instead
* @default "src/error.html"
*/
errorTemplate?: string;
};Where to find various files within your project.
inlineStyleThreshold?: number;Inline CSS inside a <style> block at the head of the HTML. This option is a number that specifies the maximum length of a CSS file in UTF-16 code units, as specified by the String.length property, to be inlined. All CSS files needed for the page that are smaller than this value are merged and inlined in a <style> block.
This results in fewer initial requests and can improve your First Contentful Paint score. However, it generates larger HTML output and reduces the effectiveness of browser caches. Use it advisedly.
moduleExtensions?: string[];An array of file extensions that SvelteKit will treat as modules. Files with extensions that match neither config.extensions nor config.kit.moduleExtensions will be ignored by the router.
outDir?: string;The directory that SvelteKit writes files to during dev and build. You should exclude this directory from version control.
output?: {
/**
* SvelteKit will preload the JavaScript modules needed for the initial page to avoid import 'waterfalls', resulting in faster application startup. There
* are three strategies with different trade-offs:
* - `modulepreload` - uses `<link rel="modulepreload">`. This delivers the best results in Chromium-based browsers, in Firefox 115+, and Safari 17+. It is ignored in older browsers.
* - `preload-js` - uses `<link rel="preload">`. Prevents waterfalls in Chromium and Safari, but Chromium will parse each module twice (once as a script, once as a module). Causes modules to be requested twice in Firefox. This is a good setting if you want to maximise performance for users on iOS devices at the cost of a very slight degradation for Chromium users.
* - `preload-mjs` - uses `<link rel="preload">` but with the `.mjs` extension which prevents double-parsing in Chromium. Some static webservers will fail to serve .mjs files with a `Content-Type: application/javascript` header, which will cause your application to break. If that doesn't apply to you, this is the option that will deliver the best performance for the largest number of users, until `modulepreload` is more widely supported.
* @default "modulepreload"
* @since 1.8.4
*/
preloadStrategy?: 'modulepreload' | 'preload-js' | 'preload-mjs';
/**
* The bundle strategy option affects how your app's JavaScript and CSS files are loaded.
* - If `'split'`, splits the app up into multiple .js/.css files so that they are loaded lazily as the user navigates around the app. This is the default, and is recommended for most scenarios.
* - If `'single'`, creates just one .js bundle and one .css file containing code for the entire app.
* - If `'inline'`, inlines all JavaScript and CSS of the entire app into the HTML. The result is usable without a server (i.e. you can just open the file in your browser).
*
* When using `'split'`, you can also adjust the bundling behaviour by setting [`output.experimentalMinChunkSize`](https://rollupjs.org/configuration-options/#output-experimentalminchunksize) and [`output.manualChunks`](https://rollupjs.org/configuration-options/#output-manualchunks) inside your Vite config's [`build.rollupOptions`](https://vite.dev/config/build-options.html#build-rollupoptions).
*
* If you want to inline your assets, you'll need to set Vite's [`build.assetsInlineLimit`](https://vite.dev/config/build-options.html#build-assetsinlinelimit) option to an appropriate size then import your assets through Vite.
*
* ```js
* /// file: vite.config.js
* import { sveltekit } from '@sveltejs/kit/vite';
* import { defineConfig } from 'vite';
*
* export default defineConfig({
* plugins: [sveltekit()],
* build: {
* // inline all imported assets
* assetsInlineLimit: Infinity
* }
* });
* ```
*
* ```svelte
* /// file: src/routes/+layout.svelte
* <script>
* // import the asset through Vite
* import favicon from './favicon.png';
* </script>
*
* <svelte:head>
* <!-- this asset will be inlined as a base64 URL -->
* <link rel="icon" href={favicon} />
* </svelte:head>
* ```
* @default 'split'
* @since 2.13.0
*/
bundleStrategy?: 'split' | 'single' | 'inline';
};Options related to the build output format
paths?: {
/**
* An absolute path that your app's files are served from. This is useful if your files are served from a storage bucket of some kind.
* @default ""
*/
assets?: '' | `http://${string}` | `https://${string}`;
/**
* A root-relative path that must start, but not end with `/` (e.g. `/base-path`), unless it is the empty string. This specifies where your app is served from and allows the app to live on a non-root path. Note that you need to prepend all your root-relative links with the base value or they will point to the root of your domain, not your `base` (this is how the browser works). You can use [`base` from `$app/paths`](https://svelte.dev/docs/kit/$app-paths#base) for that: `<a href="{base}/your-page">Link</a>`. If you find yourself writing this often, it may make sense to extract this into a reusable component.
* @default ""
*/
base?: '' | `/${string}`;
/**
* Whether to use relative asset paths.
*
* If `true`, `base` and `assets` imported from `$app/paths` will be replaced with relative asset paths during server-side rendering, resulting in more portable HTML.
* If `false`, `%sveltekit.assets%` and references to build artifacts will always be root-relative paths, unless `paths.assets` is an external URL
*
* [Single-page app](https://svelte.dev/docs/kit/single-page-apps) fallback pages will always use absolute paths, regardless of this setting.
*
* If your app uses a `<base>` element, you should set this to `false`, otherwise asset URLs will incorrectly be resolved against the `<base>` URL rather than the current page.
*
* In 1.0, `undefined` was a valid value, which was set by default. In that case, if `paths.assets` was not external, SvelteKit would replace `%sveltekit.assets%` with a relative path and use relative paths to reference build artifacts, but `base` and `assets` imported from `$app/paths` would be as specified in your config.
*
* @default true
* @since 1.9.0
*/
relative?: boolean;
};prerender?: {
/**
* How many pages can be prerendered simultaneously. JS is single-threaded, but in cases where prerendering performance is network-bound (for example loading content from a remote CMS) this can speed things up by processing other tasks while waiting on the network response.
* @default 1
*/
concurrency?: number;
/**
* Whether SvelteKit should find pages to prerender by following links from `entries`.
* @default true
*/
crawl?: boolean;
/**
* An array of pages to prerender, or start crawling from (if `crawl: true`). The `*` string includes all routes containing no required `[parameters]` with optional parameters included as being empty (since SvelteKit doesn't know what value any parameters should have).
* @default ["*"]
*/
entries?: Array<'*' | `/${string}`>;
/**
* How to respond to HTTP errors encountered while prerendering the app.
*
* - `'fail'` — fail the build
* - `'ignore'` - silently ignore the failure and continue
* - `'warn'` — continue, but print a warning
* - `(details) => void` — a custom error handler that takes a `details` object with `status`, `path`, `referrer`, `referenceType` and `message` properties. If you `throw` from this function, the build will fail
*
* ```js
* /// file: svelte.config.js
* /// type: import('@sveltejs/kit').Config
* const config = {
* kit: {
* prerender: {
* handleHttpError: ({ path, referrer, message }) => {
* // ignore deliberate link to shiny 404 page
* if (path === '/not-found' && referrer === '/blog/how-we-built-our-404-page') {
* return;
* }
*
* // otherwise fail the build
* throw new Error(message);
* }
* }
* }
* };
* ```
*
* @default "fail"
* @since 1.15.7
*/
handleHttpError?: PrerenderHttpErrorHandlerValue;
/**
* How to respond when hash links from one prerendered page to another don't correspond to an `id` on the destination page.
*
* - `'fail'` — fail the build
* - `'ignore'` - silently ignore the failure and continue
* - `'warn'` — continue, but print a warning
* - `(details) => void` — a custom error handler that takes a `details` object with `path`, `id`, `referrers` and `message` properties. If you `throw` from this function, the build will fail
*
* @default "fail"
* @since 1.15.7
*/
handleMissingId?: PrerenderMissingIdHandlerValue;
/**
* How to respond when an entry generated by the `entries` export doesn't match the route it was generated from.
*
* - `'fail'` — fail the build
* - `'ignore'` - silently ignore the failure and continue
* - `'warn'` — continue, but print a warning
* - `(details) => void` — a custom error handler that takes a `details` object with `generatedFromId`, `entry`, `matchedId` and `message` properties. If you `throw` from this function, the build will fail
*
* @default "fail"
* @since 1.16.0
*/
handleEntryGeneratorMismatch?: PrerenderEntryGeneratorMismatchHandlerValue;
/**
* How to respond when a route is marked as prerenderable but has not been prerendered.
*
* - `'fail'` — fail the build
* - `'ignore'` - silently ignore the failure and continue
* - `'warn'` — continue, but print a warning
* - `(details) => void` — a custom error handler that takes a `details` object with a `routes` property which contains all routes that haven't been prerendered. If you `throw` from this function, the build will fail
*
* The default behavior is to fail the build. This may be undesirable when you know that some of your routes may never be reached under certain
* circumstances such as a CMS not returning data for a specific area, resulting in certain routes never being reached.
*
* @default "fail"
* @since 2.16.0
*/
handleUnseenRoutes?: PrerenderUnseenRoutesHandlerValue;
/**
* How to respond when SvelteKit encounters a URL it cannot parse while crawling prerendered HTML (for example, an AT Protocol URL such as `at://did:plc:...`).
*
* - `'fail'` — fail the build
* - `'ignore'` - silently ignore the failure and continue
* - `'warn'` — continue, but print a warning
* - `(details) => void` — a custom error handler that takes a `details` object with `href`, `referrer` and `message` properties. If you `throw` from this function, the build will fail
*
* @default "fail"
* @since 2.67.0
*/
handleInvalidUrl?: PrerenderInvalidUrlHandlerValue;
/**
* The value of `url.origin` during prerendering; useful if it is included in rendered content.
* @default "http://sveltekit-prerender"
*/
origin?: string;
};See Prerendering.
router?: {
/**
* What type of client-side router to use.
* - `'pathname'` is the default and means the current URL pathname determines the route
* - `'hash'` means the route is determined by `location.hash`. In this case, SSR and prerendering are disabled. This is only recommended if `pathname` is not an option, for example because you don't control the webserver where your app is deployed.
* It comes with some caveats: you can't use server-side rendering (or indeed any server logic), and you have to make sure that the links in your app all start with #/, or they won't work. Beyond that, everything works exactly like a normal SvelteKit app.
*
* @default "pathname"
* @since 2.14.0
*/
type?: 'pathname' | 'hash';
/**
* How to determine which route to load when navigating to a new page.
*
* By default, SvelteKit will serve a route manifest to the browser.
* When navigating, this manifest is used (along with the `reroute` hook, if it exists) to determine which components to load and which `load` functions to run.
* Because everything happens on the client, this decision can be made immediately. The drawback is that the manifest needs to be
* loaded and parsed before the first navigation can happen, which may have an impact if your app contains many routes.
*
* Alternatively, SvelteKit can determine the route on the server. This means that for every navigation to a path that has not yet been visited, the server will be asked to determine the route.
* This has several advantages:
* - The client does not need to load the routing manifest upfront, which can lead to faster initial page loads
* - The list of routes is hidden from public view
* - The server has an opportunity to intercept each navigation (for example through a middleware), enabling (for example) A/B testing opaque to SvelteKit
* The drawback is that for unvisited paths, resolution will take slightly longer (though this is mitigated by [preloading](https://svelte.dev/docs/kit/link-options#data-sveltekit-preload-data)).
*
* > [!NOTE] When using server-side route resolution and prerendering, the resolution is prerendered along with the route itself.
*
* @default "client"
* @since 2.17.0
*/
resolution?: 'client' | 'server';
};serviceWorker?: {
/**
* Determine which files in your `static` directory will be available in `$service-worker.files`.
* @default (filename) => !/\.DS_Store/.test(filename)
*/
files?: (file: string) => boolean;
} & (
| {
/**
* Whether to automatically register the service worker, if it exists.
* @default true
*/
register: true;
/**
* Options for serviceWorker.register("...", options);
*/
options?: RegistrationOptions;
}
| {
/**
* Whether to automatically register the service worker, if it exists.
* @default true
*/
register?: false;
}
);typescript?: {
/**
* A function that allows you to edit the generated `tsconfig.json`. You can mutate the config (recommended) or return a new one.
* This is useful for extending a shared `tsconfig.json` in a monorepo root, for example.
*
* Note that any paths configured here should be relative to the generated config file, which is written to `.svelte-kit/tsconfig.json`.
*
* @default (config) => config
* @since 1.3.0
*/
config?: (config: Record<string, any>) => Record<string, any> | void;
};version?: {
/**
* The current app version string. If specified, this must be deterministic (e.g. a commit ref rather than `Math.random()` or `Date.now().toString()`), otherwise defaults to a timestamp of the build.
*
* For example, to use the current commit hash, you could do use `git rev-parse HEAD`:
*
* ```js
* /// file: svelte.config.js
* import * as child_process from 'node:child_process';
*
* export default {
* kit: {
* version: {
* name: child_process.execSync('git rev-parse HEAD').toString().trim()
* }
* }
* };
* ```
*/
name?: string;
/**
* The interval in milliseconds to poll for version changes. If this is `0`, no polling occurs.
* @default 0
*/
pollInterval?: number;
};Client-side navigation can be buggy if you deploy a new version of your app while people are using it. If the code for the new page is already loaded, it may have stale content; if it isn't, the app's route manifest may point to a JavaScript file that no longer exists.
SvelteKit helps you solve this problem through version management.
If SvelteKit encounters an error while loading the page and detects that a new version has been deployed (using the name specified here, which defaults to a timestamp of the build) it will fall back to traditional full-page navigation.
Not all navigations will result in an error though, for example if the JavaScript for the next page is already loaded. If you still want to force a full-page navigation in these cases, use techniques such as setting the pollInterval and then using beforeNavigate:
<script>
import { beforeNavigate } from '$app/navigation';
import { updated } from '$app/state';
beforeNavigate(({ willUnload, to }) => {
if (updated.current && !willUnload && to?.url) {
location.href = to.url.href;
}
});
</script>If you set pollInterval to a non-zero value, SvelteKit will poll for new versions in the background and set the value of updated.current true when it detects one.
Handle
The handle hook runs every time the SvelteKit server receives a request and
determines the 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).
export type Handle = (input: {
event: RequestEvent;
resolve: (event: RequestEvent, opts?: ResolveOptions) => MaybePromise<Response>;
}) => MaybePromise<Response>;HandleServerError
The server-side handleError hook runs when an unexpected error is thrown while responding to a request.
If an unexpected error is thrown during loading or rendering, this function will be called with the error and the event. Make sure that this function never throws an error.
export type HandleServerError = (input: {
error: unknown;
event: RequestEvent;
status: number;
message: string;
}) => MaybePromise<void | App.Error>;HandleValidationError
The handleValidationError hook runs when the argument to a remote function fails validation.
It will be called with the validation issues and the event, and must return an object shape that matches App.Error.
export type HandleValidationError<Issue extends StandardSchemaV1.Issue = StandardSchemaV1.Issue> =
(input: { issues: Issue[]; event: RequestEvent }) => MaybePromise<App.Error>;HandleClientError
The client-side handleError hook runs when an unexpected error is thrown while navigating.
If an unexpected error is thrown during loading or the following render, this function will be called with the error and the event. Make sure that this function never throws an error.
export type HandleClientError = (input: {
error: unknown;
event: NavigationEvent;
status: number;
message: string;
}) => MaybePromise<void | App.Error>;HandleFetch
The handleFetch hook allows you to modify (or replace) the result of an event.fetch call that runs on the server (or during prerendering) inside an endpoint, load, action, handle, handleError or reroute.
export type HandleFetch = (input: {
event: RequestEvent;
request: Request;
fetch: typeof fetch;
}) => MaybePromise<Response>;ServerInit
Available since 2.10.0
The init will be invoked before the server responds to its first request
export type ServerInit = () => MaybePromise<void>;ClientInit
Available since 2.10.0
The init will be invoked once the app starts in the browser
export type ClientInit = () => MaybePromise<void>;Reroute
Available since 2.3.0
The reroute hook allows you to modify the URL before it is used to determine which route to render.
export type Reroute = (event: { url: URL; fetch: typeof fetch }) => MaybePromise<void | string>;Transport
Available since 2.11.0
The 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.
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)
}
};export type Transport = Record<string, Transporter>;Transporter
A member of the transport hook.
export interface interface Transporter<T = any, U = any>interface Transporter<T = any, U = any>Transporter<
function (type parameter) T in Transporter<T = any, U = any>function (type parameter) T in Transporter<T = any, U = any>T = any,
function (type parameter) U in Transporter<T = any, U = any>function (type parameter) U in Transporter<T = any, U = any>U = type Exclude<T, U> = T extends U ? never : TExclude from T those types that are assignable to U
type Exclude<T, U> = T extends U ? never : TExclude from T those types that are assignable to U
Exclude<any, false | 0 | '' | null | undefined | typeof var NaN: numbervar NaN: numberNaN>
> {/*…*/}encode: (value: T) => false | U;decode: (data: U) => T;Load
The generic form of PageLoad and LayoutLoad. You should import those from ./$types (see generated types)
rather than using Load directly.
export type Load<
Params extends AppLayoutParams<'/'> = AppLayoutParams<'/'>,
InputData extends Record<string, unknown> | null = Record<string, any> | null,
ParentData extends Record<string, unknown> = Record<string, any>,
OutputData extends Record<string, unknown> | void = Record<string, any> | void,
RouteId extends AppRouteId | null = AppRouteId | null
> = (event: LoadEvent<Params, InputData, ParentData, RouteId>) => MaybePromise<OutputData>;LoadEvent
The generic form of PageLoadEvent and LayoutLoadEvent. You should import those from ./$types (see generated types)
rather than using LoadEvent directly.
export interface LoadEvent<
Params extends AppLayoutParams<'/'> = AppLayoutParams<'/'>,
Data extends Record<string, unknown> | null = Record<string, any> | null,
ParentData extends Record<string, unknown> = Record<string, any>,
RouteId extends AppRouteId | null = AppRouteId | null
> extends NavigationEvent<Params, RouteId> {/*…*/}fetch: typeof function fetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> (+1 overload)function fetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> (+1 overload)fetch;fetch is equivalent to the native fetch web API, with a few additional features:
- It can be used to make credentialed requests on the server, as it inherits the
cookieandauthorizationheaders for the page request. - It can make relative requests on the server (ordinarily,
fetchrequires a URL with an origin when used in a server context). - Internal requests (e.g. for
+server.jsroutes) go directly to the handler function when running on the server, without the overhead of an HTTP call. - During server-side rendering, the response will be captured and inlined into the rendered HTML by hooking into the
textandjsonmethods of theResponseobject. Note that headers will not be serialized, unless explicitly included viafilterSerializedResponseHeaders - During hydration, the response will be read from the HTML, guaranteeing consistency and preventing an additional network request.
You can learn more about making credentialed requests with cookies here
data: Data;Contains the data returned by the route's server load function (in +layout.server.js or +page.server.js), if any.
setHeaders: (headers: Record<string, string>) => void;If you need to set headers for the response, you can do so using the this method. This is useful if you want the page to be cached, for example:
export async function 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 API in a server-only load function instead.
setHeaders has no effect when a load function runs in the browser.
parent: () => Promise<ParentData>;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.
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() 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.
Custom identifiers have to be prefixed with one or more lowercase letters followed by a colon to conform to the URI specification.
The following example shows how to use depends to register a dependency on a custom identifier, which is invalidated after a button click, making the load function rerun.
let count = 0;
export async function load({ depends }) {
depends('increase:count');
return { count: count++ };
}<script>
import { invalidate } from '$app/navigation';
let { data } = $props();
const increase = async () => {
await invalidate('increase:count');
}
</script>
<p>{data.count}<p>
<button on:click={increase}>Increase Count</button>untrack: <T>(fn: () => T) => T;Use this function to opt out of dependency tracking for everything that is synchronously called within the callback. Example:
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!' };
}
}tracing: {
/** Whether tracing is enabled. */
enabled: boolean;
/** The root span for the request. This span is named `sveltekit.handle.root`. */
root: Span;
/** The span associated with the current `load` function. */
current: Span;
};Access to spans for tracing. If tracing is not enabled or the function is being run in the browser, these spans will do nothing.
NavigationEvent
export interface NavigationEvent<
Params extends AppLayoutParams<'/'> = AppLayoutParams<'/'>,
RouteId extends AppRouteId | null = AppRouteId | null
> {/*…*/}params: Params;The parameters of the current page - e.g. for a route like /blog/[slug], a { slug: string } object
route: {
/**
* 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.
*/
id: RouteId;
};Info about the current route
url: var URL: {
new (url: string | URL, base?: string | URL): URL;
prototype: URL;
canParse(url: string | URL, base?: string | URL): boolean;
createObjectURL(obj: Blob | MediaSource): string;
parse(url: string | URL, base?: string | URL): URL | null;
revokeObjectURL(url: string): void;
}
The URL interface is used to parse, construct, normalize, and encode URLs. It works by providing properties which allow you to easily read and modify the components of a URL.
var URL: {
new (url: string | URL, base?: string | URL): URL;
prototype: URL;
canParse(url: string | URL, base?: string | URL): boolean;
createObjectURL(obj: Blob | MediaSource): string;
parse(url: string | URL, base?: string | URL): URL | null;
revokeObjectURL(url: string): void;
}
The URL interface is used to parse, construct, normalize, and encode URLs. It works by providing properties which allow you to easily read and modify the components of a URL.
URL;The URL of the current page
NavigationTarget
Information about the target of a specific navigation.
export interface NavigationTarget<
Params extends AppLayoutParams<'/'> = AppLayoutParams<'/'>,
RouteId extends AppRouteId | null = AppRouteId | null
> {/*…*/}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).
route: {
/**
* 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.
*/
id: RouteId | null;
};Info about the target route
url: var URL: {
new (url: string | URL, base?: string | URL): URL;
prototype: URL;
canParse(url: string | URL, base?: string | URL): boolean;
createObjectURL(obj: Blob | MediaSource): string;
parse(url: string | URL, base?: string | URL): URL | null;
revokeObjectURL(url: string): void;
}
The URL interface is used to parse, construct, normalize, and encode URLs. It works by providing properties which allow you to easily read and modify the components of a URL.
var URL: {
new (url: string | URL, base?: string | URL): URL;
prototype: URL;
canParse(url: string | URL, base?: string | URL): boolean;
createObjectURL(obj: Blob | MediaSource): string;
parse(url: string | URL, base?: string | URL): URL | null;
revokeObjectURL(url: string): void;
}
The URL interface is used to parse, construct, normalize, and encode URLs. It works by providing properties which allow you to easily read and modify the components of a URL.
URL;The URL that is navigated to
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
beforeNavigateandonNavigate, this is only available forpopstatenavigations (back/forward button) and will benullfor 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/startedform: The user submitted a<form method="GET">goto: Navigation was triggered by agoto(...)call or a redirectleave: The app is being left either because the tab is being closed or a navigation to a different document is occurringlink: Navigation was triggered by a link clickpopstate: Navigation was triggered by back/forward navigation
export type type NavigationType = "enter" | "form" | "leave" | "link" | "goto" | "popstate"type NavigationType = "enter" | "form" | "leave" | "link" | "goto" | "popstate"NavigationType = 'enter' | 'form' | 'leave' | 'link' | 'goto' | 'popstate';NavigationBase
export interface NavigationBase {/*…*/}type: NavigationType;The type of navigation:
enter: The app has hydrated/startedform: The user submitted a<form method="GET">goto: Navigation was triggered by agoto(...)call or a redirectleave: The app is being left either because the tab is being closed or a navigation to a different document is occurringlink: Navigation was triggered by a link clickpopstate: Navigation was triggered by back/forward navigation
from: NavigationTarget | null;Where navigation was triggered from
to: NavigationTarget | null;Where navigation is going to/has gone to
willUnload: boolean;Whether or not the navigation will result in the page being unloaded (i.e. not a client-side navigation).
complete: var Promise: PromiseConstructorRepresents the completion of an asynchronous operation
var Promise: PromiseConstructorRepresents the completion of an asynchronous operation
Promise<void>;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
export interface NavigationEnter extends NavigationBase {/*…*/}type: 'enter';delta?: undefined;In case of a history back/forward navigation, the number of steps to go back/forward
event?: undefined;Dispatched Event object when navigation occurred by popstate or link.
NavigationExternal
export type NavigationExternal = NavigationGoto | NavigationLeave;NavigationGoto
A navigation triggered by a goto(...) call or a redirect
export interface NavigationGoto extends NavigationBase {/*…*/}type: 'goto';delta?: undefined;In case of a history back/forward navigation, the number of steps to go back/forward
NavigationLeave
A navigation triggered by the tab being closed, or the user navigating to a different document
export interface NavigationLeave extends NavigationBase {/*…*/}type: 'leave';delta?: undefined;In case of a history back/forward navigation, the number of steps to go back/forward
NavigationFormSubmit
A navigation triggered by a <form method="GET">
export interface NavigationFormSubmit extends NavigationBase {/*…*/}type: 'form';event: var SubmitEvent: {
new (type: string, eventInitDict?: SubmitEventInit): SubmitEvent;
prototype: SubmitEvent;
}
The SubmitEvent interface defines the object used to represent an HTML form's submit event. This event is fired at the when the form's submit action is invoked.
var SubmitEvent: {
new (type: string, eventInitDict?: SubmitEventInit): SubmitEvent;
prototype: SubmitEvent;
}
The SubmitEvent interface defines the object used to represent an HTML form's submit event. This event is fired at the when the form's submit action is invoked.
SubmitEvent;The SubmitEvent that caused the navigation
delta?: undefined;In case of a history back/forward navigation, the number of steps to go back/forward
NavigationPopState
A navigation triggered by back/forward navigation
export interface NavigationPopState extends NavigationBase {/*…*/}type: 'popstate';delta: number;In case of a history back/forward navigation, the number of steps to go back/forward
event: var PopStateEvent: {
new (type: string, eventInitDict?: PopStateEventInit): PopStateEvent;
prototype: PopStateEvent;
}
PopStateEvent is an interface for the popstate event.
var PopStateEvent: {
new (type: string, eventInitDict?: PopStateEventInit): PopStateEvent;
prototype: PopStateEvent;
}
PopStateEvent is an interface for the popstate event.
PopStateEvent;The PopStateEvent that caused the navigation
NavigationLink
A navigation triggered by a link click
export interface NavigationLink extends NavigationBase {/*…*/}type: 'link';event: var PointerEvent: {
new (type: string, eventInitDict?: PointerEventInit): PointerEvent;
prototype: PointerEvent;
}
The PointerEvent interface represents the state of a DOM event produced by a pointer such as the geometry of the contact point, the device type that generated the event, the amount of pressure that was applied on the contact surface, etc.
var PointerEvent: {
new (type: string, eventInitDict?: PointerEventInit): PointerEvent;
prototype: PointerEvent;
}
The PointerEvent interface represents the state of a DOM event produced by a pointer such as the geometry of the contact point, the device type that generated the event, the amount of pressure that was applied on the contact surface, etc.
PointerEvent;The PointerEvent that caused the navigation
delta?: undefined;In case of a history back/forward navigation, the number of steps to go back/forward
Navigation
export type Navigation =
| NavigationExternal
| NavigationFormSubmit
| NavigationPopState
| NavigationLink;BeforeNavigate
The argument passed to beforeNavigate callbacks.
export type type BeforeNavigate = Navigation & {
cancel: () => void;
}
type BeforeNavigate = Navigation & {
cancel: () => void;
}
BeforeNavigate = Navigation & {
/**
* Call this to prevent the navigation from starting.
*/
cancel: () => voidCall this to prevent the navigation from starting.
cancel: () => voidCall this to prevent the navigation from starting.
cancel: () => void;
};OnNavigate
The argument passed to onNavigate callbacks.
export type type OnNavigate = Navigation & {
type: Exclude<NavigationType, "enter" | "leave">;
willUnload: false;
}
type OnNavigate = Navigation & {
type: Exclude<NavigationType, "enter" | "leave">;
willUnload: false;
}
OnNavigate = Navigation & {
type: NavigationTypetype: NavigationTypetype: type Exclude<T, U> = T extends U ? never : TExclude from T those types that are assignable to U
type Exclude<T, U> = T extends U ? never : TExclude from T those types that are assignable to U
Exclude<type NavigationType = "push" | "reload" | "replace" | "traverse"type NavigationType = "push" | "reload" | "replace" | "traverse"NavigationType, 'enter' | 'leave'>;
/**
* Since `onNavigate` callbacks are called immediately before a client-side navigation, they will never be called with a navigation that unloads the page.
*/
willUnload: falseSince onNavigate callbacks are called immediately before a client-side navigation, they will never be called with a navigation that unloads the page.
willUnload: falseSince onNavigate callbacks are called immediately before a client-side navigation, they will never be called with a navigation that unloads the page.
willUnload: false;
};AfterNavigate
The argument passed to afterNavigate callbacks.
export type AfterNavigate = (Navigation | NavigationEnter) & {
type: Exclude<NavigationType, 'leave'>;
/**
* Since `afterNavigate` callbacks are called after a navigation completes, they will never be called with a navigation that unloads the page.
*/
willUnload: false;
};Page
The shape of the page reactive object and the $page store.
export interface Page<
Params extends AppLayoutParams<'/'> = AppLayoutParams<'/'>,
RouteId extends AppRouteId | null = AppRouteId | null
> {/*…*/}url: URL & { pathname: ResolvedPathname };The URL of the current page.
params: Params;The parameters of the current page - e.g. for a route like /blog/[slug], a { slug: string } object.
route: {
/**
* 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.
*/
id: RouteId;
};Info about the current route.
status: number;HTTP status code of the current page.
error: App.Error | null;The error object of the current page, if any. Filled from the handleError hooks.
data: App.PageData & Record<string, any>;The merged result of all data from all load functions on the current page. You can type a common denominator through App.PageData.
state: App.PageState;The page state, which can be manipulated using the pushState and replaceState functions from $app/navigation.
form: any;Filled only after a form submission. See form actions for more info.
ParamMatcher
The shape of a param matcher. See matching for more info.
export type type ParamMatcher = (param: string) => booleantype ParamMatcher = (param: string) => booleanParamMatcher = (param: stringparam: stringparam: string) => boolean;RequestedEntry
A single entry yielded by 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.
export type RequestedEntry<Validated, Output> = {
arg: Validated;
query: RemoteQuery<Output>;
};LiveRequestedEntry
A single entry yielded by 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.
export type LiveRequestedEntry<Validated, Output> = {
arg: Validated;
query: RemoteLiveQuery<Output>;
};QueryRequestedResult
export type QueryRequestedResult<Validated, Output> = Iterable<RequestedEntry<Validated, Output>> &
AsyncIterable<RequestedEntry<Validated, Output>> & {
/**
* 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<void>;
};LiveQueryRequestedResult
export type LiveQueryRequestedResult<Validated, Output> = Iterable<
LiveRequestedEntry<Validated, Output>
> &
AsyncIterable<LiveRequestedEntry<Validated, Output>> & {
/**
* 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<void>;
};RequestedResult
export type RequestedResult<Validated, Output> =
| QueryRequestedResult<Validated, Output>
| LiveQueryRequestedResult<Validated, Output>;RequestEvent
export interface RequestEvent<
Params extends AppLayoutParams<'/'> = AppLayoutParams<'/'>,
RouteId extends AppRouteId | null = AppRouteId | null
> {/*…*/}cookies: Cookies;Get or set cookies related to the current request
fetch: typeof function fetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> (+1 overload)function fetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> (+1 overload)fetch;fetch is equivalent to the native fetch web API, with a few additional features:
- It can be used to make credentialed requests on the server, as it inherits the
cookieandauthorizationheaders for the page request. - It can make relative requests on the server (ordinarily,
fetchrequires a URL with an origin when used in a server context). - Internal requests (e.g. for
+server.jsroutes) go directly to the handler function when running on the server, without the overhead of an HTTP call. - During server-side rendering, the response will be captured and inlined into the rendered HTML by hooking into the
textandjsonmethods of theResponseobject. Note that headers will not be serialized, unless explicitly included viafilterSerializedResponseHeaders - During hydration, the response will be read from the HTML, guaranteeing consistency and preventing an additional network request.
You can learn more about making credentialed requests with cookies here.
getClientAddress: () => string;The client's IP address, set by the adapter.
locals: App.Locals;Contains custom data that was added to the request within the server handle hook.
params: Params;The parameters of the current route - e.g. for a route like /blog/[slug], a { slug: string } object.
In the context of a remote function request initiated by the client, this relates to the page the remote function was called from, not the URL of the endpoint SvelteKit creates for the remote function. Never use this 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.
platform: Readonly<App.Platform> | undefined;Additional data made available through the adapter.
request: var Request: {
new (input: RequestInfo | URL, init?: RequestInit): Request;
prototype: Request;
}
The Request interface of the Fetch API represents a resource request.
var Request: {
new (input: RequestInfo | URL, init?: RequestInit): Request;
prototype: Request;
}
The Request interface of the Fetch API represents a resource request.
Request;The original request object.
route: {
/**
* 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.
*
* In the context of a remote function request initiated by the client, this relates to the page the remote function
* was called from, _not_ the URL of the endpoint SvelteKit creates for the remote function. Never use this 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.
*/
id: RouteId;
};Info about the current route.
setHeaders: (headers: Record<string, string>) => void;If you need to set headers for the response, you can do so using the this method. This is useful if you want the page to be cached, for example:
export async function 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 API instead.
url: var URL: {
new (url: string | URL, base?: string | URL): URL;
prototype: URL;
canParse(url: string | URL, base?: string | URL): boolean;
createObjectURL(obj: Blob | MediaSource): string;
parse(url: string | URL, base?: string | URL): URL | null;
revokeObjectURL(url: string): void;
}
The URL interface is used to parse, construct, normalize, and encode URLs. It works by providing properties which allow you to easily read and modify the components of a URL.
var URL: {
new (url: string | URL, base?: string | URL): URL;
prototype: URL;
canParse(url: string | URL, base?: string | URL): boolean;
createObjectURL(obj: Blob | MediaSource): string;
parse(url: string | URL, base?: string | URL): URL | null;
revokeObjectURL(url: string): void;
}
The URL interface is used to parse, construct, normalize, and encode URLs. It works by providing properties which allow you to easily read and modify the components of a URL.
URL;The requested URL.
In the context of a remote function request initiated by the client, this relates to the page the remote function was called from, not the URL of the endpoint SvelteKit creates for the remote function. Never use this 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.
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.
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.
tracing: {
/** Whether tracing is enabled. */
enabled: boolean;
/** The root span for the request. This span is named `sveltekit.handle.root`. */
root: Span;
/** The span associated with the current `handle` hook, `load` function, or form action. */
current: Span;
};Access to spans for tracing. If tracing is not enabled, these spans will do nothing.
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 instead.
export type RequestHandler<
Params extends AppLayoutParams<'/'> = AppLayoutParams<'/'>,
RouteId extends AppRouteId | null = AppRouteId | null
> = (event: RequestEvent<Params, RouteId>) => MaybePromise<Response>;ResolveOptions
export interface ResolveOptions {/*…*/}transformPageChunk?: (input: { html: string; done: boolean }) => MaybePromise<string | undefined>;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.
filterSerializedResponseHeaders?: (name: string, value: string) => boolean;Determines which headers should be included in serialized responses when a load function loads a resource with fetch.
By default, none will be included.
preload?: (input: { type: 'font' | 'css' | 'js' | 'asset'; path: string }) => boolean;Determines what should be added to the <head> tag to preload it.
By default, js and css files will be preloaded.
RouteDefinition
export interface interface RouteDefinition<Config = any>interface RouteDefinition<Config = any>RouteDefinition<function (type parameter) Config in RouteDefinition<Config = any>function (type parameter) Config in RouteDefinition<Config = any>Config = any> {/*…*/}id: string;api: {
methods: Array<HttpMethod | '*'>;
};page: {
methods: Array<Extract<HttpMethod, 'GET' | 'POST'>>;
};pattern: var RegExp: RegExpConstructorvar RegExp: RegExpConstructorRegExp;prerender: PrerenderOption;segments: RouteSegment[];methods: Array<HttpMethod | '*'>;config: Config;Server
export class class Serverclass ServerServer {/*…*/}constructor(manifest: SSRManifest);init(options: ServerInitOptions): Promise<void>;respond(request: Request, options: RequestOptions): Promise<Response>;ServerInitOptions
export interface ServerInitOptions {/*…*/}env: Record<string, string>;A map of environment variables.
read?: (file: string) => MaybePromise<ReadableStream | null>;A function that turns an asset filename into a ReadableStream. Required for the read export from $app/server to work.
SSRManifest
export interface SSRManifest {/*…*/}appDir: string;appPath: string;assets: var Set: SetConstructorvar Set: SetConstructorSet<string>;Static files from kit.config.files.assets and the service worker (if any).
mimeTypes: Record<string, string>;_: {
client: BuildData['client'];
nodes: SSRNodeLoader[];
/** hashed filename -> import to that file */
remotes: Record<string, () => Promise<any>>;
routes: SSRRoute[];
prerendered_routes: Set<string>;
matchers: () => Promise<Record<string, ParamMatcher>>;
/** A `[file]: size` map of all assets imported by server code. */
server_assets: Record<string, number>;
};private fields
ServerLoad
The generic form of PageServerLoad and LayoutServerLoad. You should import those from ./$types (see generated types)
rather than using ServerLoad directly.
export type ServerLoad<
Params extends AppLayoutParams<'/'> = AppLayoutParams<'/'>,
ParentData extends Record<string, any> = Record<string, any>,
OutputData extends Record<string, any> | void = Record<string, any> | void,
RouteId extends AppRouteId | null = AppRouteId | null
> = (event: ServerLoadEvent<Params, ParentData, RouteId>) => MaybePromise<OutputData>;ServerLoadEvent
export interface ServerLoadEvent<
Params extends AppLayoutParams<'/'> = AppLayoutParams<'/'>,
ParentData extends Record<string, any> = Record<string, any>,
RouteId extends AppRouteId | null = AppRouteId | null
> extends RequestEvent<Params, RouteId> {/*…*/}parent: () => Promise<ParentData>;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.
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() 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.
Custom identifiers have to be prefixed with one or more lowercase letters followed by a colon to conform to the URI specification.
The following example shows how to use depends to register a dependency on a custom identifier, which is invalidated after a button click, making the load function rerun.
let count = 0;
export async function load({ depends }) {
depends('increase:count');
return { count: count++ };
}<script>
import { invalidate } from '$app/navigation';
let { data } = $props();
const increase = async () => {
await invalidate('increase:count');
}
</script>
<p>{data.count}<p>
<button on:click={increase}>Increase Count</button>untrack: <T>(fn: () => T) => T;Use this function to opt out of dependency tracking for everything that is synchronously called within the callback. Example:
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!' };
}
}tracing: {
/** Whether tracing is enabled. */
enabled: boolean;
/** The root span for the request. This span is named `sveltekit.handle.root`. */
root: Span;
/** The span associated with the current server `load` function. */
current: Span;
};Access to spans for tracing. If tracing is not enabled, these spans will do nothing.
Action
Shape of a form action method that is part of export const actions = {...} in +page.server.js.
See form actions for more information.
export type Action<
Params extends AppLayoutParams<'/'> = AppLayoutParams<'/'>,
OutputData extends Record<string, any> | void = Record<string, any> | void,
RouteId extends AppRouteId | null = AppRouteId | null
> = (event: RequestEvent<Params, RouteId>) => MaybePromise<OutputData>;Actions
Shape of the export const actions = {...} object in +page.server.js.
See form actions for more information.
export type Actions<
Params extends AppLayoutParams<'/'> = AppLayoutParams<'/'>,
OutputData extends Record<string, any> | void = Record<string, any> | void,
RouteId extends AppRouteId | null = AppRouteId | null
> = Record<string, Action<Params, OutputData, RouteId>>;ActionResult
When calling a form action via fetch, the response will be one of these shapes.
<form method="post" use:enhance={() => {
return ({ result }) => {
// result is of type ActionResult
};
}}export type type ActionResult<Success extends Record<string, unknown> | undefined = Record<string, any>, Failure extends Record<string, unknown> | undefined = Record<string, any>> = {
type: "success";
status: number;
data?: Success;
} | {
type: "failure";
status: number;
data?: Failure;
} | {
type: "redirect";
status: number;
location: string;
} | {
type: "error";
status?: number;
error: any;
}
type ActionResult<Success extends Record<string, unknown> | undefined = Record<string, any>, Failure extends Record<string, unknown> | undefined = Record<string, any>> = {
type: "success";
status: number;
data?: Success;
} | {
type: "failure";
status: number;
data?: Failure;
} | {
type: "redirect";
status: number;
location: string;
} | {
type: "error";
status?: number;
error: any;
}
ActionResult<
function (type parameter) Success in type ActionResult<Success extends Record<string, unknown> | undefined = Record<string, any>, Failure extends Record<string, unknown> | undefined = Record<string, any>>function (type parameter) Success in type ActionResult<Success extends Record<string, unknown> | undefined = Record<string, any>, Failure extends Record<string, unknown> | undefined = Record<string, any>>Success extends type Record<K extends keyof any, T> = { [P in K]: T; }Construct a type with a set of properties K of type T
type Record<K extends keyof any, T> = { [P in K]: T; }Construct a type with a set of properties K of type T
Record<string, unknown> | undefined = type Record<K extends keyof any, T> = { [P in K]: T; }Construct a type with a set of properties K of type T
type Record<K extends keyof any, T> = { [P in K]: T; }Construct a type with a set of properties K of type T
Record<string, any>,
function (type parameter) Failure in type ActionResult<Success extends Record<string, unknown> | undefined = Record<string, any>, Failure extends Record<string, unknown> | undefined = Record<string, any>>function (type parameter) Failure in type ActionResult<Success extends Record<string, unknown> | undefined = Record<string, any>, Failure extends Record<string, unknown> | undefined = Record<string, any>>Failure extends type Record<K extends keyof any, T> = { [P in K]: T; }Construct a type with a set of properties K of type T
type Record<K extends keyof any, T> = { [P in K]: T; }Construct a type with a set of properties K of type T
Record<string, unknown> | undefined = type Record<K extends keyof any, T> = { [P in K]: T; }Construct a type with a set of properties K of type T
type Record<K extends keyof any, T> = { [P in K]: T; }Construct a type with a set of properties K of type T
Record<string, any>
> =
| { type: "success"type: "success"type: 'success'; status: numberstatus: numberstatus: number; data?: Success | undefineddata?: Success | undefineddata?: function (type parameter) Success in type ActionResult<Success extends Record<string, unknown> | undefined = Record<string, any>, Failure extends Record<string, unknown> | undefined = Record<string, any>>function (type parameter) Success in type ActionResult<Success extends Record<string, unknown> | undefined = Record<string, any>, Failure extends Record<string, unknown> | undefined = Record<string, any>>Success }
| { type: "failure"type: "failure"type: 'failure'; status: numberstatus: numberstatus: number; data?: Failure | undefineddata?: Failure | undefineddata?: function (type parameter) Failure in type ActionResult<Success extends Record<string, unknown> | undefined = Record<string, any>, Failure extends Record<string, unknown> | undefined = Record<string, any>>function (type parameter) Failure in type ActionResult<Success extends Record<string, unknown> | undefined = Record<string, any>, Failure extends Record<string, unknown> | undefined = Record<string, any>>Failure }
| { type: "redirect"type: "redirect"type: 'redirect'; status: numberstatus: numberstatus: number; location: stringlocation: stringlocation: string }
| { type: "error"type: "error"type: 'error'; status?: number | undefinedstatus?: number | undefinedstatus?: number; error: anyerror: anyerror: any };HttpError
The object returned by the error function.
export interface HttpError {/*…*/}status: number;The HTTP status code, in the range 400-599.
body: App.Error;The content of the error.
Redirect
The object returned by the redirect function.
export interface Redirect {/*…*/}status: 300 | 301 | 302 | 303 | 304 | 305 | 306 | 307 | 308;The HTTP status code, in the range 300-308.
location: string;The location to redirect to.
SubmitFunction
export type SubmitFunction<
Success extends Record<string, unknown> | undefined = Record<string, any>,
Failure extends Record<string, unknown> | undefined = Record<string, any>
> = (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<Success, Failure>;
/**
* Call this to get the default behavior of a form submission response.
* @param options Set `reset: false` if you don't want the `<form>` values to be reset after a successful submission.
* @param invalidateAll Set `invalidateAll: false` if you don't want the action to call `invalidateAll` after submission.
*/
update: (options?: { reset?: boolean; invalidateAll?: boolean }) => Promise<void>;
}) => MaybePromise<void>)
>;Snapshot
The type of export const snapshot exported from a page or layout component.
export interface interface Snapshot<T = any>interface Snapshot<T = any>Snapshot<function (type parameter) T in Snapshot<T = any>function (type parameter) T in Snapshot<T = any>T = any> {/*…*/}capture: () => T;restore: (snapshot: T) => void;RemoteFormFieldType
export type RemoteFormFieldType<T> = {
[K in keyof InputTypeMap]: T extends InputTypeMap[K] ? K : never;
}[keyof InputTypeMap];RemoteFormFieldValue
export type type RemoteFormFieldValue = string | number | boolean | string[] | File | File[]type RemoteFormFieldValue = string | number | boolean | string[] | File | File[]RemoteFormFieldValue = string | string[] | number | boolean | File | File[];RemoteFormField
Form field accessor type that provides name(), value(), and issues() methods
export type RemoteFormField<Value extends RemoteFormFieldValue> = RemoteFormFieldMethods<Value> & {
/**
* 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
* <input {...myForm.fields.myString.as('text')} />
* <input {...myForm.fields.myNumber.as('number')} />
* <input {...myForm.fields.myBoolean.as('checkbox')} />
* ```
*/
as<T extends RemoteFormFieldType<Value>>(...args: AsArgs<T, Value>): InputElementProps<T>;
};RemoteFormFields
Recursive type to build form fields structure with proxy access
export type RemoteFormFields<T> =
WillRecurseIndefinitely<T> extends true
? RecursiveFormFields
: NonNullable<T> extends string | number | boolean | File
? RemoteFormField<NonNullable<T>>
: // [NonNullable<T>] 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<T>] extends [string[] | File[]]
? RemoteFormField<NonNullable<T>> & {
[K in number]: RemoteFormField<NonNullable<T>[number]>;
}
: [NonNullable<T>] extends [Array<infer U>]
? RemoteFormFieldContainer<NonNullable<T>> & {
[K in number]: RemoteFormFields<U>;
}
: RemoteFormFieldContainer<T> & {
[K in KeysOfUnion<T>]-?: RemoteFormFields<ValueOfUnionKey<T, K>>;
};RemoteFormInput
export interface RemoteFormInput {/*…*/}[key: string]: MaybeArray<string | number | boolean | File | RemoteFormInput> | undefined;RemoteFormIssue
export interface RemoteFormIssue {/*…*/}message: string;path: var Array: ArrayConstructorvar Array: ArrayConstructorArray<string | number>;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.
export type InvalidField<T> =
WillRecurseIndefinitely<T> extends true
? Record<string | number, any>
: NonNullable<T> extends string | number | boolean | File
? (message: string) => StandardSchemaV1.Issue
: NonNullable<T> extends Array<infer U>
? {
[K in number]: InvalidField<U>;
} & ((message: string) => StandardSchemaV1.Issue)
: NonNullable<T> extends RemoteFormInput
? {
[K in keyof T]-?: InvalidField<T[K]>;
} & ((message: string) => StandardSchemaV1.Issue)
: Record<string, never>;ValidationError
A validation error thrown by invalid.
export interface ValidationError {/*…*/}issues: StandardSchemaV1.Issue[];The validation issues
RemoteFormEnhanceInstance
The form instance as received inside an enhance callback. See Remote functions for full documentation.
export type RemoteFormEnhanceInstance<
Input extends RemoteFormInput | void = RemoteFormInput | void,
Output = any
> = Omit<RemoteForm<Input, Output>, 'enhance' | 'element'> & {
readonly element: HTMLFormElement;
};RemoteFormEnhanceCallback
The callback passed to a remote form's enhance method. See Remote functions for full documentation.
export type RemoteFormEnhanceCallback<
Input extends RemoteFormInput | void = RemoteFormInput | void,
Output = any
> = (form: RemoteFormEnhanceInstance<Input, Output>) => MaybePromise<void>;RemoteForm
The type of a remote form function. See Remote functions for full documentation.
export 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 `<form>` element this instance is currently attached to, if any. */
get element(): HTMLFormElement | null;
/** Submit the currently attached form programmatically. */
submit(): Promise<boolean> & {
updates: (...updates: RemoteQueryUpdate[]) => Promise<boolean>;
};
/** Use the `enhance` method to influence what happens when the form is submitted. */
enhance(callback: RemoteFormEnhanceCallback<Input, Output>): {
method: 'POST';
action: string;
[attachment: symbol]: (node: HTMLFormElement) => void;
};
/**
* Create an instance of the form for the given `id`.
* The `id` is stringified and used for deduplication to potentially reuse existing instances.
* Useful when you have multiple forms that use the same remote form action, for example in a loop.
* ```svelte
* {#each todos as todo}
* {@const todoForm = updateTodo.for(todo.id)}
* <form {...todoForm}>
* {#if todoForm.result?.invalid}<p>Invalid data</p>{/if}
* ...
* </form>
* {/each}
* ```
*/
for(id: ExtractId<Input>): Omit<RemoteForm<Input, Output>, 'for'>;
/** Preflight checks */
preflight(schema: StandardSchemaV1<Input, any>): RemoteForm<Input, Output>;
/** Validate the form contents programmatically */
validate(options?: {
/** Set this to `true` to also show validation issues of fields that haven't been touched yet. */
includeUntouched?: boolean;
/** Set this to `true` to only run the `preflight` validation. */
preflightOnly?: boolean;
}): Promise<void>;
/** The result of the form submission */
get result(): Output | undefined;
/** The number of pending submissions */
get pending(): number;
/** True if the form has been submitted at least once */
get submitted(): boolean;
/** Access form fields using object notation */
fields: RemoteFormFieldsRoot<Input>;
};RemoteCommand
The type of a remote command function. See Remote functions for full documentation.
export type RemoteCommand<Input, Output> = {
(arg: undefined extends Input ? Input | void : Input): Promise<Output> & {
updates(...updates: RemoteQueryUpdate[]): Promise<Output>;
};
/** The number of pending command executions */
get pending(): number;
};RemoteQueryUpdate
export type RemoteQueryUpdate =
| RemoteQuery<any>
| RemoteLiveQuery<any>
| RemoteQueryFunction<any, any>
| RemoteLiveQueryFunction<any, any>
| RemoteQueryOverride;RemoteResource
export type type RemoteResource<T> = Promise<T> & ({
readonly error: any;
readonly loading: boolean;
} & ({
readonly current: undefined;
ready: false;
} | {
readonly current: T;
ready: true;
}))
type RemoteResource<T> = Promise<T> & ({
readonly error: any;
readonly loading: boolean;
} & ({
readonly current: undefined;
ready: false;
} | {
readonly current: T;
ready: true;
}))
RemoteResource<function (type parameter) T in type RemoteResource<T>function (type parameter) T in type RemoteResource<T>T> = interface Promise<T>Represents the completion of an asynchronous operation
interface Promise<T>Represents the completion of an asynchronous operation
Promise<function (type parameter) T in type RemoteResource<T>function (type parameter) T in type RemoteResource<T>T> & {
/** The error in case the query fails. Most often this is a [`HttpError`](https://svelte.dev/docs/kit/@sveltejs-kit#HttpError) but it isn't guaranteed to be. */
get error: anyThe error in case the query fails. Most often this is a HttpError but it isn't guaranteed to be.
error: anyThe error in case the query fails. Most often this is a HttpError but it isn't guaranteed to be.
error(): any;
/** `true` before the first result is available and during refreshes */
get loading: booleantrue before the first result is available and during refreshes
loading: booleantrue before the first result is available and during refreshes
loading(): boolean;
} & (
| {
/** The current value of the query. Undefined until `ready` is `true` */
get current: undefinedThe current value of the query. Undefined until ready is true
current: undefinedThe current value of the query. Undefined until ready is true
current(): undefined;
ready: falseready: falseready: false;
}
| {
/** The current value of the query. Undefined until `ready` is `true` */
get current: TThe current value of the query. Undefined until ready is true
current: TThe current value of the query. Undefined until ready is true
current(): function (type parameter) T in type RemoteResource<T>function (type parameter) T in type RemoteResource<T>T;
ready: trueready: trueready: true;
}
);RemoteQuery
export type RemoteQuery<T> = RemoteResource<T> & {
/**
* 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<void>;
/**
* 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
* <script>
* import { getTodos, addTodo } from './todos.remote.js';
* const todos = getTodos();
* </script>
*
* <form {...addTodo.enhance(async (form) => {
* await form.submit().updates(
* todos.withOverride((todos) => [...todos, { text: form.fields.text.value() }])
* );
* })}>
* <input type="text" name="text" />
* <button type="submit">Add Todo</button>
* </form>
* ```
*/
withOverride(update: (current: T) => T): RemoteQueryOverride;
};RemoteLiveQuery
export type RemoteLiveQuery<T> = RemoteResource<T> &
AsyncIterable<T> & {
/** `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<void>;
};RemoteQueryOverride
export type type RemoteQueryOverride = () => voidtype RemoteQueryOverride = () => voidRemoteQueryOverride = () => void;RemotePrerenderFunction
The type of a remote prerender function. See Remote functions for full documentation.
export type RemotePrerenderFunction<Input, Output> = (
arg: undefined extends Input ? Input | void : Input
) => RemoteResource<Output>;RemoteQueryFunction
The return value of a remote query function. See Remote functions 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. For queries declared
with Standard Schema 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.
export type RemoteQueryFunction<Input, Output, _Validated = Input> = (
arg: undefined extends Input ? Input | void : Input
) => RemoteQuery<Output>;RemoteLiveQueryFunction
The type of a remote query.live function. See Remote functions 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.
export type RemoteLiveQueryFunction<Input, Output, _Validated = Input> = (
arg: undefined extends Input ? Input | void : Input
) => RemoteLiveQuery<Output>;EnvVarConfig
Environment variables can be configured by exporting
a variables object from src/env.ts, using defineEnvVars.
export interface interface EnvVarConfig<T>interface EnvVarConfig<T>EnvVarConfig<function (type parameter) T in EnvVarConfig<T>function (type parameter) T in EnvVarConfig<T>T> {/*…*/}public?: boolean;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
static?: boolean;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
schema?: StandardSchemaV1<string | undefined, T>;A Standard Schema validator that is applied to the value when the app starts. The validator can output any value — not necessarily a string — but public, non-static values must be serializable by devalue so that they can be sent to the browser.
If omitted, the value must be a non-empty string.
description?: string;A description of the variable that will be used for inline documentation on hover.
PrerenderOption
export type type PrerenderOption = boolean | "auto"type PrerenderOption = boolean | "auto"PrerenderOption = boolean | 'auto';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 without invoking handleError.
Make sure you're not catching the thrown error, which would prevent SvelteKit from handling it.
export function error(status: number, body: App.Error): never;
export function error(status: number, body?: {
message: string;
} extends App.Error ? App.Error | string | undefined : never): never;isHttpError
Checks whether this is an error thrown by {@link error}.
export function isHttpError<T extends number>(e: unknown, status?: T): e is (HttpError_1 & {
status: T extends undefined ? never : T;
});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 method308 Permanent Redirect: redirect will keep the request method, SEO will be transferred to the new page
export function redirect(status: 300 | 301 | 302 | 303 | 304 | 305 | 306 | 307 | 308 | ({} & number), location: string | URL): never;isRedirect
Checks whether this is a redirect thrown by {@link redirect}.
export function isRedirect(e: unknown): e is Redirect_1;json
Create a JSON Response object from the supplied data.
export function json(data: any, init?: ResponseInit): Response;text
Create a Response object from the supplied body.
export function text(body: string, init?: ResponseInit): Response;fail
Create an ActionFailure object. Call when form submission fails.
export function fail(status: number): ActionFailure<undefined>;
export function fail<T = undefined>(status: number, data: T): ActionFailure<T>;isActionFailure
Checks whether this is an action failure thrown by {@link fail}.
export function isActionFailure(e: unknown): e is 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.
export function invalid(...issues: (StandardSchemaV1.Issue | string)[]): never;isValidationError
Available since 2.47.3
Checks whether this is an validation error thrown by {@link invalid}.
export function isValidationError(e: unknown): e is ActionFailure;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.
import { function normalizeUrl(url: URL | string): {
url: URL;
wasNormalized: boolean;
denormalize: (url?: string | URL) => URL;
}
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.
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
function normalizeUrl(url: URL | string): {
url: URL;
wasNormalized: boolean;
denormalize: (url?: string | URL) => URL;
}
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.
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
normalizeUrl } from '@sveltejs/kit';
const { const url: URLconst url: URLurl, const denormalize: (url?: string | URL) => URLconst denormalize: (url?: string | URL) => URLdenormalize } = function normalizeUrl(url: URL | string): {
url: URL;
wasNormalized: boolean;
denormalize: (url?: string | URL) => URL;
}
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.
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
function normalizeUrl(url: URL | string): {
url: URL;
wasNormalized: boolean;
denormalize: (url?: string | URL) => URL;
}
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.
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
normalizeUrl('/blog/post/__data.json');
var console: Consolevar console: Consoleconsole.Console.log(...data: any[]): voidThe console.log() static method outputs a message to the console.
Console.log(...data: any[]): voidThe console.log() static method outputs a message to the console.
log(const url: URLconst url: URLurl.URL.pathname: stringThe pathname property of the URL interface represents a location in a hierarchical structure. It is a string constructed from a list of path segments, each of which is prefixed by a / character.
URL.pathname: stringThe pathname property of the URL interface represents a location in a hierarchical structure. It is a string constructed from a list of path segments, each of which is prefixed by a / character.
pathname); // /blog/post
var console: Consolevar console: Consoleconsole.Console.log(...data: any[]): voidThe console.log() static method outputs a message to the console.
Console.log(...data: any[]): voidThe console.log() static method outputs a message to the console.
log(const denormalize: (url?: string | URL) => URLconst denormalize: (url?: string | URL) => URLdenormalize('/blog/post/a')); // /blog/post/a/__data.jsonexport function normalizeUrl(url: URL | string): {
url: URL;
wasNormalized: boolean;
denormalize: (url?: string | URL) => URL;
};LessThan
export type type LessThan<TNumber extends number, TArray extends any[] = []> = TNumber extends TArray["length"] ? TArray[number] : LessThan<TNumber, [...TArray, TArray["length"]]>type LessThan<TNumber extends number, TArray extends any[] = []> = TNumber extends TArray["length"] ? TArray[number] : LessThan<TNumber, [...TArray, TArray["length"]]>LessThan<function (type parameter) TNumber in type LessThan<TNumber extends number, TArray extends any[] = []>function (type parameter) TNumber in type LessThan<TNumber extends number, TArray extends any[] = []>TNumber extends number, function (type parameter) TArray in type LessThan<TNumber extends number, TArray extends any[] = []>function (type parameter) TArray in type LessThan<TNumber extends number, TArray extends any[] = []>TArray extends any[] = []> = function (type parameter) TNumber in type LessThan<TNumber extends number, TArray extends any[] = []>function (type parameter) TNumber in type LessThan<TNumber extends number, TArray extends any[] = []>TNumber extends function (type parameter) TArray in type LessThan<TNumber extends number, TArray extends any[] = []>function (type parameter) TArray in type LessThan<TNumber extends number, TArray extends any[] = []>TArray["length"] ? function (type parameter) TArray in type LessThan<TNumber extends number, TArray extends any[] = []>function (type parameter) TArray in type LessThan<TNumber extends number, TArray extends any[] = []>TArray[number] : type LessThan<TNumber extends number, TArray extends any[] = []> = TNumber extends TArray["length"] ? TArray[number] : LessThan<TNumber, [...TArray, TArray["length"]]>type LessThan<TNumber extends number, TArray extends any[] = []> = TNumber extends TArray["length"] ? TArray[number] : LessThan<TNumber, [...TArray, TArray["length"]]>LessThan<function (type parameter) TNumber in type LessThan<TNumber extends number, TArray extends any[] = []>function (type parameter) TNumber in type LessThan<TNumber extends number, TArray extends any[] = []>TNumber, [...function (type parameter) TArray in type LessThan<TNumber extends number, TArray extends any[] = []>function (type parameter) TArray in type LessThan<TNumber extends number, TArray extends any[] = []>TArray, function (type parameter) TArray in type LessThan<TNumber extends number, TArray extends any[] = []>function (type parameter) TArray in type LessThan<TNumber extends number, TArray extends any[] = []>TArray["length"]]>;NumericRange
export type NumericRange<TStart extends number, TEnd extends number> = Exclude<TEnd | LessThan<TEnd>, LessThan<TStart>>;VERSION
export const VERSION: string;Private types
The following are referenced by the public types documented above, but cannot be imported directly:
Adapter
Adapters are responsible for taking the production build and turning it into something that can be deployed to a platform of your choosing.
export interface Adapter {/*…*/}name: string;The name of the adapter, using for logging. Will typically correspond to the package name.
adapt: (builder: Builder) => MaybePromise<void>;This function is called after SvelteKit has built your app.
supports?: {
/**
* Test support for `read` from `$app/server`.
* @param details.config The merged adapter-specific route config exported from the route with `export const config`
*/
read?: (details: { config: any; route: { id: string } }) => boolean;
/**
* Test support for `instrumentation.server.js`. To pass, the adapter must support running `instrumentation.server.js` prior to the application code.
* @since 2.31.0
*/
instrumentation?: () => boolean;
};Checks called during dev and build to determine whether specific features will work in production with this adapter.
emulate?: () => MaybePromise<Emulator>;Creates an Emulator, which allows the adapter to influence the environment
during dev, build and prerendering.
LoadProperties
export type type LoadProperties<input extends Record<string, any> | void> = input extends void ? undefined : input extends Record<string, any> ? input : unknowntype LoadProperties<input extends Record<string, any> | void> = input extends void ? undefined : input extends Record<string, any> ? input : unknownLoadProperties<function (type parameter) input in type LoadProperties<input extends Record<string, any> | void>function (type parameter) input in type LoadProperties<input extends Record<string, any> | void>input extends type Record<K extends keyof any, T> = { [P in K]: T; }Construct a type with a set of properties K of type T
type Record<K extends keyof any, T> = { [P in K]: T; }Construct a type with a set of properties K of type T
Record<string, any> | void> = function (type parameter) input in type LoadProperties<input extends Record<string, any> | void>function (type parameter) input in type LoadProperties<input extends Record<string, any> | void>input extends void
? undefined // needs to be undefined, because void will break intellisense
: function (type parameter) input in type LoadProperties<input extends Record<string, any> | void>function (type parameter) input in type LoadProperties<input extends Record<string, any> | void>input extends type Record<K extends keyof any, T> = { [P in K]: T; }Construct a type with a set of properties K of type T
type Record<K extends keyof any, T> = { [P in K]: T; }Construct a type with a set of properties K of type T
Record<string, any>
? function (type parameter) input in type LoadProperties<input extends Record<string, any> | void>function (type parameter) input in type LoadProperties<input extends Record<string, any> | void>input
: unknown;AwaitedActions
export type AwaitedActions<T extends Record<string, (...args: any) => any>> = OptionalUnion<
{
[Key in keyof T]: UnpackValidationError<Awaited<ReturnType<T[Key]>>>;
}[keyof T]
>;ActionFailure
export interface interface ActionFailure<T = undefined>interface ActionFailure<T = undefined>ActionFailure<function (type parameter) T in ActionFailure<T = undefined>function (type parameter) T in ActionFailure<T = undefined>T = undefined> {/*…*/}status: number;data: T;[uniqueSymbol]: true;Builder
This object is passed to the adapt function of adapters.
It contains various methods and properties that are useful for adapting the app.
export interface Builder {/*…*/}log: Logger;Print messages to the console. log.info and log.minor are silent unless Vite's logLevel is info.
rimraf: (dir: string) => void;Remove dir and all its contents.
mkdirp: (dir: string) => void;Create dir and any required parent directories.
config: ValidatedConfig;The fully resolved Svelte config.
prerendered: Prerendered;Information about prerendered pages and assets, if any.
routes: RouteDefinition[];An array of all routes (including prerendered)
createEntries: (fn: (route: RouteDefinition) => AdapterEntry) => Promise<void>;Create separate functions that map to one or more routes of your app.
findServerAssets: (routes: RouteDefinition[]) => string[];Find all the assets imported by server files belonging to routes
generateFallback: (dest: stringdest: stringdest: string) => var Promise: PromiseConstructorRepresents the completion of an asynchronous operation
var Promise: PromiseConstructorRepresents the completion of an asynchronous operation
Promise<void>;Generate a fallback page for a static webserver to use when no route is matched. Useful for single-page apps.
generateEnvModule: () => void;Generate a module exposing build-time environment variables as $env/dynamic/public or $app/env/public if the app uses it.
generateManifest: (opts: { relativePath: string; routes?: RouteDefinition[] }) => string;Generate a server-side manifest to initialise the SvelteKit server with.
getBuildDirectory: (name: string) => string;Resolve a path to the name directory inside outDir, e.g. /path/to/.svelte-kit/my-adapter.
getClientDirectory: () => string;Get the fully resolved path to the directory containing client-side assets, including the contents of your static directory.
getServerDirectory: () => string;Get the fully resolved path to the directory containing server-side code.
getAppPath: () => string;Get the application path including any configured base path, e.g. my-base-path/_app.
writeClient: (dest: string) => string[];Write client assets to dest.
writePrerendered: (dest: string) => string[];Write prerendered files to dest.
writeServer: (dest: string) => string[];Write server-side code to dest.
copy: (
from: string,
to: string,
opts?: {
filter?(basename: string): boolean;
replace?: Record<string, string>;
}
) => string[];Copy a file or directory.
hasServerInstrumentationFile: () => boolean;Check if the server instrumentation file exists.
instrument: (args: {
entrypoint: string;
instrumentation: string;
start?: string;
module?:
| {
exports: string[];
}
| {
generateText: (args: { instrumentation: string; start: string }) => string;
};
}) => void;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
tlaisfalse, OTEL auto-instrumentation may not work properly. Use it if your environment supports it. - Use
hasServerInstrumentationFileto check if the user has a server instrumentation file; if they don't, you shouldn't do this.
compress: (directory: stringdirectory: stringdirectory: string) => var Promise: PromiseConstructorRepresents the completion of an asynchronous operation
var Promise: PromiseConstructorRepresents the completion of an asynchronous operation
Promise<void>;Compress files in directory with gzip and brotli, where appropriate. Generates .gz and .br files alongside the originals.
Config
An extension of vite-plugin-svelte's options.
export interface Config extends SvelteConfig {/*…*/}kit?: KitConfig;SvelteKit options.
[key: string]: any;Any additional options required by tooling that integrates with Svelte.
Cookies
export interface Cookies {/*…*/}get: (name: string, opts?: import('cookie').CookieParseOptions) => string | undefined;Gets a cookie that was previously set with cookies.set, or from the request headers.
getAll: (opts?: import('cookie').CookieParseOptions) => Array<{ name: string; value: string }>;Gets all cookies that were previously set with cookies.set, or from the request headers.
set: (
name: string,
value: string,
opts: import('cookie').CookieSerializeOptions & { path: string }
) => void;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 and secure options are true by default (except on http://localhost, where secure is false), and must be explicitly disabled if you want cookies to be readable by client-side JavaScript and/or transmitted over HTTP. The sameSite option defaults to lax.
You must specify a path for the cookie. In most cases you should explicitly set path: '/' to make the cookie available throughout your app. You can use relative paths, or set path: '' to make the cookie only available on the current path and its children
delete: (name: string, opts: import('cookie').CookieSerializeOptions & { path: string }) => void;Deletes a cookie by setting its value to an empty string and setting the expiry date in the past.
You must specify a path for the cookie. In most cases you should explicitly set path: '/' to make the cookie available throughout your app. You can use relative paths, or set path: '' to make the cookie only available on the current path and its children
serialize: (
name: string,
value: string,
opts: import('cookie').CookieSerializeOptions & { path: string }
) => string;Serialize a cookie name-value pair into a Set-Cookie header string, but don't apply it to the response.
The httpOnly and secure options are true by default (except on http://localhost, where secure is false), and must be explicitly disabled if you want cookies to be readable by client-side JavaScript and/or transmitted over HTTP. The sameSite option defaults to lax.
You must specify a path for the cookie. In most cases you should explicitly set path: '/' to make the cookie available throughout your app. You can use relative paths, or set path: '' to make the cookie only available on the current path and its children
Emulator
A collection of functions that influence the environment during dev, build and prerendering
export interface Emulator {/*…*/}platform?(details: { config: any; prerender: PrerenderOption }): MaybePromise<App.Platform>;A function that is called with the current route config and prerender option
and returns an App.Platform object
KitConfig
export interface KitConfig {/*…*/}adapter?: Adapter;Your adapter is run when executing vite build. It determines how the output is converted for different platforms.
alias?: Record<string, string>;An object containing zero or more aliases used to replace values in import statements. These aliases are automatically passed to Vite and TypeScript.
/// type: import('@sveltejs/kit').Config
const const config: {
kit: {
alias: {
'my-file': string;
'my-directory': string;
'my-directory/*': string;
};
};
}
const config: {
kit: {
alias: {
'my-file': string;
'my-directory': string;
'my-directory/*': string;
};
};
}
config = {
kit: {
alias: {
'my-file': string;
'my-directory': string;
'my-directory/*': string;
};
}
kit: {
alias: {
'my-file': string;
'my-directory': string;
'my-directory/*': string;
};
}
kit: {
alias: {
'my-file': string;
'my-directory': string;
'my-directory/*': string;
}
alias: {
'my-file': string;
'my-directory': string;
'my-directory/*': string;
}
alias: {
// this will match a file
'my-file': 'path/to/my-file.js',
// this will match a directory and its contents
// (`my-directory/x` resolves to `path/to/my-directory/x`)
'my-directory': 'path/to/my-directory',
// an alias ending /* will only match
// the contents of a directory, not the directory itself
'my-directory/*': 'path/to/my-directory/*'
}
}
};You will need to run
npm run devto have SvelteKit automatically generate the required alias configuration injsconfig.jsonortsconfig.json.
appDir?: string;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?: {
/**
* Whether to use hashes or nonces to restrict `<script>` and `<style>` elements. `'auto'` will use hashes for prerendered pages, and nonces for dynamically rendered pages.
*/
mode?: 'hash' | 'nonce' | 'auto';
/**
* Directives that will be added to `Content-Security-Policy` headers.
*/
directives?: CspDirectives;
/**
* Directives that will be added to `Content-Security-Policy-Report-Only` headers.
*/
reportOnly?: CspDirectives;
};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...
/// type: import('@sveltejs/kit').Config
const const config: {
kit: {
csp: {
directives: {
'script-src': string[];
};
reportOnly: {
'script-src': string[];
'report-uri': string[];
};
};
};
}
const config: {
kit: {
csp: {
directives: {
'script-src': string[];
};
reportOnly: {
'script-src': string[];
'report-uri': string[];
};
};
};
}
config = {
kit: {
csp: {
directives: {
'script-src': string[];
};
reportOnly: {
'script-src': string[];
'report-uri': string[];
};
};
}
kit: {
csp: {
directives: {
'script-src': string[];
};
reportOnly: {
'script-src': string[];
'report-uri': string[];
};
};
}
kit: {
csp: {
directives: {
'script-src': string[];
};
reportOnly: {
'script-src': string[];
'report-uri': string[];
};
}
csp: {
directives: {
'script-src': string[];
};
reportOnly: {
'script-src': string[];
'report-uri': string[];
};
}
csp: {
directives: {
'script-src': string[];
}
directives: {
'script-src': string[];
}
directives: {
'script-src': ['self']
},
// must be specified with either the `report-uri` or `report-to` directives, or both
reportOnly: {
'script-src': string[];
'report-uri': string[];
}
reportOnly: {
'script-src': string[];
'report-uri': string[];
}
reportOnly: {
'script-src': ['self'],
'report-uri': ['/']
}
}
}
};
export default const config: {
kit: {
csp: {
directives: {
'script-src': string[];
};
reportOnly: {
'script-src': string[];
'report-uri': string[];
};
};
};
}
const config: {
kit: {
csp: {
directives: {
'script-src': string[];
};
reportOnly: {
'script-src': string[];
'report-uri': string[];
};
};
};
}
config;...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 <script nonce="%sveltekit.nonce%">).
When pages are prerendered, the CSP header is added via a <meta http-equiv> tag (note that in this case, frame-ancestors, report-uri and sandbox directives will be ignored).
When
modeis'auto', SvelteKit will use nonces for dynamically rendered pages and hashes for prerendered pages. Using nonces with prerendered pages is insecure and therefore forbidden.
Note that most Svelte transitions work by creating an inline
<style>element. If you use these in your app, you must either leave thestyle-srcdirective unspecified or addunsafe-inline.
If this level of configuration is insufficient and you have more dynamic requirements, you can use the handle hook to roll your own CSP.
csrf?: {
/**
* Whether to check the incoming `origin` header for `POST`, `PUT`, `PATCH`, or `DELETE` form submissions and verify that it matches the server's origin.
*
* To allow people to make `POST`, `PUT`, `PATCH`, or `DELETE` requests with a `Content-Type` of `application/x-www-form-urlencoded`, `multipart/form-data`, or `text/plain` to your app from other origins, you will need to disable this option. Be careful!
* @default true
* @deprecated Use `trustedOrigins: ['*']` instead
*/
checkOrigin?: boolean;
/**
* An array of origins that are allowed to make cross-origin form submissions to your app.
*
* Each origin should be a complete origin including protocol (e.g., `https://payment-gateway.com`).
* This is useful for allowing trusted third-party services like payment gateways or authentication providers to submit forms to your app.
*
* If the array contains `'*'`, all origins will be trusted. This is generally not recommended!
*
* > [!NOTE] Only add origins you completely trust, as this bypasses CSRF protection for those origins.
*
* CSRF checks only apply in production, not in local development.
* @default []
* @example ['https://checkout.stripe.com', 'https://accounts.google.com']
*/
trustedOrigins?: string[];
};Protection against cross-site request forgery (CSRF) attacks.
embedded?: boolean;Whether or not the app is embedded inside a larger app. If true, SvelteKit will add its event listeners related to navigation etc on the parent of %sveltekit.body% instead of window, and will pass params from the server rather than inferring them from location.pathname.
Note that it is generally not supported to embed multiple SvelteKit apps on the same page and use client-side SvelteKit features within them (things such as pushing to the history state assume a single instance).
env?: {
/**
* The directory to search for `.env` files.
* @default "."
*/
dir?: string;
/**
* A prefix that signals that an environment variable is safe to expose to client-side code. See [`$env/static/public`](https://svelte.dev/docs/kit/$env-static-public) and [`$env/dynamic/public`](https://svelte.dev/docs/kit/$env-dynamic-public). Note that Vite's [`envPrefix`](https://vitejs.dev/config/shared-options.html#envprefix) must be set separately if you are using Vite's environment variable handling - though use of that feature should generally be unnecessary.
* @default "PUBLIC_"
*/
publicPrefix?: string;
/**
* A prefix that signals that an environment variable is unsafe to expose to client-side code. Environment variables matching neither the public nor the private prefix will be discarded completely. See [`$env/static/private`](https://svelte.dev/docs/kit/$env-static-private) and [`$env/dynamic/private`](https://svelte.dev/docs/kit/$env-dynamic-private).
* @default ""
* @since 1.21.0
*/
privatePrefix?: string;
};Environment variable configuration
experimental?: {
/**
* Whether to enable explicit environment variables using `src/env.js` or `src/env.ts`.
* @since 2.63.0
* @default false
*/
explicitEnvironmentVariables?: boolean;
/**
* Options for enabling server-side [OpenTelemetry](https://opentelemetry.io/) tracing for SvelteKit operations including the [`handle` hook](https://svelte.dev/docs/kit/hooks#handle), [`load` functions](https://svelte.dev/docs/kit/load), [form actions](https://svelte.dev/docs/kit/form-actions), and [remote functions](https://svelte.dev/docs/kit/remote-functions).
* @default { server: false, serverFile: false }
* @since 2.31.0
*/
tracing?: {
/**
* Enables server-side [OpenTelemetry](https://opentelemetry.io/) span emission for SvelteKit operations including the [`handle` hook](https://svelte.dev/docs/kit/hooks#handle), [`load` functions](https://svelte.dev/docs/kit/load), [form actions](https://svelte.dev/docs/kit/form-actions), and [remote functions](https://svelte.dev/docs/kit/remote-functions).
* @default false
* @since 2.31.0
*/
server?: boolean;
};
/**
* @since 2.31.0
*/
instrumentation?: {
/**
* Enables `instrumentation.server.js` for tracing and observability instrumentation.
* @default false
* @since 2.31.0
*/
server?: boolean;
};
/**
* Whether to enable the experimental remote functions feature. This feature is not yet stable and may be changed or removed at any time.
* @default false
*/
remoteFunctions?: boolean;
/**
* Whether to enable the experimental forked preloading feature using Svelte's fork API.
* @default false
*/
forkPreloads?: boolean;
/**
* Whether to enable the experimental handling of rendering errors.
* When enabled, `<svelte:boundary>` is used to wrap components at each level
* where there's an `+error.svelte`, rendering the error page if the component fails.
* In addition, error boundaries also work on the server and the error object goes through `handleError`.
* @default false
*/
handleRenderingErrors?: boolean;
};Experimental features. Here be dragons. These are not subject to semantic versioning, so breaking changes or removal can happen in any release.
files?: {
/**
* The location of your source code.
* @deprecated this feature is still supported, but it's generally recommended to use [monorepos](https://levelup.video/tutorials/monorepos-with-pnpm) instead
* @default "src"
* @since 2.28
*/
src?: string;
/**
* A place to put static files that should have stable URLs and undergo no processing, such as `favicon.ico` or `manifest.json`.
* @deprecated this feature is still supported, but it's generally recommended to use [monorepos](https://levelup.video/tutorials/monorepos-with-pnpm) instead
* @default "static"
*/
assets?: string;
hooks?: {
/**
* The location of your client [hooks](https://svelte.dev/docs/kit/hooks).
* @deprecated this feature is still supported, but it's generally recommended to use [monorepos](https://levelup.video/tutorials/monorepos-with-pnpm) instead
* @default "src/hooks.client"
*/
client?: string;
/**
* The location of your server [hooks](https://svelte.dev/docs/kit/hooks).
* @deprecated this feature is still supported, but it's generally recommended to use [monorepos](https://levelup.video/tutorials/monorepos-with-pnpm) instead
* @default "src/hooks.server"
*/
server?: string;
/**
* The location of your universal [hooks](https://svelte.dev/docs/kit/hooks).
* @deprecated this feature is still supported, but it's generally recommended to use [monorepos](https://levelup.video/tutorials/monorepos-with-pnpm) instead
* @default "src/hooks"
* @since 2.3.0
*/
universal?: string;
};
/**
* Your app's internal library, accessible throughout the codebase as `$lib`.
* @deprecated this feature is still supported, but it's generally recommended to use [monorepos](https://levelup.video/tutorials/monorepos-with-pnpm) instead
* @default "src/lib"
*/
lib?: string;
/**
* A directory containing [parameter matchers](https://svelte.dev/docs/kit/advanced-routing#Matching).
* @deprecated this feature is still supported, but it's generally recommended to use [monorepos](https://levelup.video/tutorials/monorepos-with-pnpm) instead
* @default "src/params"
*/
params?: string;
/**
* The files that define the structure of your app (see [Routing](https://svelte.dev/docs/kit/routing)).
* @deprecated this feature is still supported, but it's generally recommended to use [monorepos](https://levelup.video/tutorials/monorepos-with-pnpm) instead
* @default "src/routes"
*/
routes?: string;
/**
* The location of your service worker's entry point (see [Service workers](https://svelte.dev/docs/kit/service-workers)).
* @deprecated this feature is still supported, but it's generally recommended to use [monorepos](https://levelup.video/tutorials/monorepos-with-pnpm) instead
* @default "src/service-worker"
*/
serviceWorker?: string;
/**
* The location of the template for HTML responses.
* @deprecated this feature is still supported, but it's generally recommended to use [monorepos](https://levelup.video/tutorials/monorepos-with-pnpm) instead
* @default "src/app.html"
*/
appTemplate?: string;
/**
* The location of the template for fallback error responses.
* @deprecated this feature is still supported, but it's generally recommended to use [monorepos](https://levelup.video/tutorials/monorepos-with-pnpm) instead
* @default "src/error.html"
*/
errorTemplate?: string;
};Where to find various files within your project.
inlineStyleThreshold?: number;Inline CSS inside a <style> block at the head of the HTML. This option is a number that specifies the maximum length of a CSS file in UTF-16 code units, as specified by the String.length property, to be inlined. All CSS files needed for the page that are smaller than this value are merged and inlined in a <style> block.
This results in fewer initial requests and can improve your First Contentful Paint score. However, it generates larger HTML output and reduces the effectiveness of browser caches. Use it advisedly.
moduleExtensions?: string[];An array of file extensions that SvelteKit will treat as modules. Files with extensions that match neither config.extensions nor config.kit.moduleExtensions will be ignored by the router.
outDir?: string;The directory that SvelteKit writes files to during dev and build. You should exclude this directory from version control.
output?: {
/**
* SvelteKit will preload the JavaScript modules needed for the initial page to avoid import 'waterfalls', resulting in faster application startup. There
* are three strategies with different trade-offs:
* - `modulepreload` - uses `<link rel="modulepreload">`. This delivers the best results in Chromium-based browsers, in Firefox 115+, and Safari 17+. It is ignored in older browsers.
* - `preload-js` - uses `<link rel="preload">`. Prevents waterfalls in Chromium and Safari, but Chromium will parse each module twice (once as a script, once as a module). Causes modules to be requested twice in Firefox. This is a good setting if you want to maximise performance for users on iOS devices at the cost of a very slight degradation for Chromium users.
* - `preload-mjs` - uses `<link rel="preload">` but with the `.mjs` extension which prevents double-parsing in Chromium. Some static webservers will fail to serve .mjs files with a `Content-Type: application/javascript` header, which will cause your application to break. If that doesn't apply to you, this is the option that will deliver the best performance for the largest number of users, until `modulepreload` is more widely supported.
* @default "modulepreload"
* @since 1.8.4
*/
preloadStrategy?: 'modulepreload' | 'preload-js' | 'preload-mjs';
/**
* The bundle strategy option affects how your app's JavaScript and CSS files are loaded.
* - If `'split'`, splits the app up into multiple .js/.css files so that they are loaded lazily as the user navigates around the app. This is the default, and is recommended for most scenarios.
* - If `'single'`, creates just one .js bundle and one .css file containing code for the entire app.
* - If `'inline'`, inlines all JavaScript and CSS of the entire app into the HTML. The result is usable without a server (i.e. you can just open the file in your browser).
*
* When using `'split'`, you can also adjust the bundling behaviour by setting [`output.experimentalMinChunkSize`](https://rollupjs.org/configuration-options/#output-experimentalminchunksize) and [`output.manualChunks`](https://rollupjs.org/configuration-options/#output-manualchunks) inside your Vite config's [`build.rollupOptions`](https://vite.dev/config/build-options.html#build-rollupoptions).
*
* If you want to inline your assets, you'll need to set Vite's [`build.assetsInlineLimit`](https://vite.dev/config/build-options.html#build-assetsinlinelimit) option to an appropriate size then import your assets through Vite.
*
* ```js
* /// file: vite.config.js
* import { sveltekit } from '@sveltejs/kit/vite';
* import { defineConfig } from 'vite';
*
* export default defineConfig({
* plugins: [sveltekit()],
* build: {
* // inline all imported assets
* assetsInlineLimit: Infinity
* }
* });
* ```
*
* ```svelte
* /// file: src/routes/+layout.svelte
* <script>
* // import the asset through Vite
* import favicon from './favicon.png';
* </script>
*
* <svelte:head>
* <!-- this asset will be inlined as a base64 URL -->
* <link rel="icon" href={favicon} />
* </svelte:head>
* ```
* @default 'split'
* @since 2.13.0
*/
bundleStrategy?: 'split' | 'single' | 'inline';
};Options related to the build output format
paths?: {
/**
* An absolute path that your app's files are served from. This is useful if your files are served from a storage bucket of some kind.
* @default ""
*/
assets?: '' | `http://${string}` | `https://${string}`;
/**
* A root-relative path that must start, but not end with `/` (e.g. `/base-path`), unless it is the empty string. This specifies where your app is served from and allows the app to live on a non-root path. Note that you need to prepend all your root-relative links with the base value or they will point to the root of your domain, not your `base` (this is how the browser works). You can use [`base` from `$app/paths`](https://svelte.dev/docs/kit/$app-paths#base) for that: `<a href="{base}/your-page">Link</a>`. If you find yourself writing this often, it may make sense to extract this into a reusable component.
* @default ""
*/
base?: '' | `/${string}`;
/**
* Whether to use relative asset paths.
*
* If `true`, `base` and `assets` imported from `$app/paths` will be replaced with relative asset paths during server-side rendering, resulting in more portable HTML.
* If `false`, `%sveltekit.assets%` and references to build artifacts will always be root-relative paths, unless `paths.assets` is an external URL
*
* [Single-page app](https://svelte.dev/docs/kit/single-page-apps) fallback pages will always use absolute paths, regardless of this setting.
*
* If your app uses a `<base>` element, you should set this to `false`, otherwise asset URLs will incorrectly be resolved against the `<base>` URL rather than the current page.
*
* In 1.0, `undefined` was a valid value, which was set by default. In that case, if `paths.assets` was not external, SvelteKit would replace `%sveltekit.assets%` with a relative path and use relative paths to reference build artifacts, but `base` and `assets` imported from `$app/paths` would be as specified in your config.
*
* @default true
* @since 1.9.0
*/
relative?: boolean;
};prerender?: {
/**
* How many pages can be prerendered simultaneously. JS is single-threaded, but in cases where prerendering performance is network-bound (for example loading content from a remote CMS) this can speed things up by processing other tasks while waiting on the network response.
* @default 1
*/
concurrency?: number;
/**
* Whether SvelteKit should find pages to prerender by following links from `entries`.
* @default true
*/
crawl?: boolean;
/**
* An array of pages to prerender, or start crawling from (if `crawl: true`). The `*` string includes all routes containing no required `[parameters]` with optional parameters included as being empty (since SvelteKit doesn't know what value any parameters should have).
* @default ["*"]
*/
entries?: Array<'*' | `/${string}`>;
/**
* How to respond to HTTP errors encountered while prerendering the app.
*
* - `'fail'` — fail the build
* - `'ignore'` - silently ignore the failure and continue
* - `'warn'` — continue, but print a warning
* - `(details) => void` — a custom error handler that takes a `details` object with `status`, `path`, `referrer`, `referenceType` and `message` properties. If you `throw` from this function, the build will fail
*
* ```js
* /// file: svelte.config.js
* /// type: import('@sveltejs/kit').Config
* const config = {
* kit: {
* prerender: {
* handleHttpError: ({ path, referrer, message }) => {
* // ignore deliberate link to shiny 404 page
* if (path === '/not-found' && referrer === '/blog/how-we-built-our-404-page') {
* return;
* }
*
* // otherwise fail the build
* throw new Error(message);
* }
* }
* }
* };
* ```
*
* @default "fail"
* @since 1.15.7
*/
handleHttpError?: PrerenderHttpErrorHandlerValue;
/**
* How to respond when hash links from one prerendered page to another don't correspond to an `id` on the destination page.
*
* - `'fail'` — fail the build
* - `'ignore'` - silently ignore the failure and continue
* - `'warn'` — continue, but print a warning
* - `(details) => void` — a custom error handler that takes a `details` object with `path`, `id`, `referrers` and `message` properties. If you `throw` from this function, the build will fail
*
* @default "fail"
* @since 1.15.7
*/
handleMissingId?: PrerenderMissingIdHandlerValue;
/**
* How to respond when an entry generated by the `entries` export doesn't match the route it was generated from.
*
* - `'fail'` — fail the build
* - `'ignore'` - silently ignore the failure and continue
* - `'warn'` — continue, but print a warning
* - `(details) => void` — a custom error handler that takes a `details` object with `generatedFromId`, `entry`, `matchedId` and `message` properties. If you `throw` from this function, the build will fail
*
* @default "fail"
* @since 1.16.0
*/
handleEntryGeneratorMismatch?: PrerenderEntryGeneratorMismatchHandlerValue;
/**
* How to respond when a route is marked as prerenderable but has not been prerendered.
*
* - `'fail'` — fail the build
* - `'ignore'` - silently ignore the failure and continue
* - `'warn'` — continue, but print a warning
* - `(details) => void` — a custom error handler that takes a `details` object with a `routes` property which contains all routes that haven't been prerendered. If you `throw` from this function, the build will fail
*
* The default behavior is to fail the build. This may be undesirable when you know that some of your routes may never be reached under certain
* circumstances such as a CMS not returning data for a specific area, resulting in certain routes never being reached.
*
* @default "fail"
* @since 2.16.0
*/
handleUnseenRoutes?: PrerenderUnseenRoutesHandlerValue;
/**
* How to respond when SvelteKit encounters a URL it cannot parse while crawling prerendered HTML (for example, an AT Protocol URL such as `at://did:plc:...`).
*
* - `'fail'` — fail the build
* - `'ignore'` - silently ignore the failure and continue
* - `'warn'` — continue, but print a warning
* - `(details) => void` — a custom error handler that takes a `details` object with `href`, `referrer` and `message` properties. If you `throw` from this function, the build will fail
*
* @default "fail"
* @since 2.67.0
*/
handleInvalidUrl?: PrerenderInvalidUrlHandlerValue;
/**
* The value of `url.origin` during prerendering; useful if it is included in rendered content.
* @default "http://sveltekit-prerender"
*/
origin?: string;
};See Prerendering.
router?: {
/**
* What type of client-side router to use.
* - `'pathname'` is the default and means the current URL pathname determines the route
* - `'hash'` means the route is determined by `location.hash`. In this case, SSR and prerendering are disabled. This is only recommended if `pathname` is not an option, for example because you don't control the webserver where your app is deployed.
* It comes with some caveats: you can't use server-side rendering (or indeed any server logic), and you have to make sure that the links in your app all start with #/, or they won't work. Beyond that, everything works exactly like a normal SvelteKit app.
*
* @default "pathname"
* @since 2.14.0
*/
type?: 'pathname' | 'hash';
/**
* How to determine which route to load when navigating to a new page.
*
* By default, SvelteKit will serve a route manifest to the browser.
* When navigating, this manifest is used (along with the `reroute` hook, if it exists) to determine which components to load and which `load` functions to run.
* Because everything happens on the client, this decision can be made immediately. The drawback is that the manifest needs to be
* loaded and parsed before the first navigation can happen, which may have an impact if your app contains many routes.
*
* Alternatively, SvelteKit can determine the route on the server. This means that for every navigation to a path that has not yet been visited, the server will be asked to determine the route.
* This has several advantages:
* - The client does not need to load the routing manifest upfront, which can lead to faster initial page loads
* - The list of routes is hidden from public view
* - The server has an opportunity to intercept each navigation (for example through a middleware), enabling (for example) A/B testing opaque to SvelteKit
* The drawback is that for unvisited paths, resolution will take slightly longer (though this is mitigated by [preloading](https://svelte.dev/docs/kit/link-options#data-sveltekit-preload-data)).
*
* > [!NOTE] When using server-side route resolution and prerendering, the resolution is prerendered along with the route itself.
*
* @default "client"
* @since 2.17.0
*/
resolution?: 'client' | 'server';
};serviceWorker?: {
/**
* Determine which files in your `static` directory will be available in `$service-worker.files`.
* @default (filename) => !/\.DS_Store/.test(filename)
*/
files?: (file: string) => boolean;
} & (
| {
/**
* Whether to automatically register the service worker, if it exists.
* @default true
*/
register: true;
/**
* Options for serviceWorker.register("...", options);
*/
options?: RegistrationOptions;
}
| {
/**
* Whether to automatically register the service worker, if it exists.
* @default true
*/
register?: false;
}
);typescript?: {
/**
* A function that allows you to edit the generated `tsconfig.json`. You can mutate the config (recommended) or return a new one.
* This is useful for extending a shared `tsconfig.json` in a monorepo root, for example.
*
* Note that any paths configured here should be relative to the generated config file, which is written to `.svelte-kit/tsconfig.json`.
*
* @default (config) => config
* @since 1.3.0
*/
config?: (config: Record<string, any>) => Record<string, any> | void;
};version?: {
/**
* The current app version string. If specified, this must be deterministic (e.g. a commit ref rather than `Math.random()` or `Date.now().toString()`), otherwise defaults to a timestamp of the build.
*
* For example, to use the current commit hash, you could do use `git rev-parse HEAD`:
*
* ```js
* /// file: svelte.config.js
* import * as child_process from 'node:child_process';
*
* export default {
* kit: {
* version: {
* name: child_process.execSync('git rev-parse HEAD').toString().trim()
* }
* }
* };
* ```
*/
name?: string;
/**
* The interval in milliseconds to poll for version changes. If this is `0`, no polling occurs.
* @default 0
*/
pollInterval?: number;
};Client-side navigation can be buggy if you deploy a new version of your app while people are using it. If the code for the new page is already loaded, it may have stale content; if it isn't, the app's route manifest may point to a JavaScript file that no longer exists.
SvelteKit helps you solve this problem through version management.
If SvelteKit encounters an error while loading the page and detects that a new version has been deployed (using the name specified here, which defaults to a timestamp of the build) it will fall back to traditional full-page navigation.
Not all navigations will result in an error though, for example if the JavaScript for the next page is already loaded. If you still want to force a full-page navigation in these cases, use techniques such as setting the pollInterval and then using beforeNavigate:
<script>
import { beforeNavigate } from '$app/navigation';
import { updated } from '$app/state';
beforeNavigate(({ willUnload, to }) => {
if (updated.current && !willUnload && to?.url) {
location.href = to.url.href;
}
});
</script>If you set pollInterval to a non-zero value, SvelteKit will poll for new versions in the background and set the value of updated.current true when it detects one.
Handle
The handle hook runs every time the SvelteKit server receives a request and
determines the 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).
export type Handle = (input: {
event: RequestEvent;
resolve: (event: RequestEvent, opts?: ResolveOptions) => MaybePromise<Response>;
}) => MaybePromise<Response>;HandleServerError
The server-side handleError hook runs when an unexpected error is thrown while responding to a request.
If an unexpected error is thrown during loading or rendering, this function will be called with the error and the event. Make sure that this function never throws an error.
export type HandleServerError = (input: {
error: unknown;
event: RequestEvent;
status: number;
message: string;
}) => MaybePromise<void | App.Error>;HandleValidationError
The handleValidationError hook runs when the argument to a remote function fails validation.
It will be called with the validation issues and the event, and must return an object shape that matches App.Error.
export type HandleValidationError<Issue extends StandardSchemaV1.Issue = StandardSchemaV1.Issue> =
(input: { issues: Issue[]; event: RequestEvent }) => MaybePromise<App.Error>;HandleClientError
The client-side handleError hook runs when an unexpected error is thrown while navigating.
If an unexpected error is thrown during loading or the following render, this function will be called with the error and the event. Make sure that this function never throws an error.
export type HandleClientError = (input: {
error: unknown;
event: NavigationEvent;
status: number;
message: string;
}) => MaybePromise<void | App.Error>;HandleFetch
The handleFetch hook allows you to modify (or replace) the result of an event.fetch call that runs on the server (or during prerendering) inside an endpoint, load, action, handle, handleError or reroute.
export type HandleFetch = (input: {
event: RequestEvent;
request: Request;
fetch: typeof fetch;
}) => MaybePromise<Response>;ServerInit
Available since 2.10.0
The init will be invoked before the server responds to its first request
export type ServerInit = () => MaybePromise<void>;ClientInit
Available since 2.10.0
The init will be invoked once the app starts in the browser
export type ClientInit = () => MaybePromise<void>;Reroute
Available since 2.3.0
The reroute hook allows you to modify the URL before it is used to determine which route to render.
export type Reroute = (event: { url: URL; fetch: typeof fetch }) => MaybePromise<void | string>;Transport
Available since 2.11.0
The 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.
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)
}
};export type Transport = Record<string, Transporter>;Transporter
A member of the transport hook.
export interface interface Transporter<T = any, U = any>interface Transporter<T = any, U = any>Transporter<
function (type parameter) T in Transporter<T = any, U = any>function (type parameter) T in Transporter<T = any, U = any>T = any,
function (type parameter) U in Transporter<T = any, U = any>function (type parameter) U in Transporter<T = any, U = any>U = type Exclude<T, U> = T extends U ? never : TExclude from T those types that are assignable to U
type Exclude<T, U> = T extends U ? never : TExclude from T those types that are assignable to U
Exclude<any, false | 0 | '' | null | undefined | typeof var NaN: numbervar NaN: numberNaN>
> {/*…*/}encode: (value: T) => false | U;decode: (data: U) => T;Load
The generic form of PageLoad and LayoutLoad. You should import those from ./$types (see generated types)
rather than using Load directly.
export type Load<
Params extends AppLayoutParams<'/'> = AppLayoutParams<'/'>,
InputData extends Record<string, unknown> | null = Record<string, any> | null,
ParentData extends Record<string, unknown> = Record<string, any>,
OutputData extends Record<string, unknown> | void = Record<string, any> | void,
RouteId extends AppRouteId | null = AppRouteId | null
> = (event: LoadEvent<Params, InputData, ParentData, RouteId>) => MaybePromise<OutputData>;LoadEvent
The generic form of PageLoadEvent and LayoutLoadEvent. You should import those from ./$types (see generated types)
rather than using LoadEvent directly.
export interface LoadEvent<
Params extends AppLayoutParams<'/'> = AppLayoutParams<'/'>,
Data extends Record<string, unknown> | null = Record<string, any> | null,
ParentData extends Record<string, unknown> = Record<string, any>,
RouteId extends AppRouteId | null = AppRouteId | null
> extends NavigationEvent<Params, RouteId> {/*…*/}fetch: typeof function fetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> (+1 overload)function fetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> (+1 overload)fetch;fetch is equivalent to the native fetch web API, with a few additional features:
- It can be used to make credentialed requests on the server, as it inherits the
cookieandauthorizationheaders for the page request. - It can make relative requests on the server (ordinarily,
fetchrequires a URL with an origin when used in a server context). - Internal requests (e.g. for
+server.jsroutes) go directly to the handler function when running on the server, without the overhead of an HTTP call. - During server-side rendering, the response will be captured and inlined into the rendered HTML by hooking into the
textandjsonmethods of theResponseobject. Note that headers will not be serialized, unless explicitly included viafilterSerializedResponseHeaders - During hydration, the response will be read from the HTML, guaranteeing consistency and preventing an additional network request.
You can learn more about making credentialed requests with cookies here
data: Data;Contains the data returned by the route's server load function (in +layout.server.js or +page.server.js), if any.
setHeaders: (headers: Record<string, string>) => void;If you need to set headers for the response, you can do so using the this method. This is useful if you want the page to be cached, for example:
export async function 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 API in a server-only load function instead.
setHeaders has no effect when a load function runs in the browser.
parent: () => Promise<ParentData>;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.
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() 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.
Custom identifiers have to be prefixed with one or more lowercase letters followed by a colon to conform to the URI specification.
The following example shows how to use depends to register a dependency on a custom identifier, which is invalidated after a button click, making the load function rerun.
let count = 0;
export async function load({ depends }) {
depends('increase:count');
return { count: count++ };
}<script>
import { invalidate } from '$app/navigation';
let { data } = $props();
const increase = async () => {
await invalidate('increase:count');
}
</script>
<p>{data.count}<p>
<button on:click={increase}>Increase Count</button>untrack: <T>(fn: () => T) => T;Use this function to opt out of dependency tracking for everything that is synchronously called within the callback. Example:
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!' };
}
}tracing: {
/** Whether tracing is enabled. */
enabled: boolean;
/** The root span for the request. This span is named `sveltekit.handle.root`. */
root: Span;
/** The span associated with the current `load` function. */
current: Span;
};Access to spans for tracing. If tracing is not enabled or the function is being run in the browser, these spans will do nothing.
NavigationEvent
export interface NavigationEvent<
Params extends AppLayoutParams<'/'> = AppLayoutParams<'/'>,
RouteId extends AppRouteId | null = AppRouteId | null
> {/*…*/}params: Params;The parameters of the current page - e.g. for a route like /blog/[slug], a { slug: string } object
route: {
/**
* 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.
*/
id: RouteId;
};Info about the current route
url: var URL: {
new (url: string | URL, base?: string | URL): URL;
prototype: URL;
canParse(url: string | URL, base?: string | URL): boolean;
createObjectURL(obj: Blob | MediaSource): string;
parse(url: string | URL, base?: string | URL): URL | null;
revokeObjectURL(url: string): void;
}
The URL interface is used to parse, construct, normalize, and encode URLs. It works by providing properties which allow you to easily read and modify the components of a URL.
var URL: {
new (url: string | URL, base?: string | URL): URL;
prototype: URL;
canParse(url: string | URL, base?: string | URL): boolean;
createObjectURL(obj: Blob | MediaSource): string;
parse(url: string | URL, base?: string | URL): URL | null;
revokeObjectURL(url: string): void;
}
The URL interface is used to parse, construct, normalize, and encode URLs. It works by providing properties which allow you to easily read and modify the components of a URL.
URL;The URL of the current page
NavigationTarget
Information about the target of a specific navigation.
export interface NavigationTarget<
Params extends AppLayoutParams<'/'> = AppLayoutParams<'/'>,
RouteId extends AppRouteId | null = AppRouteId | null
> {/*…*/}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).
route: {
/**
* 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.
*/
id: RouteId | null;
};Info about the target route
url: var URL: {
new (url: string | URL, base?: string | URL): URL;
prototype: URL;
canParse(url: string | URL, base?: string | URL): boolean;
createObjectURL(obj: Blob | MediaSource): string;
parse(url: string | URL, base?: string | URL): URL | null;
revokeObjectURL(url: string): void;
}
The URL interface is used to parse, construct, normalize, and encode URLs. It works by providing properties which allow you to easily read and modify the components of a URL.
var URL: {
new (url: string | URL, base?: string | URL): URL;
prototype: URL;
canParse(url: string | URL, base?: string | URL): boolean;
createObjectURL(obj: Blob | MediaSource): string;
parse(url: string | URL, base?: string | URL): URL | null;
revokeObjectURL(url: string): void;
}
The URL interface is used to parse, construct, normalize, and encode URLs. It works by providing properties which allow you to easily read and modify the components of a URL.
URL;The URL that is navigated to
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
beforeNavigateandonNavigate, this is only available forpopstatenavigations (back/forward button) and will benullfor 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/startedform: The user submitted a<form method="GET">goto: Navigation was triggered by agoto(...)call or a redirectleave: The app is being left either because the tab is being closed or a navigation to a different document is occurringlink: Navigation was triggered by a link clickpopstate: Navigation was triggered by back/forward navigation
export type type NavigationType = "enter" | "form" | "leave" | "link" | "goto" | "popstate"type NavigationType = "enter" | "form" | "leave" | "link" | "goto" | "popstate"NavigationType = 'enter' | 'form' | 'leave' | 'link' | 'goto' | 'popstate';NavigationBase
export interface NavigationBase {/*…*/}type: NavigationType;The type of navigation:
enter: The app has hydrated/startedform: The user submitted a<form method="GET">goto: Navigation was triggered by agoto(...)call or a redirectleave: The app is being left either because the tab is being closed or a navigation to a different document is occurringlink: Navigation was triggered by a link clickpopstate: Navigation was triggered by back/forward navigation
from: NavigationTarget | null;Where navigation was triggered from
to: NavigationTarget | null;Where navigation is going to/has gone to
willUnload: boolean;Whether or not the navigation will result in the page being unloaded (i.e. not a client-side navigation).
complete: var Promise: PromiseConstructorRepresents the completion of an asynchronous operation
var Promise: PromiseConstructorRepresents the completion of an asynchronous operation
Promise<void>;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
export interface NavigationEnter extends NavigationBase {/*…*/}type: 'enter';delta?: undefined;In case of a history back/forward navigation, the number of steps to go back/forward
event?: undefined;Dispatched Event object when navigation occurred by popstate or link.
NavigationExternal
export type NavigationExternal = NavigationGoto | NavigationLeave;NavigationGoto
A navigation triggered by a goto(...) call or a redirect
export interface NavigationGoto extends NavigationBase {/*…*/}type: 'goto';delta?: undefined;In case of a history back/forward navigation, the number of steps to go back/forward
NavigationLeave
A navigation triggered by the tab being closed, or the user navigating to a different document
export interface NavigationLeave extends NavigationBase {/*…*/}type: 'leave';delta?: undefined;In case of a history back/forward navigation, the number of steps to go back/forward
NavigationFormSubmit
A navigation triggered by a <form method="GET">
export interface NavigationFormSubmit extends NavigationBase {/*…*/}type: 'form';event: var SubmitEvent: {
new (type: string, eventInitDict?: SubmitEventInit): SubmitEvent;
prototype: SubmitEvent;
}
The SubmitEvent interface defines the object used to represent an HTML form's submit event. This event is fired at the when the form's submit action is invoked.
var SubmitEvent: {
new (type: string, eventInitDict?: SubmitEventInit): SubmitEvent;
prototype: SubmitEvent;
}
The SubmitEvent interface defines the object used to represent an HTML form's submit event. This event is fired at the when the form's submit action is invoked.
SubmitEvent;The SubmitEvent that caused the navigation
delta?: undefined;In case of a history back/forward navigation, the number of steps to go back/forward
NavigationPopState
A navigation triggered by back/forward navigation
export interface NavigationPopState extends NavigationBase {/*…*/}type: 'popstate';delta: number;In case of a history back/forward navigation, the number of steps to go back/forward
event: var PopStateEvent: {
new (type: string, eventInitDict?: PopStateEventInit): PopStateEvent;
prototype: PopStateEvent;
}
PopStateEvent is an interface for the popstate event.
var PopStateEvent: {
new (type: string, eventInitDict?: PopStateEventInit): PopStateEvent;
prototype: PopStateEvent;
}
PopStateEvent is an interface for the popstate event.
PopStateEvent;The PopStateEvent that caused the navigation
NavigationLink
A navigation triggered by a link click
export interface NavigationLink extends NavigationBase {/*…*/}type: 'link';event: var PointerEvent: {
new (type: string, eventInitDict?: PointerEventInit): PointerEvent;
prototype: PointerEvent;
}
The PointerEvent interface represents the state of a DOM event produced by a pointer such as the geometry of the contact point, the device type that generated the event, the amount of pressure that was applied on the contact surface, etc.
var PointerEvent: {
new (type: string, eventInitDict?: PointerEventInit): PointerEvent;
prototype: PointerEvent;
}
The PointerEvent interface represents the state of a DOM event produced by a pointer such as the geometry of the contact point, the device type that generated the event, the amount of pressure that was applied on the contact surface, etc.
PointerEvent;The PointerEvent that caused the navigation
delta?: undefined;In case of a history back/forward navigation, the number of steps to go back/forward
Navigation
export type Navigation =
| NavigationExternal
| NavigationFormSubmit
| NavigationPopState
| NavigationLink;BeforeNavigate
The argument passed to beforeNavigate callbacks.
export type type BeforeNavigate = Navigation & {
cancel: () => void;
}
type BeforeNavigate = Navigation & {
cancel: () => void;
}
BeforeNavigate = Navigation & {
/**
* Call this to prevent the navigation from starting.
*/
cancel: () => voidCall this to prevent the navigation from starting.
cancel: () => voidCall this to prevent the navigation from starting.
cancel: () => void;
};OnNavigate
The argument passed to onNavigate callbacks.
export type type OnNavigate = Navigation & {
type: Exclude<NavigationType, "enter" | "leave">;
willUnload: false;
}
type OnNavigate = Navigation & {
type: Exclude<NavigationType, "enter" | "leave">;
willUnload: false;
}
OnNavigate = Navigation & {
type: NavigationTypetype: NavigationTypetype: type Exclude<T, U> = T extends U ? never : TExclude from T those types that are assignable to U
type Exclude<T, U> = T extends U ? never : TExclude from T those types that are assignable to U
Exclude<type NavigationType = "push" | "reload" | "replace" | "traverse"type NavigationType = "push" | "reload" | "replace" | "traverse"NavigationType, 'enter' | 'leave'>;
/**
* Since `onNavigate` callbacks are called immediately before a client-side navigation, they will never be called with a navigation that unloads the page.
*/
willUnload: falseSince onNavigate callbacks are called immediately before a client-side navigation, they will never be called with a navigation that unloads the page.
willUnload: falseSince onNavigate callbacks are called immediately before a client-side navigation, they will never be called with a navigation that unloads the page.
willUnload: false;
};AfterNavigate
The argument passed to afterNavigate callbacks.
export type AfterNavigate = (Navigation | NavigationEnter) & {
type: Exclude<NavigationType, 'leave'>;
/**
* Since `afterNavigate` callbacks are called after a navigation completes, they will never be called with a navigation that unloads the page.
*/
willUnload: false;
};Page
The shape of the page reactive object and the $page store.
export interface Page<
Params extends AppLayoutParams<'/'> = AppLayoutParams<'/'>,
RouteId extends AppRouteId | null = AppRouteId | null
> {/*…*/}url: URL & { pathname: ResolvedPathname };The URL of the current page.
params: Params;The parameters of the current page - e.g. for a route like /blog/[slug], a { slug: string } object.
route: {
/**
* 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.
*/
id: RouteId;
};Info about the current route.
status: number;HTTP status code of the current page.
error: App.Error | null;The error object of the current page, if any. Filled from the handleError hooks.
data: App.PageData & Record<string, any>;The merged result of all data from all load functions on the current page. You can type a common denominator through App.PageData.
state: App.PageState;The page state, which can be manipulated using the pushState and replaceState functions from $app/navigation.
form: any;Filled only after a form submission. See form actions for more info.
ParamMatcher
The shape of a param matcher. See matching for more info.
export type type ParamMatcher = (param: string) => booleantype ParamMatcher = (param: string) => booleanParamMatcher = (param: stringparam: stringparam: string) => boolean;RequestedEntry
A single entry yielded by 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.
export type RequestedEntry<Validated, Output> = {
arg: Validated;
query: RemoteQuery<Output>;
};LiveRequestedEntry
A single entry yielded by 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.
export type LiveRequestedEntry<Validated, Output> = {
arg: Validated;
query: RemoteLiveQuery<Output>;
};QueryRequestedResult
export type QueryRequestedResult<Validated, Output> = Iterable<RequestedEntry<Validated, Output>> &
AsyncIterable<RequestedEntry<Validated, Output>> & {
/**
* 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<void>;
};LiveQueryRequestedResult
export type LiveQueryRequestedResult<Validated, Output> = Iterable<
LiveRequestedEntry<Validated, Output>
> &
AsyncIterable<LiveRequestedEntry<Validated, Output>> & {
/**
* 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<void>;
};RequestedResult
export type RequestedResult<Validated, Output> =
| QueryRequestedResult<Validated, Output>
| LiveQueryRequestedResult<Validated, Output>;RequestEvent
export interface RequestEvent<
Params extends AppLayoutParams<'/'> = AppLayoutParams<'/'>,
RouteId extends AppRouteId | null = AppRouteId | null
> {/*…*/}cookies: Cookies;Get or set cookies related to the current request
fetch: typeof function fetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> (+1 overload)function fetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> (+1 overload)fetch;fetch is equivalent to the native fetch web API, with a few additional features:
- It can be used to make credentialed requests on the server, as it inherits the
cookieandauthorizationheaders for the page request. - It can make relative requests on the server (ordinarily,
fetchrequires a URL with an origin when used in a server context). - Internal requests (e.g. for
+server.jsroutes) go directly to the handler function when running on the server, without the overhead of an HTTP call. - During server-side rendering, the response will be captured and inlined into the rendered HTML by hooking into the
textandjsonmethods of theResponseobject. Note that headers will not be serialized, unless explicitly included viafilterSerializedResponseHeaders - During hydration, the response will be read from the HTML, guaranteeing consistency and preventing an additional network request.
You can learn more about making credentialed requests with cookies here.
getClientAddress: () => string;The client's IP address, set by the adapter.
locals: App.Locals;Contains custom data that was added to the request within the server handle hook.
params: Params;The parameters of the current route - e.g. for a route like /blog/[slug], a { slug: string } object.
In the context of a remote function request initiated by the client, this relates to the page the remote function was called from, not the URL of the endpoint SvelteKit creates for the remote function. Never use this 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.
platform: Readonly<App.Platform> | undefined;Additional data made available through the adapter.
request: var Request: {
new (input: RequestInfo | URL, init?: RequestInit): Request;
prototype: Request;
}
The Request interface of the Fetch API represents a resource request.
var Request: {
new (input: RequestInfo | URL, init?: RequestInit): Request;
prototype: Request;
}
The Request interface of the Fetch API represents a resource request.
Request;The original request object.
route: {
/**
* 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.
*
* In the context of a remote function request initiated by the client, this relates to the page the remote function
* was called from, _not_ the URL of the endpoint SvelteKit creates for the remote function. Never use this 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.
*/
id: RouteId;
};Info about the current route.
setHeaders: (headers: Record<string, string>) => void;If you need to set headers for the response, you can do so using the this method. This is useful if you want the page to be cached, for example:
export async function 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 API instead.
url: var URL: {
new (url: string | URL, base?: string | URL): URL;
prototype: URL;
canParse(url: string | URL, base?: string | URL): boolean;
createObjectURL(obj: Blob | MediaSource): string;
parse(url: string | URL, base?: string | URL): URL | null;
revokeObjectURL(url: string): void;
}
The URL interface is used to parse, construct, normalize, and encode URLs. It works by providing properties which allow you to easily read and modify the components of a URL.
var URL: {
new (url: string | URL, base?: string | URL): URL;
prototype: URL;
canParse(url: string | URL, base?: string | URL): boolean;
createObjectURL(obj: Blob | MediaSource): string;
parse(url: string | URL, base?: string | URL): URL | null;
revokeObjectURL(url: string): void;
}
The URL interface is used to parse, construct, normalize, and encode URLs. It works by providing properties which allow you to easily read and modify the components of a URL.
URL;The requested URL.
In the context of a remote function request initiated by the client, this relates to the page the remote function was called from, not the URL of the endpoint SvelteKit creates for the remote function. Never use this 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.
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.
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.
tracing: {
/** Whether tracing is enabled. */
enabled: boolean;
/** The root span for the request. This span is named `sveltekit.handle.root`. */
root: Span;
/** The span associated with the current `handle` hook, `load` function, or form action. */
current: Span;
};Access to spans for tracing. If tracing is not enabled, these spans will do nothing.
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 instead.
export type RequestHandler<
Params extends AppLayoutParams<'/'> = AppLayoutParams<'/'>,
RouteId extends AppRouteId | null = AppRouteId | null
> = (event: RequestEvent<Params, RouteId>) => MaybePromise<Response>;ResolveOptions
export interface ResolveOptions {/*…*/}transformPageChunk?: (input: { html: string; done: boolean }) => MaybePromise<string | undefined>;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.
filterSerializedResponseHeaders?: (name: string, value: string) => boolean;Determines which headers should be included in serialized responses when a load function loads a resource with fetch.
By default, none will be included.
preload?: (input: { type: 'font' | 'css' | 'js' | 'asset'; path: string }) => boolean;Determines what should be added to the <head> tag to preload it.
By default, js and css files will be preloaded.
RouteDefinition
export interface interface RouteDefinition<Config = any>interface RouteDefinition<Config = any>RouteDefinition<function (type parameter) Config in RouteDefinition<Config = any>function (type parameter) Config in RouteDefinition<Config = any>Config = any> {/*…*/}id: string;api: {
methods: Array<HttpMethod | '*'>;
};page: {
methods: Array<Extract<HttpMethod, 'GET' | 'POST'>>;
};pattern: var RegExp: RegExpConstructorvar RegExp: RegExpConstructorRegExp;prerender: PrerenderOption;segments: RouteSegment[];methods: Array<HttpMethod | '*'>;config: Config;Server
export class class Serverclass ServerServer {/*…*/}constructor(manifest: SSRManifest);init(options: ServerInitOptions): Promise<void>;respond(request: Request, options: RequestOptions): Promise<Response>;ServerInitOptions
export interface ServerInitOptions {/*…*/}env: Record<string, string>;A map of environment variables.
read?: (file: string) => MaybePromise<ReadableStream | null>;A function that turns an asset filename into a ReadableStream. Required for the read export from $app/server to work.
SSRManifest
export interface SSRManifest {/*…*/}appDir: string;appPath: string;assets: var Set: SetConstructorvar Set: SetConstructorSet<string>;Static files from kit.config.files.assets and the service worker (if any).
mimeTypes: Record<string, string>;_: {
client: BuildData['client'];
nodes: SSRNodeLoader[];
/** hashed filename -> import to that file */
remotes: Record<string, () => Promise<any>>;
routes: SSRRoute[];
prerendered_routes: Set<string>;
matchers: () => Promise<Record<string, ParamMatcher>>;
/** A `[file]: size` map of all assets imported by server code. */
server_assets: Record<string, number>;
};private fields
ServerLoad
The generic form of PageServerLoad and LayoutServerLoad. You should import those from ./$types (see generated types)
rather than using ServerLoad directly.
export type ServerLoad<
Params extends AppLayoutParams<'/'> = AppLayoutParams<'/'>,
ParentData extends Record<string, any> = Record<string, any>,
OutputData extends Record<string, any> | void = Record<string, any> | void,
RouteId extends AppRouteId | null = AppRouteId | null
> = (event: ServerLoadEvent<Params, ParentData, RouteId>) => MaybePromise<OutputData>;ServerLoadEvent
export interface ServerLoadEvent<
Params extends AppLayoutParams<'/'> = AppLayoutParams<'/'>,
ParentData extends Record<string, any> = Record<string, any>,
RouteId extends AppRouteId | null = AppRouteId | null
> extends RequestEvent<Params, RouteId> {/*…*/}parent: () => Promise<ParentData>;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.
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() 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.
Custom identifiers have to be prefixed with one or more lowercase letters followed by a colon to conform to the URI specification.
The following example shows how to use depends to register a dependency on a custom identifier, which is invalidated after a button click, making the load function rerun.
let count = 0;
export async function load({ depends }) {
depends('increase:count');
return { count: count++ };
}<script>
import { invalidate } from '$app/navigation';
let { data } = $props();
const increase = async () => {
await invalidate('increase:count');
}
</script>
<p>{data.count}<p>
<button on:click={increase}>Increase Count</button>untrack: <T>(fn: () => T) => T;Use this function to opt out of dependency tracking for everything that is synchronously called within the callback. Example:
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!' };
}
}tracing: {
/** Whether tracing is enabled. */
enabled: boolean;
/** The root span for the request. This span is named `sveltekit.handle.root`. */
root: Span;
/** The span associated with the current server `load` function. */
current: Span;
};Access to spans for tracing. If tracing is not enabled, these spans will do nothing.
Action
Shape of a form action method that is part of export const actions = {...} in +page.server.js.
See form actions for more information.
export type Action<
Params extends AppLayoutParams<'/'> = AppLayoutParams<'/'>,
OutputData extends Record<string, any> | void = Record<string, any> | void,
RouteId extends AppRouteId | null = AppRouteId | null
> = (event: RequestEvent<Params, RouteId>) => MaybePromise<OutputData>;Actions
Shape of the export const actions = {...} object in +page.server.js.
See form actions for more information.
export type Actions<
Params extends AppLayoutParams<'/'> = AppLayoutParams<'/'>,
OutputData extends Record<string, any> | void = Record<string, any> | void,
RouteId extends AppRouteId | null = AppRouteId | null
> = Record<string, Action<Params, OutputData, RouteId>>;ActionResult
When calling a form action via fetch, the response will be one of these shapes.
<form method="post" use:enhance={() => {
return ({ result }) => {
// result is of type ActionResult
};
}}export type type ActionResult<Success extends Record<string, unknown> | undefined = Record<string, any>, Failure extends Record<string, unknown> | undefined = Record<string, any>> = {
type: "success";
status: number;
data?: Success;
} | {
type: "failure";
status: number;
data?: Failure;
} | {
type: "redirect";
status: number;
location: string;
} | {
type: "error";
status?: number;
error: any;
}
type ActionResult<Success extends Record<string, unknown> | undefined = Record<string, any>, Failure extends Record<string, unknown> | undefined = Record<string, any>> = {
type: "success";
status: number;
data?: Success;
} | {
type: "failure";
status: number;
data?: Failure;
} | {
type: "redirect";
status: number;
location: string;
} | {
type: "error";
status?: number;
error: any;
}
ActionResult<
function (type parameter) Success in type ActionResult<Success extends Record<string, unknown> | undefined = Record<string, any>, Failure extends Record<string, unknown> | undefined = Record<string, any>>function (type parameter) Success in type ActionResult<Success extends Record<string, unknown> | undefined = Record<string, any>, Failure extends Record<string, unknown> | undefined = Record<string, any>>Success extends type Record<K extends keyof any, T> = { [P in K]: T; }Construct a type with a set of properties K of type T
type Record<K extends keyof any, T> = { [P in K]: T; }Construct a type with a set of properties K of type T
Record<string, unknown> | undefined = type Record<K extends keyof any, T> = { [P in K]: T; }Construct a type with a set of properties K of type T
type Record<K extends keyof any, T> = { [P in K]: T; }Construct a type with a set of properties K of type T
Record<string, any>,
function (type parameter) Failure in type ActionResult<Success extends Record<string, unknown> | undefined = Record<string, any>, Failure extends Record<string, unknown> | undefined = Record<string, any>>function (type parameter) Failure in type ActionResult<Success extends Record<string, unknown> | undefined = Record<string, any>, Failure extends Record<string, unknown> | undefined = Record<string, any>>Failure extends type Record<K extends keyof any, T> = { [P in K]: T; }Construct a type with a set of properties K of type T
type Record<K extends keyof any, T> = { [P in K]: T; }Construct a type with a set of properties K of type T
Record<string, unknown> | undefined = type Record<K extends keyof any, T> = { [P in K]: T; }Construct a type with a set of properties K of type T
type Record<K extends keyof any, T> = { [P in K]: T; }Construct a type with a set of properties K of type T
Record<string, any>
> =
| { type: "success"type: "success"type: 'success'; status: numberstatus: numberstatus: number; data?: Success | undefineddata?: Success | undefineddata?: function (type parameter) Success in type ActionResult<Success extends Record<string, unknown> | undefined = Record<string, any>, Failure extends Record<string, unknown> | undefined = Record<string, any>>function (type parameter) Success in type ActionResult<Success extends Record<string, unknown> | undefined = Record<string, any>, Failure extends Record<string, unknown> | undefined = Record<string, any>>Success }
| { type: "failure"type: "failure"type: 'failure'; status: numberstatus: numberstatus: number; data?: Failure | undefineddata?: Failure | undefineddata?: function (type parameter) Failure in type ActionResult<Success extends Record<string, unknown> | undefined = Record<string, any>, Failure extends Record<string, unknown> | undefined = Record<string, any>>function (type parameter) Failure in type ActionResult<Success extends Record<string, unknown> | undefined = Record<string, any>, Failure extends Record<string, unknown> | undefined = Record<string, any>>Failure }
| { type: "redirect"type: "redirect"type: 'redirect'; status: numberstatus: numberstatus: number; location: stringlocation: stringlocation: string }
| { type: "error"type: "error"type: 'error'; status?: number | undefinedstatus?: number | undefinedstatus?: number; error: anyerror: anyerror: any };HttpError
The object returned by the error function.
export interface HttpError {/*…*/}status: number;The HTTP status code, in the range 400-599.
body: App.Error;The content of the error.
Redirect
The object returned by the redirect function.
export interface Redirect {/*…*/}status: 300 | 301 | 302 | 303 | 304 | 305 | 306 | 307 | 308;The HTTP status code, in the range 300-308.
location: string;The location to redirect to.
SubmitFunction
export type SubmitFunction<
Success extends Record<string, unknown> | undefined = Record<string, any>,
Failure extends Record<string, unknown> | undefined = Record<string, any>
> = (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<Success, Failure>;
/**
* Call this to get the default behavior of a form submission response.
* @param options Set `reset: false` if you don't want the `<form>` values to be reset after a successful submission.
* @param invalidateAll Set `invalidateAll: false` if you don't want the action to call `invalidateAll` after submission.
*/
update: (options?: { reset?: boolean; invalidateAll?: boolean }) => Promise<void>;
}) => MaybePromise<void>)
>;Snapshot
The type of export const snapshot exported from a page or layout component.
export interface interface Snapshot<T = any>interface Snapshot<T = any>Snapshot<function (type parameter) T in Snapshot<T = any>function (type parameter) T in Snapshot<T = any>T = any> {/*…*/}capture: () => T;restore: (snapshot: T) => void;RemoteFormFieldType
export type RemoteFormFieldType<T> = {
[K in keyof InputTypeMap]: T extends InputTypeMap[K] ? K : never;
}[keyof InputTypeMap];RemoteFormFieldValue
export type type RemoteFormFieldValue = string | number | boolean | string[] | File | File[]type RemoteFormFieldValue = string | number | boolean | string[] | File | File[]RemoteFormFieldValue = string | string[] | number | boolean | File | File[];RemoteFormField
Form field accessor type that provides name(), value(), and issues() methods
export type RemoteFormField<Value extends RemoteFormFieldValue> = RemoteFormFieldMethods<Value> & {
/**
* 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
* <input {...myForm.fields.myString.as('text')} />
* <input {...myForm.fields.myNumber.as('number')} />
* <input {...myForm.fields.myBoolean.as('checkbox')} />
* ```
*/
as<T extends RemoteFormFieldType<Value>>(...args: AsArgs<T, Value>): InputElementProps<T>;
};RemoteFormFields
Recursive type to build form fields structure with proxy access
export type RemoteFormFields<T> =
WillRecurseIndefinitely<T> extends true
? RecursiveFormFields
: NonNullable<T> extends string | number | boolean | File
? RemoteFormField<NonNullable<T>>
: // [NonNullable<T>] 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<T>] extends [string[] | File[]]
? RemoteFormField<NonNullable<T>> & {
[K in number]: RemoteFormField<NonNullable<T>[number]>;
}
: [NonNullable<T>] extends [Array<infer U>]
? RemoteFormFieldContainer<NonNullable<T>> & {
[K in number]: RemoteFormFields<U>;
}
: RemoteFormFieldContainer<T> & {
[K in KeysOfUnion<T>]-?: RemoteFormFields<ValueOfUnionKey<T, K>>;
};RemoteFormInput
export interface RemoteFormInput {/*…*/}[key: string]: MaybeArray<string | number | boolean | File | RemoteFormInput> | undefined;RemoteFormIssue
export interface RemoteFormIssue {/*…*/}message: string;path: var Array: ArrayConstructorvar Array: ArrayConstructorArray<string | number>;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.
export type InvalidField<T> =
WillRecurseIndefinitely<T> extends true
? Record<string | number, any>
: NonNullable<T> extends string | number | boolean | File
? (message: string) => StandardSchemaV1.Issue
: NonNullable<T> extends Array<infer U>
? {
[K in number]: InvalidField<U>;
} & ((message: string) => StandardSchemaV1.Issue)
: NonNullable<T> extends RemoteFormInput
? {
[K in keyof T]-?: InvalidField<T[K]>;
} & ((message: string) => StandardSchemaV1.Issue)
: Record<string, never>;ValidationError
A validation error thrown by invalid.
export interface ValidationError {/*…*/}issues: StandardSchemaV1.Issue[];The validation issues
RemoteFormEnhanceInstance
The form instance as received inside an enhance callback. See Remote functions for full documentation.
export type RemoteFormEnhanceInstance<
Input extends RemoteFormInput | void = RemoteFormInput | void,
Output = any
> = Omit<RemoteForm<Input, Output>, 'enhance' | 'element'> & {
readonly element: HTMLFormElement;
};RemoteFormEnhanceCallback
The callback passed to a remote form's enhance method. See Remote functions for full documentation.
export type RemoteFormEnhanceCallback<
Input extends RemoteFormInput | void = RemoteFormInput | void,
Output = any
> = (form: RemoteFormEnhanceInstance<Input, Output>) => MaybePromise<void>;RemoteForm
The type of a remote form function. See Remote functions for full documentation.
export 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 `<form>` element this instance is currently attached to, if any. */
get element(): HTMLFormElement | null;
/** Submit the currently attached form programmatically. */
submit(): Promise<boolean> & {
updates: (...updates: RemoteQueryUpdate[]) => Promise<boolean>;
};
/** Use the `enhance` method to influence what happens when the form is submitted. */
enhance(callback: RemoteFormEnhanceCallback<Input, Output>): {
method: 'POST';
action: string;
[attachment: symbol]: (node: HTMLFormElement) => void;
};
/**
* Create an instance of the form for the given `id`.
* The `id` is stringified and used for deduplication to potentially reuse existing instances.
* Useful when you have multiple forms that use the same remote form action, for example in a loop.
* ```svelte
* {#each todos as todo}
* {@const todoForm = updateTodo.for(todo.id)}
* <form {...todoForm}>
* {#if todoForm.result?.invalid}<p>Invalid data</p>{/if}
* ...
* </form>
* {/each}
* ```
*/
for(id: ExtractId<Input>): Omit<RemoteForm<Input, Output>, 'for'>;
/** Preflight checks */
preflight(schema: StandardSchemaV1<Input, any>): RemoteForm<Input, Output>;
/** Validate the form contents programmatically */
validate(options?: {
/** Set this to `true` to also show validation issues of fields that haven't been touched yet. */
includeUntouched?: boolean;
/** Set this to `true` to only run the `preflight` validation. */
preflightOnly?: boolean;
}): Promise<void>;
/** The result of the form submission */
get result(): Output | undefined;
/** The number of pending submissions */
get pending(): number;
/** True if the form has been submitted at least once */
get submitted(): boolean;
/** Access form fields using object notation */
fields: RemoteFormFieldsRoot<Input>;
};RemoteCommand
The type of a remote command function. See Remote functions for full documentation.
export type RemoteCommand<Input, Output> = {
(arg: undefined extends Input ? Input | void : Input): Promise<Output> & {
updates(...updates: RemoteQueryUpdate[]): Promise<Output>;
};
/** The number of pending command executions */
get pending(): number;
};RemoteQueryUpdate
export type RemoteQueryUpdate =
| RemoteQuery<any>
| RemoteLiveQuery<any>
| RemoteQueryFunction<any, any>
| RemoteLiveQueryFunction<any, any>
| RemoteQueryOverride;RemoteResource
export type type RemoteResource<T> = Promise<T> & ({
readonly error: any;
readonly loading: boolean;
} & ({
readonly current: undefined;
ready: false;
} | {
readonly current: T;
ready: true;
}))
type RemoteResource<T> = Promise<T> & ({
readonly error: any;
readonly loading: boolean;
} & ({
readonly current: undefined;
ready: false;
} | {
readonly current: T;
ready: true;
}))
RemoteResource<function (type parameter) T in type RemoteResource<T>function (type parameter) T in type RemoteResource<T>T> = interface Promise<T>Represents the completion of an asynchronous operation
interface Promise<T>Represents the completion of an asynchronous operation
Promise<function (type parameter) T in type RemoteResource<T>function (type parameter) T in type RemoteResource<T>T> & {
/** The error in case the query fails. Most often this is a [`HttpError`](https://svelte.dev/docs/kit/@sveltejs-kit#HttpError) but it isn't guaranteed to be. */
get error: anyThe error in case the query fails. Most often this is a HttpError but it isn't guaranteed to be.
error: anyThe error in case the query fails. Most often this is a HttpError but it isn't guaranteed to be.
error(): any;
/** `true` before the first result is available and during refreshes */
get loading: booleantrue before the first result is available and during refreshes
loading: booleantrue before the first result is available and during refreshes
loading(): boolean;
} & (
| {
/** The current value of the query. Undefined until `ready` is `true` */
get current: undefinedThe current value of the query. Undefined until ready is true
current: undefinedThe current value of the query. Undefined until ready is true
current(): undefined;
ready: falseready: falseready: false;
}
| {
/** The current value of the query. Undefined until `ready` is `true` */
get current: TThe current value of the query. Undefined until ready is true
current: TThe current value of the query. Undefined until ready is true
current(): function (type parameter) T in type RemoteResource<T>function (type parameter) T in type RemoteResource<T>T;
ready: trueready: trueready: true;
}
);RemoteQuery
export type RemoteQuery<T> = RemoteResource<T> & {
/**
* 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<void>;
/**
* 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
* <script>
* import { getTodos, addTodo } from './todos.remote.js';
* const todos = getTodos();
* </script>
*
* <form {...addTodo.enhance(async (form) => {
* await form.submit().updates(
* todos.withOverride((todos) => [...todos, { text: form.fields.text.value() }])
* );
* })}>
* <input type="text" name="text" />
* <button type="submit">Add Todo</button>
* </form>
* ```
*/
withOverride(update: (current: T) => T): RemoteQueryOverride;
};RemoteLiveQuery
export type RemoteLiveQuery<T> = RemoteResource<T> &
AsyncIterable<T> & {
/** `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<void>;
};RemoteQueryOverride
export type type RemoteQueryOverride = () => voidtype RemoteQueryOverride = () => voidRemoteQueryOverride = () => void;RemotePrerenderFunction
The type of a remote prerender function. See Remote functions for full documentation.
export type RemotePrerenderFunction<Input, Output> = (
arg: undefined extends Input ? Input | void : Input
) => RemoteResource<Output>;RemoteQueryFunction
The return value of a remote query function. See Remote functions 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. For queries declared
with Standard Schema 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.
export type RemoteQueryFunction<Input, Output, _Validated = Input> = (
arg: undefined extends Input ? Input | void : Input
) => RemoteQuery<Output>;RemoteLiveQueryFunction
The type of a remote query.live function. See Remote functions 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.
export type RemoteLiveQueryFunction<Input, Output, _Validated = Input> = (
arg: undefined extends Input ? Input | void : Input
) => RemoteLiveQuery<Output>;EnvVarConfig
Environment variables can be configured by exporting
a variables object from src/env.ts, using defineEnvVars.
export interface interface EnvVarConfig<T>interface EnvVarConfig<T>EnvVarConfig<function (type parameter) T in EnvVarConfig<T>function (type parameter) T in EnvVarConfig<T>T> {/*…*/}public?: boolean;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
static?: boolean;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
schema?: StandardSchemaV1<string | undefined, T>;A Standard Schema validator that is applied to the value when the app starts. The validator can output any value — not necessarily a string — but public, non-static values must be serializable by devalue so that they can be sent to the browser.
If omitted, the value must be a non-empty string.
description?: string;A description of the variable that will be used for inline documentation on hover.
PrerenderOption
export type type PrerenderOption = boolean | "auto"type PrerenderOption = boolean | "auto"PrerenderOption = boolean | 'auto';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 without invoking handleError.
Make sure you're not catching the thrown error, which would prevent SvelteKit from handling it.
export function error(status: number, body: App.Error): never;
export function error(status: number, body?: {
message: string;
} extends App.Error ? App.Error | string | undefined : never): never;isHttpError
Checks whether this is an error thrown by {@link error}.
export function isHttpError<T extends number>(e: unknown, status?: T): e is (HttpError_1 & {
status: T extends undefined ? never : T;
});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 method308 Permanent Redirect: redirect will keep the request method, SEO will be transferred to the new page
export function redirect(status: 300 | 301 | 302 | 303 | 304 | 305 | 306 | 307 | 308 | ({} & number), location: string | URL): never;isRedirect
Checks whether this is a redirect thrown by {@link redirect}.
export function isRedirect(e: unknown): e is Redirect_1;json
Create a JSON Response object from the supplied data.
export function json(data: any, init?: ResponseInit): Response;text
Create a Response object from the supplied body.
export function text(body: string, init?: ResponseInit): Response;fail
Create an ActionFailure object. Call when form submission fails.
export function fail(status: number): ActionFailure<undefined>;
export function fail<T = undefined>(status: number, data: T): ActionFailure<T>;isActionFailure
Checks whether this is an action failure thrown by {@link fail}.
export function isActionFailure(e: unknown): e is 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.
export function invalid(...issues: (StandardSchemaV1.Issue | string)[]): never;isValidationError
Available since 2.47.3
Checks whether this is an validation error thrown by {@link invalid}.
export function isValidationError(e: unknown): e is ActionFailure;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.
import { function normalizeUrl(url: URL | string): {
url: URL;
wasNormalized: boolean;
denormalize: (url?: string | URL) => URL;
}
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.
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
function normalizeUrl(url: URL | string): {
url: URL;
wasNormalized: boolean;
denormalize: (url?: string | URL) => URL;
}
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.
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
normalizeUrl } from '@sveltejs/kit';
const { const url: URLconst url: URLurl, const denormalize: (url?: string | URL) => URLconst denormalize: (url?: string | URL) => URLdenormalize } = function normalizeUrl(url: URL | string): {
url: URL;
wasNormalized: boolean;
denormalize: (url?: string | URL) => URL;
}
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.
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
function normalizeUrl(url: URL | string): {
url: URL;
wasNormalized: boolean;
denormalize: (url?: string | URL) => URL;
}
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.
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
normalizeUrl('/blog/post/__data.json');
var console: Consolevar console: Consoleconsole.Console.log(...data: any[]): voidThe console.log() static method outputs a message to the console.
Console.log(...data: any[]): voidThe console.log() static method outputs a message to the console.
log(const url: URLconst url: URLurl.URL.pathname: stringThe pathname property of the URL interface represents a location in a hierarchical structure. It is a string constructed from a list of path segments, each of which is prefixed by a / character.
URL.pathname: stringThe pathname property of the URL interface represents a location in a hierarchical structure. It is a string constructed from a list of path segments, each of which is prefixed by a / character.
pathname); // /blog/post
var console: Consolevar console: Consoleconsole.Console.log(...data: any[]): voidThe console.log() static method outputs a message to the console.
Console.log(...data: any[]): voidThe console.log() static method outputs a message to the console.
log(const denormalize: (url?: string | URL) => URLconst denormalize: (url?: string | URL) => URLdenormalize('/blog/post/a')); // /blog/post/a/__data.jsonexport function normalizeUrl(url: URL | string): {
url: URL;
wasNormalized: boolean;
denormalize: (url?: string | URL) => URL;
};LessThan
export type type LessThan<TNumber extends number, TArray extends any[] = []> = TNumber extends TArray["length"] ? TArray[number] : LessThan<TNumber, [...TArray, TArray["length"]]>type LessThan<TNumber extends number, TArray extends any[] = []> = TNumber extends TArray["length"] ? TArray[number] : LessThan<TNumber, [...TArray, TArray["length"]]>LessThan<function (type parameter) TNumber in type LessThan<TNumber extends number, TArray extends any[] = []>function (type parameter) TNumber in type LessThan<TNumber extends number, TArray extends any[] = []>TNumber extends number, function (type parameter) TArray in type LessThan<TNumber extends number, TArray extends any[] = []>function (type parameter) TArray in type LessThan<TNumber extends number, TArray extends any[] = []>TArray extends any[] = []> = function (type parameter) TNumber in type LessThan<TNumber extends number, TArray extends any[] = []>function (type parameter) TNumber in type LessThan<TNumber extends number, TArray extends any[] = []>TNumber extends function (type parameter) TArray in type LessThan<TNumber extends number, TArray extends any[] = []>function (type parameter) TArray in type LessThan<TNumber extends number, TArray extends any[] = []>TArray["length"] ? function (type parameter) TArray in type LessThan<TNumber extends number, TArray extends any[] = []>function (type parameter) TArray in type LessThan<TNumber extends number, TArray extends any[] = []>TArray[number] : type LessThan<TNumber extends number, TArray extends any[] = []> = TNumber extends TArray["length"] ? TArray[number] : LessThan<TNumber, [...TArray, TArray["length"]]>type LessThan<TNumber extends number, TArray extends any[] = []> = TNumber extends TArray["length"] ? TArray[number] : LessThan<TNumber, [...TArray, TArray["length"]]>LessThan<function (type parameter) TNumber in type LessThan<TNumber extends number, TArray extends any[] = []>function (type parameter) TNumber in type LessThan<TNumber extends number, TArray extends any[] = []>TNumber, [...function (type parameter) TArray in type LessThan<TNumber extends number, TArray extends any[] = []>function (type parameter) TArray in type LessThan<TNumber extends number, TArray extends any[] = []>TArray, function (type parameter) TArray in type LessThan<TNumber extends number, TArray extends any[] = []>function (type parameter) TArray in type LessThan<TNumber extends number, TArray extends any[] = []>TArray["length"]]>;NumericRange
export type NumericRange<TStart extends number, TEnd extends number> = Exclude<TEnd | LessThan<TEnd>, LessThan<TStart>>;VERSION
export const VERSION: string;