Skip to main content

Types

Edit this page on GitHub

$app/formspermalink

ts
import { enhance, applyAction } from '$app/forms';

SubmitFunctionpermalink

ts
type SubmitFunction<
Success extends Record<string, unknown> | undefined = Record<string, any>,
Invalid extends Record<string, unknown> | undefined = Record<string, any>
> = (input: {
action: URL;
data: FormData;
form: HTMLFormElement;
controller: AbortController;
cancel(): void;
| void
| ((opts: {
form: HTMLFormElement;
action: URL;
result: ActionResult<Success, Invalid>;
/**
* 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.
*/
update(options?: { reset: boolean }): Promise<void>;
}) => void)
>;

@sveltejs/kitpermalink

The following can be imported from @sveltejs/kit:

Actionpermalink

ts
interface Action<
Params extends Partial<Record<string, string>> = Partial<
Record<string, string>
>,
OutputData extends Record<string, any> | void = Record<string, any> | void,
RouteId extends string | null = string | null
> {}
ts
(event: RequestEvent<Params, RouteId>): MaybePromise<OutputData>;

ActionResultpermalink

When calling a form action via fetch, the response will be one of these shapes.

ts
type ActionResult<
Success extends Record<string, unknown> | undefined = Record<string, any>,
Invalid extends Record<string, unknown> | undefined = Record<string, any>
> =
| { type: 'success'; status: number; data?: Success }
| { type: 'invalid'; status: number; data?: Invalid }
| { type: 'redirect'; status: number; location: string }
| { type: 'error'; error: any };

Actionspermalink

ts
type Actions<
Params extends Partial<Record<string, string>> = Partial<
Record<string, string>
>,
OutputData extends Record<string, any> | void = Record<string, any> | void,
RouteId extends string | null = string | null
> = Record<string, Action<Params, OutputData, RouteId>>;

Adapterpermalink

ts
interface Adapter {}
ts
name: string;
ts
adapt(builder: Builder): MaybePromise<void>;

AfterNavigatepermalink

The interface that corresponds to the afterNavigate's input parameter.

ts
interface AfterNavigate extends Navigation {}
ts
type: Omit<NavigationType, 'leave'>;

The type of navigation:

  • enter: The app has hydrated
  • link: Navigation was triggered by a link click
  • goto: Navigation was triggered by a goto(...) call or a redirect
  • popstate: Navigation was triggered by back/forward navigation
ts
willUnload: false;

AwaitedActionspermalink

ts
type AwaitedActions<T extends Record<string, (...args: any) => any>> = {
[Key in keyof T]: OptionalUnion<
UnpackValidationError<Awaited<ReturnType<T[Key]>>>
>;
}[keyof T];

AwaitedPropertiespermalink

ts
type AwaitedProperties<input extends Record<string, any> | void> =
AwaitedPropertiesUnion<input> extends Record<string, any>
? OptionalUnion<AwaitedPropertiesUnion<input>>
: AwaitedPropertiesUnion<input>;

BeforeNavigatepermalink

The interface that corresponds to the beforeNavigate's input parameter.

ts
interface BeforeNavigate extends Navigation {}
ts
cancel(): void;

Call this to prevent the navigation from starting.

Builderpermalink

ts
interface Builder {}
ts
log: Logger;
ts
rimraf(dir: string): void;
ts
mkdirp(dir: string): void;
ts
config: ValidatedConfig;
ts
prerendered: Prerendered;
ts
createEntries(fn: (route: RouteDefinition) => AdapterEntry): Promise<void>;
  • fn A function that groups a set of routes into an entry point

Create entry points that map to individual functions

ts
generateManifest(opts: { relativePath: string; format?: 'esm' | 'cjs' }): string;
ts
getBuildDirectory(name: string): string;
ts
getClientDirectory(): string;
ts
getServerDirectory(): string;
ts
getStaticDirectory(): string;
ts
getAppPath(): string;

The application path including any configured base path

ts
writeClient(dest: string): string[];
  • dest the destination folder to which files should be copied
  • Returns an array of paths corresponding to the files that have been created by the copy
ts
writePrerendered(
dest: string,
opts?: {
fallback?: string;
}
): string[];
  • dest the destination folder to which files should be copied
  • opts.fallback the name of a file for fallback responses, like 200.html or 404.html depending on where the app is deployed
  • Returns an array of paths corresponding to the files that have been created by the copy
ts
writeServer(dest: string): string[];
  • dest the destination folder to which files should be copied
  • Returns an array of paths corresponding to the files that have been created by the copy
ts
copy(
from: string,
to: string,
opts?: {
filter?(basename: string): boolean;
replace?: Record<string, string>;
}
): string[];
  • from the source file or folder
  • to the destination file or folder
  • opts.filter a function to determine whether a file or folder should be copied
  • opts.replace a map of strings to replace
  • Returns an array of paths corresponding to the files that have been created by the copy
ts
compress(directory: string): Promise<void>;
  • directory Path to the directory containing the files to be compressed

Configpermalink

ts
interface Config {}
ts
compilerOptions?: CompileOptions;
ts
extensions?: string[];
ts
kit?: KitConfig;
ts
package?: {
source?: string;
dir?: string;
emitTypes?: boolean;
exports?(filepath: string): boolean;
files?(filepath: string): boolean;
};
ts
preprocess?: any;
ts
[key: string]: any;

Cookiespermalink

ts
interface Cookies {}
ts
get(name: string, opts?: import('cookie').CookieParseOptions): string | undefined;

Gets a cookie that was previously set with cookies.set, or from the request headers.

ts
set(name: string, value: string, opts?: import('cookie').CookieSerializeOptions): void;

Sets a cookie. This will add a set-cookie header to the response, but also make the cookie available via cookies.get 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.

By default, the path of a cookie is the 'directory' of the current pathname. In most cases you should explicitly set path: '/' to make the cookie available throughout your app.

ts
delete(name: string, opts?: import('cookie').CookieSerializeOptions): void;

Deletes a cookie by setting its value to an empty string and setting the expiry date in the past.

By default, the path of a cookie is the 'directory' of the current pathname. In most cases you should explicitly set path: '/' to make the cookie available throughout your app.

ts
serialize(name: string, value: string, opts?: import('cookie').CookieSerializeOptions): string;
  • name the name for the cookie
  • value value to set the cookie to
  • options object containing serialization options

Serialize a cookie name-value pair into a Set-Cookie header string.

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.

By default, the path of a cookie is the current pathname. In most cases you should explicitly set path: '/' to make the cookie available throughout your app.

Handlepermalink

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).

ts
interface Handle {}
ts
(input: {
event: RequestEvent;
resolve(event: RequestEvent, opts?: ResolveOptions): MaybePromise<Response>;
}): MaybePromise<Response>;

HandleClientErrorpermalink

The client-side handleError hook runs when an unexpected error is thrown while navigating.

ts
interface HandleClientError {}
ts
(input: { error: unknown; event: NavigationEvent }): void | App.Error;

HandleFetchpermalink

The handleFetch hook allows you to modify (or replace) a fetch request that happens inside a load function that runs on the server (or during pre-rendering)

ts
interface HandleFetch {}
ts
(input: { event: RequestEvent; request: Request; fetch: typeof fetch }): MaybePromise<Response>;

HandleServerErrorpermalink

The server-side handleError hook runs when an unexpected error is thrown while responding to a request.

ts
interface HandleServerError {}
ts
(input: { error: unknown; event: RequestEvent }): void | App.Error;

HttpErrorpermalink

The object returned by the error function

ts
interface HttpError {}
ts
status: number;

The HTTP status code

ts
body: App.Error;

The error message

KitConfigpermalink

ts
interface KitConfig {}
ts
adapter?: Adapter;
  • Default undefined

Your adapter is run when executing vite build. It determines how the output is converted for different platforms.

ts
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.

svelte.config.js
ts
/** @type {import('@sveltejs/kit').Config} */
const config = {
kit: {
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/*'
}
}
};

The built-in $lib alias is controlled by config.kit.files.lib as it is used for packaging.

You will need to run npm run dev to have SvelteKit automatically generate the required alias configuration in jsconfig.json or tsconfig.json.

ts
appDir?: string;

The directory relative to paths.assets where the built JS and CSS (and imported assets) are served from. (The filenames therein contain content-based hashes, meaning they can be cached indefinitely). Must not start or end with /.

ts
csp?: {
mode?: 'hash' | 'nonce' | 'auto';
directives?: CspDirectives;
reportOnly?: CspDirectives;
};

An object containing zero or more of the following values:

  • mode — 'hash', 'nonce' or 'auto'
  • directives — an object of [directive]: value[] pairs
  • reportOnly — an object of [directive]: value[] pairs for CSP report-only mode

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...

svelte.config.js
ts
/** @type {import('@sveltejs/kit').Config} */
const config = {
kit: {
csp: {
directives: {
'script-src': ['self']
},
reportOnly: {
'script-src': ['self']
}
}
}
};
 
export default 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 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 mode is '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 the style-src directive unspecified or add unsafe-inline.

ts
csrf?: {
checkOrigin?: boolean;
};

Protection against cross-site request forgery attacks:

  • checkOrigin — if true, SvelteKit will check the incoming origin header for POST form submissions and verify that it matches the server's origin

To allow people to make POST form submissions to your app from other origins, you will need to disable this option. Be careful!

ts
env?: {
/**
* The directory to search for `.env` files.
*/
dir?: string;
/**
* A prefix that signals that an environment variable is safe to expose to client-side code. See [`$env/static/public`](/docs/modules#$env-static-public) and [`$env/dynamic/public`](/docs/modules#$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.
*/
publicPrefix?: string;
};

Environment variable configuration

ts
files?: {
/**
* a place to put static files that should have stable URLs and undergo no processing, such as `favicon.ico` or `manifest.json`
*/
assets?: string;
/**
* the location of your client and server [hooks](https://kit.svelte.dev/docs/hooks)
*/
hooks?: {
client?: string;
server?: string;
};
/**
* your app's internal library, accessible throughout the codebase as `$lib`
*/
lib?: string;
/**
* a directory containing [parameter matchers](https://kit.svelte.dev/docs/advanced-routing#matching)
*/
params?: string;
/**
* the files that define the structure of your app (see [Routing](https://kit.svelte.dev/docs/routing))
*/
routes?: string;
/**
* the location of your service worker's entry point (see [Service workers](https://kit.svelte.dev/docs/service-workers))
*/
serviceWorker?: string;
/**
* the location of the template for HTML responses
*/
appTemplate?: string;
/**
* the location of the template for fallback error responses
*/
errorTemplate?: string;
};

Where to find various files within your project.

ts
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 to be inlined. All CSS files needed for the page and 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.

ts
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.

ts
outDir?: string;

The directory that SvelteKit writes files to during dev and build. You should exclude this directory from version control.

ts
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
*/
assets?: 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`](/docs/modules#$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.
*/
base?: string;
};
ts
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.
*/
concurrency?: number;
/**
* Determines whether SvelteKit should find pages to prerender by following links from the seed page(s).
*/
crawl?: boolean;
/**
* Set to `false` to disable prerendering altogether
*/
enabled?: boolean;
/**
* An array of pages to prerender, or start crawling from (if `crawl: true`). The `*` string includes all non-dynamic routes (i.e. pages with no `[parameters]`, because SvelteKit doesn't know what value the parameters should have).
*/
entries?: Array<'*' | `/${string}`>;
/**
* - `'fail'` — (default) fails the build when a routing error is encountered when following a link
* - `'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
* /** @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);
* }
* }
* }
* }
* };
* ```
*/
handleHttpError?: PrerenderHttpErrorHandlerValue;
/**
* - `'fail'` — (default) fails the build when a prerendered page links to another prerendered page with a `#` fragment that doesn't correspond to an `id`
* - `'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
*/
handleMissingId?: PrerenderMissingIdHandlerValue;
/**
* The value of `url.origin` during prerendering; useful if it is included in rendered content.
*/
origin?: string;
};
ts
serviceWorker?: {
/**
* If set to `false`, will disable automatic service worker registration.
*/
register?: boolean;
/**
* A function with the type of `(filepath: string) => boolean`. When `true`, the given file will be available in `$service-worker.files`, otherwise it will be excluded.
*/
files?(filepath: string): boolean;
};
ts
version?: {
/**
* The current app version string
*/
name?: string;
/**
* The interval in milliseconds to poll for version changes.
*/
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 solves this problem by falling back to traditional full-page navigation if it detects that a new version has been deployed, using the name specified here (which defaults to a timestamp of the build).

If you set pollInterval to a non-zero value, SvelteKit will poll for new versions in the background and set the value of the updated store to true when it detects one.

Loadpermalink

The generic form of PageLoad and LayoutLoad. You should import those from ./$types (see generated types) rather than using Load directly.

ts
interface Load<
Params extends Partial<Record<string, string>> = Partial<
Record<string, string>
>,
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 string | null = string | null
> {}
ts
(event: LoadEvent<Params, InputData, ParentData, RouteId>): MaybePromise<OutputData>;

LoadEventpermalink

ts
interface LoadEvent<
Params extends Partial<Record<string, string>> = Partial<
Record<string, string>
>,
Data extends Record<string, unknown> | null = Record<string, any> | null,
ParentData extends Record<string, unknown> = Record<string, any>,
RouteId extends string | null = string | null
> extends NavigationEvent<Params, RouteId> {}
ts
fetch: typeof fetch;

fetch is equivalent to the native fetch web API, with a few additional features:

  • it can be used to make credentialed requests on the server, as it inherits the cookie and authorization headers for the page request
  • it can make relative requests on the server (ordinarily, fetch requires a URL with an origin when used in a server context)
  • internal requests (e.g. for +server.js routes) go directly to the handler function when running on the server, without the overhead of an HTTP call
  • during server-side rendering, the response will be captured and inlined into the rendered HTML. Note that headers will not be serialized, unless explicitly included via filterSerializedResponseHeaders
  • during hydration, the response will be read from the HTML, guaranteeing consistency and preventing an additional network request

Cookies will only be passed through if the target host is the same as the SvelteKit application or a more specific subdomain of it.

ts
data: Data;

Contains the data returned by the route's server load function (in +layout.server.js or +page.server.js), if any.

ts
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:

src/routes/blog/+page.js
ts
export async function load({ fetch, setHeaders }) {
Binding element 'fetch' implicitly has an 'any' type.
Binding element 'setHeaders' implicitly has an 'any' type.
7031
7031
Binding element 'fetch' implicitly has an 'any' type.
Binding element 'setHeaders' implicitly has an 'any' type.
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.

ts
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.

ts
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.

src/routes/+page.js
ts
let count = 0;
export async function load({ depends }) {
Binding element 'depends' implicitly has an 'any' type.7031Binding element 'depends' implicitly has an 'any' type.
depends('increase:count');
 
return { count: count++ };
}
src/routes/+page.svelte
// @errors: 7031
<script>
  import { invalidate } from '$app/navigation';

  export let data;

  const increase = async () => {
    await invalidate('increase:count');
  }
</script>

<p>{data.count}<p>
<button on:click={increase}>Increase Count</button>

Navigationpermalink

ts
interface Navigation {}
ts
from: NavigationTarget | null;

Where navigation was triggered from

ts
to: NavigationTarget | null;

Where navigation is going to/has gone to

ts
type: Omit<NavigationType, 'enter'>;

The type of navigation:

  • leave: The user is leaving the app by closing the tab or using the back/forward buttons to go to a different document
  • link: Navigation was triggered by a link click
  • goto: Navigation was triggered by a goto(...) call or a redirect
  • popstate: Navigation was triggered by back/forward navigation
ts
willUnload: boolean;

Whether or not the navigation will result in the page being unloaded (i.e. not a client-side navigation)

ts
delta?: number;

In case of a history back/forward navigation, the number of steps to go back/forward

NavigationEventpermalink

ts
interface NavigationEvent<
Params extends Partial<Record<string, string>> = Partial<
Record<string, string>
>,
RouteId extends string | null = string | null
> {}
ts
params: Params;

The parameters of the current page - e.g. for a route like /blog/[slug], a { slug: string } object

ts
route: {
/**
* The ID of the current route - e.g. for `src/routes/blog/[slug]`, it would be `/blog/[slug]`
*/
id: RouteId;
};

Info about the current route

ts
url: URL;

The URL of the current page

NavigationTargetpermalink

ts
interface NavigationTarget {}
ts
params: Record<string, string> | null;
ts
route: { id: string | null };
ts
url: URL;

NavigationTypepermalink

  • enter: The app has hydrated
  • leave: The user is leaving the app by closing the tab or using the back/forward buttons to go to a different document
  • link: Navigation was triggered by a link click
  • goto: Navigation was triggered by a goto(...) call or a redirect
  • popstate: Navigation was triggered by back/forward navigation
ts
type NavigationType = 'enter' | 'leave' | 'link' | 'goto' | 'popstate';

Pagepermalink

The shape of the $page store

ts
interface Page<
Params extends Record<string, string> = Record<string, string>,
RouteId extends string | null = string | null
> {}
ts
url: URL;

The URL of the current page

ts
params: Params;

The parameters of the current page - e.g. for a route like /blog/[slug], a { slug: string } object

ts
route: {
/**
* The ID of the current route - e.g. for `src/routes/blog/[slug]`, it would be `/blog/[slug]`
*/
id: RouteId;
};

Info about the current route

ts
status: number;

Http status code of the current page

ts
error: App.Error | null;

The error object of the current page, if any. Filled from the handleError hooks.

ts
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.

ts
form: any;

Filled only after a form submission. See form actions for more info.

ParamMatcherpermalink

ts
interface ParamMatcher {}
ts
(param: string): boolean;

Redirectpermalink

The object returned by the redirect function

ts
interface Redirect {}
ts
status: 300 | 301 | 302 | 303 | 304 | 305 | 306 | 307 | 308;

The HTTP status code

ts
location: string;

The location to redirect to

RequestEventpermalink

ts
interface RequestEvent<
Params extends Partial<Record<string, string>> = Partial<
Record<string, string>
>,
RouteId extends string | null = string | null
> {}
ts
cookies: Cookies;

Get or set cookies related to the current request

ts
fetch: typeof fetch;

fetch is equivalent to the native fetch web API, with a few additional features:

  • it can be used to make credentialed requests on the server, as it inherits the cookie and authorization headers for the page request
  • it can make relative requests on the server (ordinarily, fetch requires a URL with an origin when used in a server context)
  • internal requests (e.g. for +server.js routes) go directly to the handler function when running on the server, without the overhead of an HTTP call

Cookies will only be passed through if the target host is the same as the SvelteKit application or a more specific subdomain of it.

ts
getClientAddress(): string;

The client's IP address, set by the adapter.

ts
locals: App.Locals;

Contains custom data that was added to the request within the handle hook.

ts
params: Params;

The parameters of the current page or endpoint - e.g. for a route like /blog/[slug], a { slug: string } object

ts
platform: Readonly<App.Platform>;

Additional data made available through the adapter.

ts
request: Request;

The original request object

ts
route: {
/**
* The ID of the current route - e.g. for `src/routes/blog/[slug]`, it would be `/blog/[slug]`
*/
id: RouteId;
};

Info about the current route

ts
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:

src/routes/blog/+page.js
ts
export async function load({ fetch, setHeaders }) {
Binding element 'fetch' implicitly has an 'any' type.
Binding element 'setHeaders' implicitly has an 'any' type.
7031
7031
Binding element 'fetch' implicitly has an 'any' type.
Binding element 'setHeaders' implicitly has an 'any' type.
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.

ts
url: URL;

The URL of the current page or endpoint

RequestHandlerpermalink

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.

ts
interface RequestHandler<
Params extends Partial<Record<string, string>> = Partial<
Record<string, string>
>,
RouteId extends string | null = string | null
> {}
ts
(event: RequestEvent<Params, RouteId>): MaybePromise<Response>;

ResolveOptionspermalink

ts
interface ResolveOptions {}
ts
transformPageChunk?(input: { html: string; done: boolean }): MaybePromise<string | undefined>;
  • input the html chunk and the info if this is the last chunk

Applies custom transforms to HTML. If done is true, it's the final chunk. Chunks are not guaranteed to be well-formed HTML (they could include an element's opening tag but not its closing tag, for example) but they will always be split at sensible boundaries such as %sveltekit.head% or layout/page components.

ts
filterSerializedResponseHeaders?(name: string, value: string): boolean;
  • name header name
  • value header value

Determines which headers should be included in serialized responses when a load function loads a resource with fetch. By default, none will be included.

ts
preload?(input: { type: 'font' | 'css' | 'js' | 'asset'; path: string }): boolean;
  • input the type of the file and its path

Determines what should be added to the <head> tag to preload it. By default, js, css and font files will be preloaded.

SSRManifestpermalink

ts
interface SSRManifest {}
ts
appDir: string;
ts
appPath: string;
ts
assets: Set<string>;
ts
mimeTypes: Record<string, string>;
ts
_: {
entry: {
file: string;
imports: string[];
stylesheets: string[];
fonts: string[];
};
nodes: SSRNodeLoader[];
routes: SSRRoute[];
matchers(): Promise<Record<string, ParamMatcher>>;
};

private fields

Serverpermalink

ts
class Server {
constructor(manifest: SSRManifest);
init(options: ServerInitOptions): Promise<void>;
respond(request: Request, options: RequestOptions): Promise<Response>;
}

ServerInitOptionspermalink

ts
interface ServerInitOptions {}
ts
env: Record<string, string>;

ServerLoadpermalink

The generic form of PageServerLoad and LayoutServerLoad. You should import those from ./$types (see generated types) rather than using ServerLoad directly.

ts
interface ServerLoad<
Params extends Partial<Record<string, string>> = Partial<
Record<string, string>
>,
ParentData extends Record<string, any> = Record<string, any>,
OutputData extends Record<string, any> | void = Record<string, any> | void,
RouteId extends string | null = string | null
> {}
ts
(event: ServerLoadEvent<Params, ParentData, RouteId>): MaybePromise<OutputData>;

ServerLoadEventpermalink

ts
interface ServerLoadEvent<
Params extends Partial<Record<string, string>> = Partial<
Record<string, string>
>,
ParentData extends Record<string, any> = Record<string, any>,
RouteId extends string | null = string | null
> extends RequestEvent<Params, RouteId> {}
ts
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.

ts
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.

src/routes/+page.js
ts
let count = 0;
export async function load({ depends }) {
Binding element 'depends' implicitly has an 'any' type.7031Binding element 'depends' implicitly has an 'any' type.
depends('increase:count');
 
return { count: count++ };
}
src/routes/+page.svelte
// @errors: 7031
<script>
  import { invalidate } from '$app/navigation';

  export let data;

  const increase = async () => {
    await invalidate('increase:count');
  }
</script>

<p>{data.count}<p>
<button on:click={increase}>Increase Count</button>

ValidationErrorpermalink

The object returned by the invalid function

ts
interface ValidationError<
T extends Record<string, unknown> | undefined = undefined
> extends UniqueInterface {}
ts
status: number;
ts
data: T;

Additional typespermalink

The following are referenced by the public types documented above, but cannot be imported directly:

AdapterEntrypermalink

ts
interface AdapterEntry {}
ts
id: string;

A string that uniquely identifies an HTTP service (e.g. serverless function) and is used for deduplication. For example, /foo/a-[b] and /foo/[c] are different routes, but would both be represented in a Netlify _redirects file as /foo/:param, so they share an ID

ts
filter(route: RouteDefinition): boolean;

A function that compares the candidate route with the current route to determine if it should be treated as a fallback for the current route. For example, /foo/[c] is a fallback for /foo/a-[b], and /[...catchall] is a fallback for all routes

ts
complete(entry: {
generateManifest(opts: { relativePath: string; format?: 'esm' | 'cjs' }): string;
}): MaybePromise<void>;

A function that is invoked once the entry has been created. This is where you should write the function to the filesystem and generate redirect manifests.

Csppermalink

ts
namespace Csp {
type ActionSource = 'strict-dynamic' | 'report-sample';
type BaseSource =
| 'self'
| 'unsafe-eval'
| 'unsafe-hashes'
| 'unsafe-inline'
| 'wasm-unsafe-eval'
| 'none';
type CryptoSource = `${'nonce' | 'sha256' | 'sha384' | 'sha512'}-${string}`;
type FrameSource = HostSource | SchemeSource | 'self' | 'none';
type HostNameScheme = `${string}.${string}` | 'localhost';
type HostSource = `${HostProtocolSchemes}${HostNameScheme}${PortScheme}`;
type HostProtocolSchemes = `${string}://` | '';
type HttpDelineator = '/' | '?' | '#' | '\\';
type PortScheme = `:${number}` | '' | ':*';
type SchemeSource =
| 'http:'
| 'https:'
| 'data:'
| 'mediastream:'
| 'blob:'
| 'filesystem:';
type Source = HostSource | SchemeSource | CryptoSource | BaseSource;
type Sources = Source[];
type UriPath = `${HttpDelineator}${string}`;
}

CspDirectivespermalink

ts
interface CspDirectives {}
ts
'child-src'?: Csp.Sources;
ts
'default-src'?: Array<Csp.Source | Csp.ActionSource>;
ts
'frame-src'?: Csp.Sources;
ts
'worker-src'?: Csp.Sources;
ts
'connect-src'?: Csp.Sources;
ts
'font-src'?: Csp.Sources;
ts
'img-src'?: Csp.Sources;
ts
'manifest-src'?: Csp.Sources;
ts
'media-src'?: Csp.Sources;
ts
'object-src'?: Csp.Sources;
ts
'prefetch-src'?: Csp.Sources;
ts
'script-src'?: Array<Csp.Source | Csp.ActionSource>;
ts
'script-src-elem'?: Csp.Sources;
ts
'script-src-attr'?: Csp.Sources;
ts
'style-src'?: Array<Csp.Source | Csp.ActionSource>;
ts
'style-src-elem'?: Csp.Sources;
ts
'style-src-attr'?: Csp.Sources;
ts
'base-uri'?: Array<Csp.Source | Csp.ActionSource>;
ts
sandbox?: Array<
| 'allow-downloads-without-user-activation'
| 'allow-forms'
| 'allow-modals'
| 'allow-orientation-lock'
| 'allow-pointer-lock'
| 'allow-popups'
| 'allow-popups-to-escape-sandbox'
| 'allow-presentation'
| 'allow-same-origin'
| 'allow-scripts'
| 'allow-storage-access-by-user-activation'
| 'allow-top-navigation'
| 'allow-top-navigation-by-user-activation'
>;
ts
'form-action'?: Array<Csp.Source | Csp.ActionSource>;
ts
'frame-ancestors'?: Array<Csp.HostSource | Csp.SchemeSource | Csp.FrameSource>;
ts
'navigate-to'?: Array<Csp.Source | Csp.ActionSource>;
ts
'report-uri'?: Csp.UriPath[];
ts
'report-to'?: string[];
ts
'require-trusted-types-for'?: Array<'script'>;
ts
'trusted-types'?: Array<'none' | 'allow-duplicates' | '*' | string>;
ts
'upgrade-insecure-requests'?: boolean;
ts
'require-sri-for'?: Array<'script' | 'style' | 'script style'>;
ts
'block-all-mixed-content'?: boolean;
ts
'plugin-types'?: Array<`${string}/${string}` | 'none'>;
ts
referrer?: Array<
| 'no-referrer'
| 'no-referrer-when-downgrade'
| 'origin'
| 'origin-when-cross-origin'
| 'same-origin'
| 'strict-origin'
| 'strict-origin-when-cross-origin'
| 'unsafe-url'
| 'none'
>;

HttpMethodpermalink

ts
type HttpMethod = 'GET' | 'HEAD' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';

Loggerpermalink

ts
interface Logger {}
ts
(msg: string): void;
ts
success(msg: string): void;
ts
error(msg: string): void;
ts
warn(msg: string): void;
ts
minor(msg: string): void;
ts
info(msg: string): void;

MaybePromisepermalink

ts
type MaybePromise<T> = T | Promise<T>;

PrerenderHttpErrorHandlerpermalink

ts
interface PrerenderHttpErrorHandler {}
ts
(details: {
status: number;
path: string;
referrer: string | null;
referenceType: 'linked' | 'fetched';
}): void;

PrerenderHttpErrorHandlerValuepermalink

ts
type PrerenderHttpErrorHandlerValue =
| 'fail'
| 'warn'
| 'ignore'

PrerenderMappermalink

ts
type PrerenderMap = Map<string, PrerenderOption>;

PrerenderMissingIdHandlerpermalink

ts
interface PrerenderMissingIdHandler {}
ts
(details: { path: string; id: string; referrers: string[] }): void;

PrerenderMissingIdHandlerValuepermalink

ts
type PrerenderMissingIdHandlerValue =
| 'fail'
| 'warn'
| 'ignore'

PrerenderOptionpermalink

ts
type PrerenderOption = boolean | 'auto';

Prerenderedpermalink

ts
interface Prerendered {}
ts
pages: Map<
string,
{
/** The location of the .html file relative to the output directory */
file: string;
}
>;
ts
assets: Map<
string,
{
/** The MIME type of the asset */
type: string;
}
>;
ts
redirects: Map<
string,
{
status: number;
location: string;
}
>;
ts
paths: string[];

An array of prerendered paths (without trailing slashes, regardless of the trailingSlash config)

RequestOptionspermalink

ts
interface RequestOptions {}
ts
getClientAddress(): string;
ts
platform?: App.Platform;

RouteDefinitionpermalink

ts
interface RouteDefinition {}
ts
id: string;
ts
pattern: RegExp;
ts
segments: RouteSegment[];
ts
methods: HttpMethod[];

RouteSegmentpermalink

ts
interface RouteSegment {}
ts
content: string;
ts
dynamic: boolean;
ts
rest: boolean;

TrailingSlashpermalink

ts
type TrailingSlash = 'never' | 'always' | 'ignore';

UniqueInterfacepermalink

ts
interface UniqueInterface {}
ts
readonly [uniqueSymbol]: unknown;

Apppermalink

It's possible to tell SvelteKit how to type objects inside your app by declaring the App namespace. By default, a new project will have a file called src/app.d.ts containing the following:

ts
/// <reference types="@sveltejs/kit" />
 
declare namespace App {
interface Locals {}
 
interface PageData {}
 
interface Platform {}
}

By populating these interfaces, you will gain type safety when using event.locals, event.platform, and data from load functions.

Note that since it's an ambient declaration file, you have to be careful when using import statements. Once you add an import at the top level, the declaration file is no longer considered ambient and you lose access to these typings in other files. To avoid this, either use the import(...) function:

ts
interface Locals {
user: import('$lib/types').User;
}

Or wrap the namespace with declare global:

ts
import { User } from '$lib/types';
 
declare global {
namespace App {
interface Locals {
user: User;
}
// ...
}
}

Errorpermalink

Defines the common shape of expected and unexpected errors. Expected errors are thrown using the error function. Unexpected errors are handled by the handleError hooks which should return this shape.

ts
interface Error {}
ts
message: string;

Localspermalink

The interface that defines event.locals, which can be accessed in hooks (handle, and handleError), server-only load functions, and +server.js files.

ts
interface Locals {}

PageDatapermalink

Defines the common shape of the $page.data store - that is, the data that is shared between all pages. The Load and ServerLoad functions in ./$types will be narrowed accordingly. Use optional properties for data that is only present on specific pages. Do not add an index signature ([key: string]: any).

ts
interface PageData {}

Platformpermalink

If your adapter provides platform-specific context via event.platform, you can specify it here.

ts
interface Platform {}

Generated typespermalink

The RequestHandler and Load types both accept a Params argument allowing you to type the params object. For example this endpoint expects foo, bar and baz params:

src/routes/[foo]/[bar]/[baz]/+page.server.js
ts
/** @type {import('@sveltejs/kit').RequestHandler<{
* foo: string;
* bar: string;
* baz: string
* }>} */
export async function GET({ params }) {
A function whose declared type is neither 'void' nor 'any' must return a value.2355A function whose declared type is neither 'void' nor 'any' must return a value.
// ...
}
src/routes/[foo]/[bar]/[baz]/+page.server.ts
ts
import type { RequestHandler } from '@sveltejs/kit';
 
export const GET: RequestHandler = async ({ params }) => {
Type '({ params }: RequestEvent<Partial<Record<string, string>>, string | null>) => Promise<void>' is not assignable to type 'RequestHandler<Partial<Record<string, string>>, string | null>'. Type 'Promise<void>' is not assignable to type 'MaybePromise<Response>'. Type 'Promise<void>' is not assignable to type 'Promise<Response>'. Type 'void' is not assignable to type 'Response'.2322Type '({ params }: RequestEvent<Partial<Record<string, string>>, string | null>) => Promise<void>' is not assignable to type 'RequestHandler<Partial<Record<string, string>>, string | null>'. Type 'Promise<void>' is not assignable to type 'MaybePromise<Response>'. Type 'Promise<void>' is not assignable to type 'Promise<Response>'. Type 'void' is not assignable to type 'Response'.
// ...
}

Needless to say, this is cumbersome to write out, and less portable (if you were to rename the [foo] directory to [qux], the type would no longer reflect reality).

To solve this problem, SvelteKit generates .d.ts files for each of your endpoints and pages:

.svelte-kit/types/src/routes/[foo]/[bar]/[baz]/$types.d.ts
ts
import type * as Kit from '@sveltejs/kit';
 
type RouteParams = {
foo: string;
bar: string;
baz: string;
}
 
export type PageServerLoad = Kit.ServerLoad<RouteParams>;
export type PageLoad = Kit.Load<RouteParams>;

These files can be imported into your endpoints and pages as siblings, thanks to the rootDirs option in your TypeScript configuration:

src/routes/[foo]/[bar]/[baz]/+page.server.js
ts
/** @type {import('./$types').PageServerLoad} */
export async function GET({ params }) {
// ...
}
src/routes/[foo]/[bar]/[baz]/+page.server.ts
ts
import type { PageServerLoad } from './$types';
 
export const GET: PageServerLoad = async ({ params }) => {
// ...
}
src/routes/[foo]/[bar]/[baz]/+page.js
ts
/** @type {import('./$types').PageLoad} */
export async function load({ params, fetch }) {
// ...
}
src/routes/[foo]/[bar]/[baz]/+page.ts
ts
import type { PageLoad } from './$types';
 
export const load: PageLoad = async ({ params, fetch }) => {
// ...
}

For this to work, your own tsconfig.json or jsconfig.json should extend from the generated .svelte-kit/tsconfig.json (where .svelte-kit is your outDir):

{ "extends": "./.svelte-kit/tsconfig.json" }

Default tsconfig.jsonpermalink

The generated .svelte-kit/tsconfig.json file contains a mixture of options. Some are generated programmatically based on your project configuration, and should generally not be overridden without good reason:

.svelte-kit/tsconfig.json
{
  "compilerOptions": {
    "baseUrl": "..",
    "paths": {
      "$lib": "src/lib",
      "$lib/*": "src/lib/*"
    },
    "rootDirs": ["..", "./types"]
  },
  "include": ["../src/**/*.js", "../src/**/*.ts", "../src/**/*.svelte"],
  "exclude": ["../node_modules/**", "./**"]
}

Others are required for SvelteKit to work properly, and should also be left untouched unless you know what you're doing:

.svelte-kit/tsconfig.json
{
  "compilerOptions": {
    // this ensures that types are explicitly
    // imported with `import type`, which is
    // necessary as svelte-preprocess cannot
    // otherwise compile components correctly
    "importsNotUsedAsValues": "error",

    // Vite compiles one TypeScript module
    // at a time, rather than compiling
    // the entire module graph
    "isolatedModules": true,

    // TypeScript cannot 'see' when you
    // use an imported value in your
    // markup, so we need this
    "preserveValueImports": true,

    // This ensures both `vite build`
    // and `svelte-package` work correctly
    "lib": ["esnext", "DOM", "DOM.Iterable"],
    "moduleResolution": "node",
    "module": "esnext",
    "target": "esnext"
  }
}
We stand with Ukraine. Donate → We stand with Ukraine. Petition your leaders. Show your support.