Reference
Types
Edit this page on GitHubPublic types permalink
The following types can be imported from
@sveltejs/kit
:
Action permalink
Shape of a form action method that is part of
export const actions = {..}
in
+page.server.js
.
See
form actions
for more information.
ts
type 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> = (event: RequestEvent<Params, RouteId>) => MaybePromise<OutputData>;
ActionFailure permalink
ts
interface ActionFailure<T extends Record<string, unknown> | undefined = undefined> {…}
ts
status: number;
ActionResult permalink
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
tstype 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 };
Actions
permalink
Shape of the
export const actions = {..}
object in
+page.server.js
.
See
form actions
for more information.
tstype 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>>;
Adapter
permalink
Adapters
are responsible for taking the production build and turning it into something that can be deployed to a platform of your choosing.
tsinterface Adapter {…}
tsname: string;
The name of the adapter, using for logging. Will typically correspond to the package name.
Checks called during dev and build to determine whether specific features will work in production with this adapter
tsread?: (details: { config: any; route: { id: string } }) => boolean;
Creates an
Emulator
, which allows the adapter to influence the environment
during dev, build and prerendering
AfterNavigate
permalink
The argument passed to
afterNavigate
callbacks.
tsinterface AfterNavigate extends Omit<Navigation, 'type'> {…}
tstype: Exclude<NavigationType, 'leave'>;
The type of navigation:
enter
: The app has hydrated
form
: The user submitted a
<form>
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
tswillUnload: false;
Since
afterNavigate
callbacks are called after a navigation completes, they will never be called with a navigation that unloads the page.
AwaitedActions
permalink
tstype AwaitedActions< T extends Record<string, (...args: any) => any>> = OptionalUnion< { [Key in keyof T]: UnpackValidationError< Awaited<ReturnType<T[Key]>> >; }[keyof T]>;
BeforeNavigate
permalink
The argument passed to
beforeNavigate
callbacks.
tsinterface BeforeNavigate extends Navigation {…}
tscancel(): void;
Call this to prevent the navigation from starting.
Builder
permalink
This object is passed to the
adapt
function of adapters.
It contains various methods and properties that are useful for adapting the app.
tsinterface Builder {…}
tslog: Logger;
Print messages to the console.
log.info
and
log.minor
are silent unless Vite's
logLevel
is
info
.
fn
A function that groups a set of routes into an entry point
deprecated
Use
builder.routes
instead
Create separate functions that map to one or more routes of your app.
opts
a relative path to the base directory of the app and optionally in which format (esm or cjs) the manifest should be generated
Generate a server-side manifest to initialise the SvelteKit
server
with.
from
the source file or directory
to
the destination file or directory
opts.filter
a function to determine whether a file or directory should be copied
opts.replace
a map of strings to replace
returns
an array of files that were copied
Copy a file or directory.
directory
The directory containing the files to be compressed
Compress files in
directory
with gzip and brotli, where appropriate. Generates
.gz
and
.br
files alongside the originals.
Config
permalink
tsinterface Config {…}
See the
configuration reference
for details.
Cookies
permalink
tsinterface Cookies {…}
tsget(name: string, opts?: import('cookie').CookieParseOptions): string | undefined;
name
the name of the cookie
opts
the options, passed directly to
cookie.parse
. See documentation
here
Gets a cookie that was previously set with
cookies.set
, or from the request headers.
name
the name of the cookie
value
the cookie value
opts
the options, passed directly to
cookie.serialize
. See documentation
here
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
name
the name of the cookie
opts
the options, passed directly to
cookie.serialize
. The
path
must match the path of the cookie you want to delete. See documentation
here
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
name
the name of the cookie
value
the cookie value
opts
the options, passed directly to
cookie.serialize
. See documentation
here
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
permalink
A collection of functions that influence the environment during dev, build and prerendering
tsinterface Emulator {…}
tsplatform?(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
Handle
permalink
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
type Handle = (input: { event: RequestEvent; resolve( event: RequestEvent, opts?: ResolveOptions ): MaybePromise<Response>;}) => MaybePromise<Response>;
HandleClientError
permalink
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.
tstype HandleClientError = (input: { error: unknown; event: NavigationEvent; status: number; message: string;}) => MaybePromise<void | App.Error>;
HandleFetch
permalink
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)
tstype HandleFetch = (input: { event: RequestEvent; request: Request; fetch: typeof fetch;}) => MaybePromise<Response>;
HandleServerError
permalink
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.
tstype HandleServerError = (input: { error: unknown; event: RequestEvent; status: number; message: string;}) => MaybePromise<void | App.Error>;
HttpError
permalink
The object returned by the
error
function.
tsinterface HttpError {…}
tsstatus: number;
The
HTTP status code
, in the range 400-599.
LessThan
permalink
tstype LessThan< TNumber extends number, TArray extends any[] = []> = TNumber extends TArray['length']
? TArray[number] : LessThan<TNumber, [...TArray, TArray['length']]>;
Load
permalink
The generic form of
PageLoad
and
LayoutLoad
. You should import those from
./$types
(see
generated types
)
rather than using
Load
directly.
tstype 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> = ( event: LoadEvent<Params, InputData, ParentData, RouteId>) => MaybePromise<OutputData>;
LoadEvent
permalink
The generic form of
PageLoadEvent
and
LayoutLoadEvent
. You should import those from
./$types
(see
generated types
)
rather than using
LoadEvent
directly.
tsinterface 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> {…}
tsfetch: 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 by hooking into the
text
and
json
methods of the
Response
object. 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.
You can learn more about making credentialed requests with cookies
here
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
tsexport async function load ({ fetch , setHeaders }) {Binding element 'fetch' implicitly has an 'any' type.Binding element 'setHeaders' implicitly has an 'any' type.7031
7031Binding 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 ();}
src/routes/blog/+page.ts
tsexport async function load ({ fetch , setHeaders }) {Binding element 'fetch' implicitly has an 'any' type.Binding element 'setHeaders' implicitly has an 'any' type.7031
7031Binding 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.
await parent()
returns data from parent
+layout.js
load
functions.
Implicitly, a missing
+layout.js
is treated as a
({ data }) => data
function, meaning that it will return and forward data from parent
+layout.server.js
files.
Be careful not to introduce accidental waterfalls when using
await parent()
. If for example you only want to merge parent data into the returned output, call it
after
fetching your other data.
This function declares that the
load
function has a
dependency
on one or more URLs or custom identifiers, which can subsequently be used with
invalidate()
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
invalidate
d 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.ts
tslet 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
<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>
tsuntrack<T>(fn: () => T): T;
Use this function to opt out of dependency tracking for everything that is synchronously called within the callback. Example:
src/routes/+page.server.js
tsexport async function load ({ untrack , url }) {Binding element 'untrack' implicitly has an 'any' type.Binding element 'url' implicitly has an 'any' type.7031
7031Binding element 'untrack' implicitly has an 'any' type.Binding element 'url' implicitly has an 'any' type. // Untrack url.pathname so that path changes don't trigger a rerun if (untrack (() => url .pathname === '/')) { return { message : 'Welcome!' }; }}
src/routes/+page.server.ts
tsexport async function load ({ untrack , url }) {Binding element 'untrack' implicitly has an 'any' type.Binding element 'url' implicitly has an 'any' type.7031
7031Binding element 'untrack' implicitly has an 'any' type.Binding element 'url' implicitly has an 'any' type. // Untrack url.pathname so that path changes don't trigger a rerun if (untrack (() => url .pathname === '/')) { return { message : 'Welcome!' }; }}
LoadProperties
permalink
ts
type LoadProperties< input extends Record<string, any> | void> = input extends void ? undefined // needs to be undefined, because void will break intellisense : input extends Record<string, any> ? input : unknown;
Navigation
permalink
tsinterface Navigation {…}
tsfrom: NavigationTarget | null;
Where navigation was triggered from
form
: The user submitted a
<form>
leave
: The app is being left either because the tab is being closed or a navigation to a different document is occurring
link
: Navigation was triggered by a link click
goto
: Navigation was triggered by a
goto(...)
call or a redirect
popstate
: Navigation was triggered by back/forward navigation
tswillUnload: boolean;
Whether or not the navigation will result in the page being unloaded (i.e. not a client-side navigation)
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
NavigationEvent
permalink
tsinterface NavigationEvent< Params extends Partial<Record<string, string>> = Partial< Record<string, string> >, RouteId extends string | null = string | null> {…}
tsparams: Params;
The parameters of the current page - e.g. for a route like
/blog/[slug]
, a
{ slug: string }
object
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).
NavigationType
permalink
-
enter
: The app has hydrated
-
form
: The user submitted a
<form>
with a GET method
-
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
tstype NavigationType = | 'enter' | 'form' | 'leave' | 'link' | 'goto' | 'popstate';
NumericRange
permalink
tstype NumericRange< TStart extends number, TEnd extends number> = Exclude<TEnd | LessThan<TEnd>, LessThan<TStart>>;
OnNavigate
permalink
The argument passed to
onNavigate
callbacks.
tsinterface OnNavigate extends Navigation {…}
tstype: Exclude<NavigationType, 'enter' | 'leave'>;
The type of navigation:
form
: The user submitted a
<form>
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
tswillUnload: false;
Since
onNavigate
callbacks are called immediately before a client-side navigation, they will never be called with a navigation that unloads the page.
Page
permalink
The shape of the
$page
store
tsinterface Page< Params extends Record<string, string> = Record< string, string >, RouteId extends string | null = string | null> {…}
tsurl: URL;
The URL of the current page
tstype PrerenderOption = boolean | 'auto';
Redirect
permalink
The object returned by the
redirect
function
tsinterface Redirect {…}
tsstatus: 300 | 301 | 302 | 303 | 304 | 305 | 306 | 307 | 308;
The
HTTP status code
, in the range 300-308.
RequestEvent
permalink
tsinterface RequestEvent< Params extends Partial<Record<string, string>> = Partial< Record<string, string> >, RouteId extends string | null = string | null> {…}
tscookies: Cookies;
Get or set cookies related to the current request
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 by hooking into the
text
and
json
methods of the
Response
object. 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.
You can learn more about making credentialed requests with cookies
here
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
7031Binding 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 ();}
src/routes/blog/+page.ts
tsexport async function load ({ fetch , setHeaders }) {Binding element 'fetch' implicitly has an 'any' type.Binding element 'setHeaders' implicitly has an 'any' type.7031
7031Binding 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.
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.
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.
RequestHandler
permalink
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.
tstype RequestHandler< Params extends Partial<Record<string, string>> = Partial<
Record<string, string> >, RouteId extends string | null = string | null> = ( event: RequestEvent<Params, RouteId>) => MaybePromise<Response>;
Reroute
permalink
The
reroute
hook allows you to modify the URL before it is used to determine which route to render.
tstype Reroute = (event: { url: URL }) => void | string;
ResolveOptions
permalink
tsinterface ResolveOptions {…}
tstransformPageChunk?(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.
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.
input
the type of the file and its path
Determines what should be added to the
<head>
tag to preload it.
By default,
js
and
css
files will be preloaded.
RouteDefinition
permalink
tsinterface RouteDefinition<Config = any> {…}
tsid: string;
A function that turns an asset filename into a
ReadableStream
. Required for the
read
export from
$app/server
to work
ServerLoad
permalink
The generic form of
PageServerLoad
and
LayoutServerLoad
. You should import those from
./$types
(see
generated types
)
rather than using
ServerLoad
directly.
tstype 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> = ( event: ServerLoadEvent<Params, ParentData, RouteId>) => MaybePromise<OutputData>;
ServerLoadEvent
permalink
tsinterface 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> {…}
tsparent(): 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.
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
invalidate
d after a button click, making the
load
function rerun.
src/routes/+page.js
tslet 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.ts
tslet 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
<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>
tsuntrack<T>(fn: () => T): T;
Use this function to opt out of dependency tracking for everything that is synchronously called within the callback. Example:
src/routes/+page.js
tsexport async function load ({ untrack , url }) {Binding element 'untrack' implicitly has an 'any' type.Binding element 'url' implicitly has an 'any' type.7031
7031Binding element 'untrack' implicitly has an 'any' type.Binding element 'url' implicitly has an 'any' type. // Untrack url.pathname so that path changes don't trigger a rerun if (untrack (() => url .pathname === '/')) { return { message : 'Welcome!' }; }}
src/routes/+page.ts
tsexport async function load ({ untrack , url }) {Binding element 'untrack' implicitly has an 'any' type.Binding element 'url' implicitly has an 'any' type.7031
7031Binding element 'untrack' implicitly has an 'any' type.Binding element 'url' implicitly has an 'any' type. // Untrack url.pathname so that path changes don't trigger a rerun if (untrack (() => url .pathname === '/')) { return { message : 'Welcome!' }; }}
Snapshot
permalink
The type of
export const snapshot
exported from a page or layout component.
tsinterface Snapshot<T = any> {…}
tscapture: () => T;
SubmitFunction
permalink
tstype 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>; }) => void)>;
Private types
permalink
The following are referenced by the public types documented above, but cannot be imported directly:
AdapterEntry
permalink
tsinterface AdapterEntry {…}
tsid: string;
A string that uniquely identifies an HTTP service (e.g. serverless function) and is used for deduplication.
For example,
/foo/a-[b]
and
/foo/[c]
are different routes, but would both
be represented in a Netlify _redirects file as
/foo/:param
, so they share an ID
A function that compares the candidate route with the current route to determine
if it should be grouped with the current route.
Use cases:
Fallback pages:
/foo/[c]
is a fallback for
/foo/a-[b]
, and
/[...catchall]
is a fallback for all routes
Grouping routes that share a common
config
:
/foo
should be deployed to the edge,
/bar
and
/baz
should be deployed to a serverless function
tscomplete(entry: { generateManifest(opts: { relativePath: string }): 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.
Csp
permalink
tsnamespace 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[];}
CspDirectives
permalink
tsinterface CspDirectives {…}
ts'child-src'?: Csp.Sources;
tssandbox?: 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'>;
HttpMethod
permalink
tstype HttpMethod = | 'GET' | 'HEAD' | 'POST'
| 'PUT' | 'DELETE' | 'PATCH' | 'OPTIONS';
Logger
permalink
tsinterface Logger {…}
ts(msg: string): void;
tstype MaybePromise<T> = T | Promise<T>;
PrerenderEntryGeneratorMismatchHandler
permalink
tsinterface PrerenderEntryGeneratorMismatchHandler {…}
ts(details: { generatedFromId: string; entry: string; matchedId: string; message: string }): void;
PrerenderEntryGeneratorMismatchHandlerValue
permalink
tstype PrerenderEntryGeneratorMismatchHandlerValue = | 'fail' | 'warn' | 'ignore' | PrerenderEntryGeneratorMismatchHandler;
PrerenderHttpErrorHandler
permalink
tsinterface PrerenderHttpErrorHandler {…}
ts(details: {status: number;path: string;referrer: string | null;referenceType: 'linked' | 'fetched';message: string;}): void;
PrerenderHttpErrorHandlerValue
permalink
tstype PrerenderHttpErrorHandlerValue = | 'fail' | 'warn' | 'ignore' | PrerenderHttpErrorHandler;
PrerenderMap
permalink
tstype PrerenderMap = Map<string, PrerenderOption>;
PrerenderMissingIdHandler
permalink
tsinterface PrerenderMissingIdHandler {…}
ts(details: { path: string; id: string; referrers: string[]; message: string }): void;
PrerenderMissingIdHandlerValue
permalink
tstype PrerenderMissingIdHandlerValue = | 'fail' | 'warn' | 'ignore' | PrerenderMissingIdHandler;
PrerenderOption
permalink
tstype PrerenderOption = boolean | 'auto';
Prerendered
permalink
tsinterface Prerendered {…}
tspages: Map<string,{ /** The location of the .html file relative to the output directory */ file: string;}>;
A map of
path
to
{ file }
objects, where a path like
/foo
corresponds to
foo.html
and a path like
/bar/
corresponds to
bar/index.html
.
An array of prerendered paths (without trailing slashes, regardless of the trailingSlash config)
RequestOptions
permalink
tsinterface RequestOptions {…}
tsgetClientAddress(): string;
Generated types
permalink
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
tsexport const GET : import('@sveltejs/kit').RequestHandler <{
Type '({ params }: RequestEvent<{ foo: string; bar: string; baz: string; }, string | null>) => Promise<void>' is not assignable to type 'RequestHandler<{ foo: string; bar: string; baz: 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<{ foo: string; bar: string; baz: string; }, string | null>) => Promise<void>' is not assignable to type 'RequestHandler<{ foo: string; bar: string; baz: 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'. foo : string; bar : string; baz : string;}> = async ({ params }) => { // ...};
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
tsimport 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
tsimport 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
) and TypeScript should be installed as a dependency:
{ "extends": "./.svelte-kit/tsconfig.json" }
Default tsconfig.json
permalink
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
ts{ "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
ts{ "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" }}
App
permalink
Error
permalink
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.
tsinterface Error {…}
tsmessage: string;
Locals
permalink
The interface that defines
event.locals
, which can be accessed in
hooks
(
handle
, and
handleError
), server-only
load
functions, and
+server.js
files.
tsinterface Locals {}
PageData
permalink
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
).
tsinterface PageData {}
PageState
permalink
The shape of the
$page.state
object, which can be manipulated using the
pushState
and
replaceState
functions from
$app/navigation
.
tsinterface PageState {}
Platform
permalink
If your adapter provides
platform-specific context
via
event.platform
, you can specify it here.
tsinterface Platform {}