# commands()
# default()
# get_adapter()
# module()
# get_asset_from_kv(req, env, context)
Parameters
Name | Types | Description |
---|---|---|
req | Request |
|
env | any |
|
context | any |
# res()
# developers.cloudflare.com()
# validate_config(builder, config_file)
Parameters
Name | Types | Description |
---|---|---|
builder | import('@sveltejs/kit').Builder |
|
config_file | string |
# generate_redirects(redirects)
Parameters
Name | Types | Description |
---|---|---|
redirects | Map<string, { status: number; location: string }> |
# get_routes_json(builder, assets, routes)
Parameters
Name | Types | Description |
---|---|---|
builder | import('@sveltejs/kit').Builder |
|
assets | string[] |
|
routes | import('./index.js').AdapterOptions['routes'] |
# worker()
# edge_manifest()
# function()
# generate_edge_functions(params, params.builder)
Parameters
Name | Types | Description |
---|---|---|
params | object |
|
params.builder | import('@sveltejs/kit').Builder |
# generate_lambda_functions(params, params.builder, params.publish, params.split)
Parameters
Name | Types | Description |
---|---|---|
params | object |
|
params.builder | import('@sveltejs/kit').Builder |
|
params.publish | string |
|
params.split | boolean |
# name()
# config()
# h()
# m()
# split_headers(headers)
Splits headers into two categories: single value and multi value
Parameters
Name | Types | Description |
---|---|---|
headers | Headers |
# init()
# is_text(content_type)
Decides how the body should be parsed based on its mime type
Parameters
Name | Types | Description |
---|---|---|
content_type | string |
undefined |
# to_request(event)
Parameters
Name | Types | Description |
---|---|---|
event | import('@netlify/functions').HandlerEvent |
# req()
The original Node request object (https://nodejs.org/api/http.html#class-httpincomingmessage)
# function()
# return()
# serve_prerendered()
# ssr()
# idle_timeout_id()
# shutdown_timeout_id()
# is()
# overrides()
# platforms()
# prerendered_redirects()
# static_vercel_config(builder)
Parameters
Name | Types | Description |
---|---|---|
builder | import('@sveltejs/kit').Builder |
# load()
# GET()
# GET()
# config()
# config()
# config()
# config()
# config()
# expiration()
Expiration time (in seconds) before the cached asset will be re-generated by invoking the Serverless Function. Setting the value to false
means it will never expire.
# sToken()
Random token that can be provided in the URL to bypass the cached version of the asset, by requesting the asset with a __prerender_bypass=GET
or HEAD
request with x-prerender-revalidate: <token>
will force the asset to be re-validated.
# common_parts()
# conflicts()
# counterpart_route()
# create_function_bundle(builder, entry, dir, config)
Parameters
Name | Types | Description |
---|---|---|
builder | import('@sveltejs/kit').Builder |
|
entry | string |
|
dir | string |
|
config | import('./index.js').ServerlessConfig |
# functions()
# generate_serverless_function()
# groups()
# hash_config(config)
Parameters
Name | Types | Description |
---|---|---|
config | import('./index.js').EdgeConfig & import('./index.js').ServerlessConfig |
# images()
# is_prerendered(route)
Parameters
Name | Types | Description |
---|---|---|
route | import('@sveltejs/kit').RouteDefinition |
# isr_config()
# overrides()
# prerendered_redirects()
# static_vercel_config(builder, config, dir)
Parameters
Name | Types | Description |
---|---|---|
builder | import('@sveltejs/kit').Builder |
|
config | import('./index.js').Config |
|
dir | string |
# unmatched_paths()
# run_pattern_to_src_test(route_id, expected)
Parameters
Name | Types | Description |
---|---|---|
route_id | string |
|
expected | string |
# get_pathname(route)
Parameters
Name | Types | Description |
---|---|---|
route | import("@sveltejs/kit").RouteDefinition<any> |
# pattern_to_src(pattern)
Adjusts the stringified route regex for Vercel's routing system
Parameters
Name | Types | Description |
---|---|---|
pattern | string |
stringified route regex |
# enhancedImages()
# fallback()
# image_plugin(imagetools_plugin)
Creates the Svelte image plugin which provides the preprocessor.
Parameters
Name | Types | Description |
---|---|---|
imagetools_plugin | import('vite').Plugin |
# imagetools_opts()
# opts()
# attributes()
# dynamic_img_to_picture(content, node, src_var_name)
For images like <img src={manually_imported} />
Parameters
Name | Types | Description |
---|---|---|
content | string |
|
node | import('svelte/compiler').AST.RegularElement |
|
src_var_name | string |
# image(opts)
Parameters
Name | Types | Description |
---|---|---|
opts | {plugin_context: import('vite').Rollup.PluginContextvite_config: import('vite').ResolvedConfigimagetools_plugin: import('vite').Plugin} |
# img_to_picture(consts, content, node, image)
Parameters
Name | Types | Description |
---|---|---|
consts | Map<string,string> |
|
content | string |
|
node | import('svelte/compiler').AST.RegularElement |
|
image | import('vite-imagetools').Picture |
# node()
# process(resolved_id, opts)
Parameters
Name | Types | Description |
---|---|---|
resolved_id | string |
|
opts | {plugin_context: import('vite').Rollup.PluginContextimagetools_plugin: import('vite').Plugin} |
# serialize_img_attributes(content, attributes, details)
Parameters
Name | Types | Description |
---|---|---|
content | string |
|
attributes | import('../types/internal.ts').Attribute[] |
|
details | {src: string,width: string |
number,height: string |
# update_element(node, src_attribute)
Parameters
Name | Types | Description |
---|---|---|
node | import('svelte/compiler').AST.RegularElement |
|
src_attribute | AST.Text |
AST.ExpressionTag |
# user_height()
# user_width()
# SVELTE_KIT_ASSETS()
A fake asset path used in vite dev
and vite preview
, so that we can serve local assets while verifying that requests are correctly prefixed
# create_builder(opts)
Creates the Builder which is passed to adapters for building the application.
Parameters
Name | Types | Description |
---|---|---|
opts | {config: import('types').ValidatedConfig;build_data: import('types').BuildData;server_metadata: import('types').ServerMetadata;route_data: import('types').RouteData[];prerendered: import('types').Prerendered;prerender_map: import('types').PrerenderMap;log: import('types').Logger;vite_config: import('vite').ResolvedConfig;} |
# lookup()
# load_error_page(config)
Loads the error page (src/error.html by default) if it exists. Falls back to a generic error page content.
Parameters
Name | Types | Description |
---|---|---|
config | import('types').ValidatedConfig |
# load_template(cwd, config)
Loads the template (src/app.html by default) and validates that it has the required content.
Parameters
Name | Types | Description |
---|---|---|
cwd | string |
|
config | import('types').ValidatedConfig |
# remove_keys(o, check)
mutates and remove keys from an object when check callback returns true
Parameters
Name | Types | Description |
---|---|---|
o | Record<string, any> |
any object |
check | ([key, value]: [string, any]) => boolean |
callback with access to the key-value pair and returns a boolean that decides the deletion of key |
# validate_paths(name, input, output)
Parameters
Name | Types | Description |
---|---|---|
name | string |
|
input | import('@sveltejs/kit').KitConfig['paths'] |
|
output | import('@sveltejs/kit').KitConfig['paths'] |
# directives()
# object(children, allow_unknown)
Parameters
Name | Types | Description |
---|---|---|
children | Record<string, Validator> |
|
allow_unknown | boolean |
# options()
# output()
# string(fallback, allow_empty)
Parameters
Name | Types | Description |
---|---|---|
fallback | string |
null |
allow_empty | boolean |
# validate(fallback, fn)
Parameters
Name | Types | Description |
---|---|---|
fallback | any |
|
fn | (value: any, keypath: string) => any |
# create_dynamic_module(type, dev_values)
Parameters
Name | Types | Description |
---|---|---|
type | EnvType |
|
dev_values | Record<string, string> |
undefined |
# create_dynamic_types(id, env, prefixes)
Parameters
Name | Types | Description |
---|---|---|
id | EnvType |
|
env | import('types').Env |
|
prefixes | {public_prefix: string;private_prefix: string;} |
# create_static_module(id, env)
Parameters
Name | Types | Description |
---|---|---|
id | string |
|
env | Record<string, string> |
# declarations()
# find_server_assets(build_data, routes)
Finds all the assets that are imported by server files associated with routes
Parameters
Name | Types | Description |
---|---|---|
build_data | import('types').BuildData |
|
routes | import('types').RouteData[] |
# server_assets()
# used_nodes()
All nodes actually used in the routes definition (prerendered routes are omitted). Root layout/error is always included as they are needed for 404 and root errors.
# files()
# generate_manifest(opts)
Generates the data used to write the server-side manifest.js file. This data is used in the Vite build process, to power routing, etc.
Parameters
Name | Types | Description |
---|---|---|
opts | {build_data: import('types').BuildData;relative_path: string;routes: import('types').RouteData[];} |
# loader()
# manifest_expr()
# reindexed()
# used_nodes()
All nodes actually used in the routes definition (prerendered routes are omitted). Root layout/error is always included as they are needed for 404 and root errors.
# analyse(opts)
Parameters
Name | Types | Description |
---|---|---|
opts | {manifest_path: string;manifest_data: import('types').ManifestData;server_manifest: import('vite').Manifest;tracked_features: Record<string, string[]>;env: Record<string, string>} |
# analyse_endpoint(route, mod)
Parameters
Name | Types | Description |
---|---|---|
route | import('types').SSRRoute |
|
mod | import('types').SSREndpoint |
# analyse_page(layouts, leaf)
Parameters
Name | Types | Description |
---|---|---|
layouts | Array<import('types').SSRNode |
undefined> |
leaf | import('types').SSRNode |
# config()
# internal()
# manifest()
# metadata()
# methods()
# attributes()
# hrefs()
# ids()
# entities()
A list of all named HTML entities, from https://html.spec.whatwg.org/multipage/named-characters.html
# config()
# generate_fallback(opts)
Parameters
Name | Types | Description |
---|---|---|
opts | {manifest_path: string;env: Record<string, string>} |
# index.js()
# internal.js()
# manifest()
# actual_hashlinks()
# config()
# dependencies()
# enqueue(referrer, decoded, encoded, generated_from_id)
Parameters
Name | Types | Description |
---|---|---|
referrer | string |
null |
decoded | string |
|
encoded | string |
|
generated_from_id | string |
# expected_hashlinks()
# index.js()
# internal()
# log()
# manifest()
# normalise_error_handler(log, input, format)
Parameters
Name | Types | Description |
---|---|---|
log | import('types').Logger |
|
input | 'fail' |
'warn' |
format | (details: K) => string |
# not_prerendered()
# prerender(opts)
Parameters
Name | Types | Description |
---|---|---|
opts | {out: string;manifest_path: string;metadata: import('types').ServerMetadata;verbose: boolean;env: Record<string, string>} |
# prerender_map()
# prerendered()
# prerendered_routes()
# route_level_entries()
# save(category, response, body, decoded, encoded, referrer, referenceType)
Parameters
Name | Types | Description |
---|---|---|
category | 'pages' |
'dependencies' |
response | Response |
|
body | string |
Uint8Array |
decoded | string |
|
encoded | string |
|
referrer | string |
null |
referenceType | 'linked' |
'fetched' |
# saved()
# visit(decoded, encoded, referrer, generated_from_id)
Parameters
Name | Types | Description |
---|---|---|
decoded | string |
|
encoded | string |
|
referrer | string |
|
generated_from_id | string |
# fulfil()
# reject()
# tasks()
# fulfils()
# analyze(project_relative, file, component_extensions, module_extensions)
Parameters
Name | Types | Description |
---|---|---|
project_relative | string |
|
file | string |
|
component_extensions | string[] |
|
module_extensions | string[] |
# count_occurrences(needle, haystack)
Parameters
Name | Types | Description |
---|---|---|
needle | string |
|
haystack | string |
# create_hooks(config, cwd)
Parameters
Name | Types | Description |
---|---|---|
config | import('types').ValidatedConfig |
|
cwd | string |
# create_manifest_data(opts)
Generates the manifest data used for the client-side manifest and types generation.
Parameters
Name | Types | Description |
---|---|---|
opts | {config: import('types').ValidatedConfig;fallback: string;cwd?: string;} |
# create_matchers(config, cwd)
Parameters
Name | Types | Description |
---|---|---|
config | import('types').ValidatedConfig |
|
cwd | string |
# create_routes_and_nodes(config, cwd, fallback)
Parameters
Name | Types | Description |
---|---|---|
config | import('types').ValidatedConfig |
|
cwd | string |
|
fallback | string |
# matchers()
# nodes()
# route()
# routes()
# walk(depth, id, segment, parent)
Parameters
Name | Types | Description |
---|---|---|
depth | number |
|
id | string |
|
segment | string |
|
parent | import('types').RouteData |
null |
# simplified()
# EMPTY()
# parts()
# segment_cache()
# sort_static(a, b)
Sort two strings lexicographically, except foobar
outranks foo
Parameters
Name | Types | Description |
---|---|---|
a | string |
|
b | string |
# all(config, mode)
Run sync.init and sync.create in series, returning the result from sync.create.
Parameters
Name | Types | Description |
---|---|---|
config | import('types').ValidatedConfig |
|
mode | string |
The Vite mode |
# all_types(config, mode)
Run sync.init and then generate all type files.
Parameters
Name | Types | Description |
---|---|---|
config | import('types').ValidatedConfig |
|
mode | string |
The Vite mode |
# create(config)
Update SvelteKit's generated files
Parameters
Name | Types | Description |
---|---|---|
config | import('types').ValidatedConfig |
# init(config, mode)
Initialize SvelteKit's generated files.
Parameters
Name | Types | Description |
---|---|---|
config | import('types').ValidatedConfig |
|
mode | string |
# server(config)
Regenerate SERVER/internal.js in response to src/{app.html,error.html,service-worker.js} changing
Parameters
Name | Types | Description |
---|---|---|
config | import('types').ValidatedConfig |
# update(config, manifest_data, file)
Update SvelteKit's generated files in response to a single file content update. Do not call this when the file in question was created/deleted.
Parameters
Name | Types | Description |
---|---|---|
config | import('types').ValidatedConfig |
|
manifest_data | import('types').ManifestData |
|
file | string |
# dedent_map()
# previous_contents()
# VERSION()
# template(env, prefixes)
Parameters
Name | Types | Description |
---|---|---|
env | import('types').Env |
|
prefixes | {public_prefix: string;private_prefix: string;} |
# write_ambient(config, mode)
Writes ambient declarations including types reference to @sveltejs/kit, and the existing environment variables in process.env to $env/static/private and $env/static/public
Parameters
Name | Types | Description |
---|---|---|
config | import('types').ValidatedKitConfig |
|
mode | string |
The Vite mode |
# generate_node(node)
Creates a module that exports a CSRPageNode
Parameters
Name | Types | Description |
---|---|---|
node | import('types').PageNode |
# write_client_manifest(kit, manifest_data, output, metadata)
Writes the client manifest to disk. The manifest is used to power the router. It contains the list of routes and corresponding Svelte components (i.e. pages and layouts).
Parameters
Name | Types | Description |
---|---|---|
kit | import('types').ValidatedKitConfig |
|
manifest_data | import('types').ManifestData |
|
output | string |
|
metadata | Array<{ has_server_load: boolean }> |
# write_non_ambient(config)
Writes non-ambient declarations to the output directory
Parameters
Name | Types | Description |
---|---|---|
config | import('types').ValidatedKitConfig |
# write_root(manifest_data, output)
Parameters
Name | Types | Description |
---|---|---|
manifest_data | import('types').ManifestData |
|
output | string |
# server_template(opts)
Parameters
Name | Types | Description |
---|---|---|
opts | {server_hooks: string |
null;universal_hooks: string |
# write_server(config, output)
Write server configuration to disk
Parameters
Name | Types | Description |
---|---|---|
config | import('types').ValidatedConfig |
|
output | string |
# get_tsconfig(kit)
Generates the tsconfig that the user's tsconfig inherits from.
Parameters
Name | Types | Description |
---|---|---|
kit | import('types').ValidatedKitConfig |
# get_tsconfig_paths(config)
Generates tsconfig path aliases from kit's aliases. Related to vite alias creation.
Parameters
Name | Types | Description |
---|---|---|
config | import('types').ValidatedKitConfig |
# paths()
# validate_user_config(cwd, out, config)
Parameters
Name | Types | Description |
---|---|---|
cwd | string |
|
out | string |
|
config | { kind: string, options: any } |
# write_tsconfig(kit)
Generates the tsconfig that the user's tsconfig inherits from.
Parameters
Name | Types | Description |
---|---|---|
kit | import('types').ValidatedKitConfig |
# create_routes_map(manifest_data)
Collect all leafs into a leaf -> route map
Parameters
Name | Types | Description |
---|---|---|
manifest_data | import('types').ManifestData |
# createProxy(file_path, is_server)
Parameters
Name | Types | Description |
---|---|---|
file_path | string |
|
is_server | boolean |
# cwd()
# data()
# declarations()
# declarations()
# ensureProxies(node, proxies)
This function populates the proxies object, if necessary and not already done. Proxies are used to tweak the code of a file before it's typechecked. They are needed in two places - when generating the types for a page or layout. To not do the same work twice, we generate the proxies once and pass them around.
Parameters
Name | Types | Description |
---|---|---|
node | import('types').PageNode |
|
proxies | Proxies |
# exports()
# exports()
# generate_params_type(params, outdir, config)
Parameters
Name | Types | Description |
---|---|---|
params | import('types').RouteParam[] |
|
outdir | string |
|
config | import('types').ValidatedConfig |
# get_data_type(file_path, fallback, proxy, expand)
Parameters
Name | Types | Description |
---|---|---|
file_path | string |
|
fallback | string |
|
proxy | Proxy |
|
expand | boolean |
# get_parent_type(node, type)
Get the parent type string by recursively looking up the parent layout and accumulate them to one type.
Parameters
Name | Types | Description |
---|---|---|
node | import('types').PageNode |
|
type | string |
# input_files()
# layout_params()
# map()
# node()
# path_to_original(outdir, file_path)
Parameters
Name | Types | Description |
---|---|---|
outdir | string |
|
file_path | string |
# process_node(node, outdir, is_page, proxies, all_pages_have_load)
Parameters
Name | Types | Description |
---|---|---|
node | import('types').PageNode |
|
outdir | string |
|
is_page | boolean |
|
proxies | Proxies |
|
all_pages_have_load | boolean |
# replace_jsdoc_type_tags(node, value)
Parameters
Name | Types | Description |
---|---|---|
node | import('typescript').Node |
|
value | import('typescript').Node |
# route.layout()
# server_data()
# tweak_types(content, is_server)
Parameters
Name | Types | Description |
---|---|---|
content | string |
|
is_server | boolean |
# update_types(config, routes, route, to_delete)
Update types for a specific route
Parameters
Name | Types | Description |
---|---|---|
config | import('types').ValidatedConfig |
|
routes | RoutesMap |
|
route | import('types').RouteData |
|
to_delete | Set<string> |
# write_types(config, manifest_data, file)
Creates types related to the given file. This should only be called if the file in question was edited, not if it was created/deleted/moved.
Parameters
Name | Types | Description |
---|---|---|
config | import('types').ValidatedConfig |
|
manifest_data | import('types').ManifestData |
|
file | string |
# actions()
# actions()
# c()
# load()
# load()
# load()
# submit()
Ordinarily this would live in a +page.svelte, but to make it easy to run the tests, we put it here. The export
is so that eslint doesn't throw a hissy fit about the unused variable
# data()
# data()
# load()
# load()
# load()
# data()
# load()
# a()
# load()
# a()
# a()
# b()
# load()
# a()
# load()
# a()
# b()
# load()
# a()
# load()
# data()
# load()
# actionData()
# data()
# load()
# data()
# load()
# load()
# load()
# load()
# load()
# load()
# a()
# load()
# files()
# get_mime_lookup(manifest_data)
Parameters
Name | Types | Description |
---|---|---|
manifest_data | import('types').ManifestData |
# list_files(dir, filter)
Parameters
Name | Types | Description |
---|---|---|
dir | string |
|
filter | (file: string) => boolean |
# log()
# mime()
# runtime_base()
This allows us to import SvelteKit internals that aren't exposed via pkg.exports
in a way that works whether @sveltejs/kit
is installed inside the project's node_modules
or in a workspace root
# runtime_directory()
Resolved path of the runtime
directory TODO Windows issue: Vite or sth else somehow sets the driver letter inconsistently to lower or upper case depending on the run environment. In playwright debug mode run through VS Code this a root-to-lowercase conversion is needed in order for the tests to run. If we do this conversion in other cases it has the opposite effect though and fails.
# apply_handle(i, event, parent_options)
Parameters
Name | Types | Description |
---|---|---|
i | number |
|
event | import('@sveltejs/kit').RequestEvent |
|
parent_options | import('@sveltejs/kit').ResolveOptions |
undefined |
# filterSerializedResponseHeaders()
# preload()
# sequence(handlers)
A helper function for sequencing multiple handle
calls in a middleware-like manner. The behavior for the handle
options is as follows: - transformPageChunk
is applied in reverse order and merged - preload
is applied in forward order, the first option "wins" and no preload
options after it are called - filterSerializedResponseHeaders
behaves the same as preload
js /// file: src/hooks.server.js import { sequence } from '@sveltejs/kit/hooks'; /// type: import('@sveltejs/kit').Handle async function first({ event, resolve }) { console.log('first pre-processing'); const result = await resolve(event, { transformPageChunk: ({ html }) => { // transforms are applied in reverse order console.log('first transform'); return html; }, preload: () => { // this one wins as it's the first defined in the chain console.log('first preload'); return true; } }); console.log('first post-processing'); return result; } /// type: import('@sveltejs/kit').Handle async function second({ event, resolve }) { console.log('second pre-processing'); const result = await resolve(event, { transformPageChunk: ({ html }) => { console.log('second transform'); return html; }, preload: () => { console.log('second preload'); return true; }, filterSerializedResponseHeaders: () => { // this one wins as it's the first defined in the chain console.log('second filterSerializedResponseHeaders'); return true; } }); console.log('second post-processing'); return result; } export const handle = sequence(first, second);
The example above would print: first pre-processing first preload second pre-processing second filterSerializedResponseHeaders second transform first transform second post-processing first post-processing
Parameters
Name | Types | Description |
---|---|---|
handlers | ...import('@sveltejs/kit').Handle |
The chain of handle functions |
# transformPageChunk()
# error(status, body)
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.
Parameters
Name | Types | Description |
---|---|---|
status | number |
The HTTP status code. Must be in the range 400-599. |
body | { message: string } extends App.Error App.Error |
string |
Returns
never
# fail(status, data)
Create an ActionFailure
object.
Parameters
Name | Types | Description |
---|---|---|
status | number |
|
data | any |
# isActionFailure(e)
Checks whether this is an action failure thrown by {@link fail}.
Parameters
Name | Types | Description |
---|---|---|
e | unknown |
The object to check. |
Returns
e is import('./public.js').ActionFailure
# isHttpError(e, status)
Checks whether this is an error thrown by {@link error}.
Parameters
Name | Types | Description |
---|---|---|
e | unknown |
|
status | T |
The status to filter for. |
Returns
e is (HttpError & { status: T extends undefined never : T })
# isRedirect(e)
Checks whether this is a redirect thrown by {@link redirect}.
Parameters
Name | Types | Description |
---|---|---|
e | unknown |
The object to check. |
Returns
e is Redirect
# json(data, init)
Create a JSON Response
object from the supplied data.
Parameters
Name | Types | Description |
---|---|---|
data | any |
The value that will be serialized as JSON. |
init | ResponseInit |
Options such as status and headers that will be added to the response. Content-Type: application/json and Content-Length headers will be added automatically. |
# redirect(status, location)
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.
Parameters
Name | Types | Description |
---|---|---|
status | 300 |
301 |
location | string |
URL |
Returns
never
# text(body, init)
Create a Response
object from the supplied body.
Parameters
Name | Types | Description |
---|---|---|
body | string |
The value that will be used as-is. |
init | ResponseInit |
Options such as status and headers that will be added to the response. A Content-Length header will be added automatically. |
# get_raw_body(req, body_size_limit)
Parameters
Name | Types | Description |
---|---|---|
req | import('http').IncomingMessage |
|
body_size_limit | number |
# globals()
# ...deps()
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. js /// file: src/routes/+page.js let count = 0; export async function load({ depends }) { depends('increase:count'); return { count: count++ }; }
html /// file: src/routes/+page.svelte <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>
# ...deps()
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. js /// file: src/routes/+page.js let count = 0; export async function load({ depends }) { depends('increase:count'); return { count: count++ }; }
html /// file: src/routes/+page.svelte <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>
# adapt(builder)
This function is called after SvelteKit has built your app.
Parameters
Name | Types | Description |
---|---|---|
builder |
|
An object provided by SvelteKit that contains methods for adapting the app |
# App.PageData()
The merged result of all data from all load
functions on the current page. You can type a common denominator through App.PageData
.
# App.PageState()
The page state, which can be manipulated using the pushState
and replaceState
functions from $app/navigation
.
# App.Platform()
A function that is called with the current route config
and prerender
option and returns an App.Platform
object
# complete()
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
# compress(directory)
Compress files in directory
with gzip and brotli, where appropriate. Generates .gz
and .br
files alongside the originals.
Parameters
Name | Types | Description |
---|---|---|
directory | string |
The directory containing the files to be compressed |
# config()
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.
# copy(from, to, opts.filter, opts.replace)
Copy a file or directory.
Parameters
Name | Types | Description |
---|---|---|
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 |
# createEntries(fn)
Create separate functions that map to one or more routes of your app.
Parameters
Name | Types | Description |
---|---|---|
fn |
|
A function that groups a set of routes into an entry point |
# data()
Contains the data returned by the route's server load
function (in +layout.server.js
or +page.server.js
), if any.
# delete(name, opts)
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
Parameters
Name | Types | Description |
---|---|---|
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 |
# details(config)
Test support for read
from $app/server
Parameters
Name | Types | Description |
---|---|---|
config |
|
The merged route config |
# e()
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
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.
# event()
The reroute
hook allows you to modify the URL before it is used to determine which route to render.
# 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
# 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
# file()
A function that turns an asset filename into a ReadableStream
. Required for the read
export from $app/server
to work
# filepath()
Determine which files in your static
directory will be available in $service-worker.files
.
# fn()
Use this function to opt out of dependency tracking for everything that is synchronously called within the callback. Example: js /// file: src/routes/+page.server.js export async function load({ untrack, url }) { // Untrack url.pathname so that path changes don't trigger a rerun if (untrack(() => url.pathname === '/')) { return { message: 'Welcome!' }; } }
# fn()
Use this function to opt out of dependency tracking for everything that is synchronously called within the callback. Example: js /// file: src/routes/+page.js export async function load({ untrack, url }) { // Untrack url.pathname so that path changes don't trigger a rerun if (untrack(() => url.pathname === '/')) { return { message: 'Welcome!' }; } }
# generateEnvModule()
Generate a module exposing build-time environment variables as $env/dynamic/public
.
# generateFallback()
Generate a fallback page for a static webserver to use when no route is matched. Useful for single-page apps.
# generateManifest(opts)
Generate a server-side manifest to initialise the SvelteKit server with.
Parameters
Name | Types | Description |
---|---|---|
opts |
|
a relative path to the base directory of the app and optionally in which format (esm or cjs) the manifest should be generated |
# get(name, opts)
Gets a cookie that was previously set with cookies.set
, or from the request headers.
Parameters
Name | Types | Description |
---|---|---|
name |
|
the name of the cookie |
opts |
|
the options, passed directly to cookie.parse . See documentation here |
# getAll(opts)
Gets all cookies that were previously set with cookies.set
, or from the request headers.
Parameters
Name | Types | Description |
---|---|---|
opts |
|
the options, passed directly to cookie.parse . See documentation here |
# getBuildDirectory(name)
Resolve a path to the name
directory inside outDir
, e.g. /path/to/.svelte-kit/my-adapter
.
Parameters
Name | Types | Description |
---|---|---|
name |
|
path to the file, relative to the build directory |
# getClientDirectory()
Get the fully resolved path to the directory containing client-side assets, including the contents of your static
directory.
# h()
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.
# http()
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.
# input()
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).
# input()
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.
# input()
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.
# input()
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)
# input(input)
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.
Parameters
Name | Types | Description |
---|---|---|
input |
|
the html chunk and the info if this is the last chunk |
# input(input)
Determines what should be added to the <head>
tag to preload it. By default, js
and css
files will be preloaded.
Parameters
Name | Types | Description |
---|---|---|
input |
|
the type of the file and its path |
# isDataRequest()
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()
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.
# log()
Print messages to the console. log.info
and log.minor
are silent unless Vite's logLevel
is info
.
# name(name, 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.
Parameters
Name | Types | Description |
---|---|---|
name |
|
header name |
value |
|
header value |
# params()
The parameters of the current page - e.g. for a route like /blog/[slug]
, a { slug: string }
object
# params()
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).
# params()
The parameters of the current page - e.g. for a route like /blog/[slug]
, a { slug: string }
object
# params()
The parameters of the current route - e.g. for a route like /blog/[slug]
, a { slug: string }
object
# parent()
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.
# parent()
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.
# serialize(name, value, opts)
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
Parameters
Name | Types | Description |
---|---|---|
name |
|
the name of the cookie |
value |
|
the cookie value |
opts |
|
the options, passed directly to cookie.serialize . See documentation here |
# set(name, value, opts)
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
Parameters
Name | Types | Description |
---|---|---|
name |
|
the name of the cookie |
value |
|
the cookie value |
opts |
|
the options, passed directly to cookie.serialize . See documentation here |
# setHeaders()
If you need to set headers for the response, you can do so using the this method. This is useful if you want the page to be cached, for example: js /// file: src/routes/blog/+page.js export async function load({ fetch, setHeaders }) { const url = `https://cms.example.com/articles.json`; const response = await fetch(url); setHeaders({ age: response.headers.get('age'), 'cache-control': response.headers.get('cache-control') }); return response.json(); }
Setting the same header multiple times (even in separate load
functions) is an error — you can only set a given header once. You cannot add a set-cookie
header with setHeaders
— use the cookies
API in a server-only load
function instead. setHeaders
has no effect when a load
function runs in the browser.
# setHeaders()
If you need to set headers for the response, you can do so using the this method. This is useful if you want the page to be cached, for example: js /// file: src/routes/blog/+page.js export async function load({ fetch, setHeaders }) { const url = `https://cms.example.com/articles.json`; const response = await fetch(url); setHeaders({ age: response.headers.get('age'), 'cache-control': response.headers.get('cache-control') }); return response.json(); }
Setting the same header multiple times (even in separate load
functions) is an error — you can only set a given header once. You cannot add a set-cookie
header with setHeaders
— use the cookies
API instead.
# type()
The type of navigation: - 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
# type()
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
# type()
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
# update(options, invalidateAll)
Call this to get the default behavior of a form submission response.
Parameters
Name | Types | Description |
---|---|---|
options |
|
Set reset: false if you don't want the <form> values to be reset after a successful submission. |
invalidateAll |
|
Set invalidateAll: false if you don't want the action to call invalidateAll after submission. |
# willUnload()
Whether or not the navigation will result in the page being unloaded (i.e. not a client-side navigation)
# willUnload()
Since onNavigate
callbacks are called immediately before a client-side navigation, they will never be called with a navigation that unloads the page.
# willUnload()
Since afterNavigate
callbacks are called after a navigation completes, they will never be called with a navigation that unloads the page.
# writeClient(dest)
Write client assets to dest
.
Parameters
Name | Types | Description |
---|---|---|
dest |
|
the destination folder |
# writePrerendered(dest)
Write prerendered files to dest
.
Parameters
Name | Types | Description |
---|---|---|
dest |
|
the destination folder |
# writeServer(dest)
Write server-side code to dest
.
Parameters
Name | Types | Description |
---|---|---|
dest |
|
the destination folder |
# build_server_nodes(out, kit, manifest_data, server_manifest, client_manifest, css)
Parameters
Name | Types | Description |
---|---|---|
out | string |
|
kit | import('types').ValidatedKitConfig |
|
manifest_data | import('types').ManifestData |
|
server_manifest | import('vite').Manifest |
|
client_manifest | import('vite').Manifest |
null |
css | import('vite').Rollup.OutputAsset[] |
null |
# exports()
# fonts()
# imported()
# imports()
# styles()
# stylesheets()
# build_service_worker(out, kit, vite_config, manifest_data, service_worker_entry_file, prerendered, client_manifest)
Parameters
Name | Types | Description |
---|---|---|
out | string |
|
kit | import('types').ValidatedKitConfig |
|
vite_config | import('vite').ResolvedConfig |
|
manifest_data | import('types').ManifestData |
|
service_worker_entry_file | string |
|
prerendered | import('types').Prerendered |
|
client_manifest | import('vite').Manifest |
# sw_virtual_modules()
# find_deps(manifest, entry, add_dynamic_css)
Adds transitive JS and CSS dependencies to the js and css inputs.
Parameters
Name | Types | Description |
---|---|---|
manifest | import('vite').Manifest |
|
entry | string |
|
add_dynamic_css | boolean |
# imported_assets()
# imports()
# resolve_symlinks(manifest, file)
Parameters
Name | Types | Description |
---|---|---|
manifest | import('vite').Manifest |
|
file | string |
# seen()
# stylesheets()
# branches()
# deps()
# dev(vite, vite_config, svelte_config)
Parameters
Name | Types | Description |
---|---|---|
vite | import('vite').ViteDevServer |
|
vite_config | import('vite').ResolvedConfig |
|
svelte_config | import('types').ValidatedConfig |
Returns
Promise<Promise<() => void>>
# find_deps(vite, node, deps)
Parameters
Name | Types | Description |
---|---|---|
vite | import('vite').ViteDevServer |
|
node | import('vite').ModuleNode |
|
deps | Set<import('vite').ModuleNode> |
# has_correct_case(file, assets)
Determine if a file is being requested with the correct case, to ensure consistent behaviour between dev and prod and across operating systems. Note that we can't use realpath here, because we don't want to follow symlinks
Parameters
Name | Types | Description |
---|---|---|
file | string |
|
assets | string |
# manifest()
# manifest_data()
# manifest_error()
# matchers()
# remove_static_middlewares(server)
Parameters
Name | Types | Description |
---|---|---|
server | import('connect').Server |
# result()
# styles()
# timeout()
# follow(id, chain)
Parameters
Name | Types | Description |
---|---|---|
id | string |
|
chain | Array<{ id: string; dynamic: boolean }> |
# is_illegal(id, dirs)
Checks if given id imports a module that is not allowed to be imported into client-side code.
Parameters
Name | Types | Description |
---|---|---|
id | string |
|
dirs | {cwd: string;node_modules: string;server: string;} |
# module_guard(context, paths)
Creates a guard that checks that no id imports a module that is not allowed to be imported into client-side code.
Parameters
Name | Types | Description |
---|---|---|
context | import('vite').Rollup.PluginContext |
|
paths | { cwd: string; lib: string } |
# normalize_id(id, lib, cwd)
Removes cwd/lib path from the start of the id
Parameters
Name | Types | Description |
---|---|---|
id | string |
|
lib | string |
|
cwd | string |
# seen()
# config()
Build the SvelteKit-provided Vite config to be merged with the user's vite.config.js file.
# config()
Build the SvelteKit-provided Vite config to be merged with the user's vite.config.js file.
# create_service_worker_module(config)
Parameters
Name | Types | Description |
---|---|---|
config | import('types').ValidatedConfig |
# enforced_config()
# env()
# finalise()
# find_overridden_config(config, resolved_config, enforced_config, path, out)
Parameters
Name | Types | Description |
---|---|---|
config | Record<string, any> |
|
resolved_config | Record<string, any> |
|
enforced_config | import('./types.js').EnforcedConfig |
|
path | string |
|
out | string[] |
used locally to compute the return value |
# import_map()
# initial_config()
# input()
# is_build()
# kit(options)
Returns the SvelteKit Vite plugin. Vite executes Rollup hooks as well as some of its own. Background reading is available at: - https://vitejs.dev/guide/api-plugin.html - https://rollupjs.org/guide/en/#plugin-development You can get an idea of the lifecycle by looking at the flow charts here: - https://rollupjs.org/guide/en/#build-hooks - https://rollupjs.org/guide/en/#output-generation-hooks
Parameters
Name | Types | Description |
---|---|---|
options | { svelte_config: import('types').ValidatedConfig } |
Returns
Promise<import('vite').Plugin[]>
# manifest_data()
# plugin_compile()
# plugin_guard()
Ensures that client-side code can't accidentally import server-side code, whether in *.server.js
files, $app/server
, $lib/server
, or $env/[static|dynamic]/private
# plugin_setup()
# preprocess()
# server_manifest()
# value.type()
# vite_config()
# vite_config_env()
# vite_plugin_svelte_options()
# warn_overridden_config(config, resolved_config)
Parameters
Name | Types | Description |
---|---|---|
config | Record<string, any> |
|
resolved_config | Record<string, any> |
# warned()
# warning_preprocessor()
# writeBundle()
Vite builds a single bundle. We need three bundles: client, server, and service worker. The user's package.json scripts will invoke the Vite CLI to execute the server build. We then use this hook to kick off builds for the client and service worker.
# internal.js()
# preview(vite, vite_config, svelte_config)
Parameters
Name | Types | Description |
---|---|---|
vite | { middlewares: import('connect').Server } |
|
vite_config | import('vite').ResolvedConfig |
|
svelte_config | import('types').ValidatedConfig |
# redirect()
# alias()
# get_config_aliases(config)
Transforms kit.alias to a valid vite.resolve.alias array. Related to tsconfig path alias creation.
Parameters
Name | Types | Description |
---|---|---|
config | import('types').ValidatedKitConfig |
# get_env(env_config, mode)
Load environment variables from process.env and .env files
Parameters
Name | Types | Description |
---|---|---|
env_config | import('types').ValidatedKitConfig['env'] |
|
mode | string |
# building()
SvelteKit analyses your app during the build
step by running it. During this process, building
is true
. This also applies during prerendering.
# dev()
Whether the dev server is running. This is not guaranteed to correspond to NODE_ENV
or MODE
.
# deserialize(result)
Use this function to deserialize the response from a form submission. Usage: js import { deserialize } from '$app/forms'; async function handleSubmit(event) { const response = await fetch('/form?/action', { method: 'POST', body: new FormData(event.target) }); const result = deserialize(await response.text()); // ... }
Parameters
Name | Types | Description |
---|---|---|
result | string |
# enhance(form_element, submit)
This action enhances a <form>
element that otherwise would work without JavaScript. The submit
function is called upon submission with the given FormData and the action
that should be triggered. If cancel
is called, the form will not be submitted. You can use the abort controller
to cancel the submission in case another one starts. If a function is returned, that function is called with the response from the server. If nothing is returned, the fallback will be used. If this function or its return value isn't set, it - falls back to updating the form
prop with the returned data if the action is on the same page as the form - updates $page.status
- resets the <form>
element and invalidates all data in case of successful submission with no redirect response - redirects in case of a redirect response - redirects to the nearest error page in case of an unexpected error If you provide a custom function with a callback and want to use the default behavior, invoke update
in your callback.
Parameters
Name | Types | Description |
---|---|---|
form_element | HTMLFormElement |
The form element |
submit | import('@sveltejs/kit').SubmitFunction<Success, Failure> |
Submit callback |
# fallback_callback(opts)
Parameters
Name | Types | Description |
---|---|---|
opts | {action: URL;invalidateAll: boolean;result: import('@sveltejs/kit').ActionResult;reset?: boolean} |
# result()
# resolveRoute()
# assets()
An absolute path that matches config.kit.paths.assets
. > [!NOTE] If a value for config.kit.paths.assets
is specified, it will be replaced with '/_svelte_kit_assets'
during vite dev
or vite preview
, since the assets don't yet live at their eventual URL.
# base()
A string that matches config.kit.paths.base
. Example usage: <a href="{base}/your-page">Link</a>
# read(asset)
Read the contents of an imported asset from the filesystem
Parameters
Name | Types | Description |
---|---|---|
asset | string |
# getStores()
A function that returns all of the contextual stores. On the server, this must be called during component initialization. Only use this if you need to defer store subscription until after the component has mounted, for some reason.
# navigating()
# navigating()
A readable store. When navigating starts, its value is a Navigation
object with from
, to
, type
and (if type === 'popstate'
) delta
properties. When navigating finishes, its value reverts to null
. On the server, this store can only be subscribed to during component initialization. In the browser, it can be subscribed to at any time.
# page()
# page()
A readable store whose value contains page data. On the server, this store can only be subscribed to during component initialization. In the browser, it can be subscribed to at any time.
# stores.updated()
# updated()
A readable store whose initial value is false
. If version.pollInterval
is a non-zero value, SvelteKit will poll for new versions of the app and update the store value to true
when it detects one. updated.check()
will force an immediate check, regardless of polling. On the server, this store can only be subscribed to during component initialization. In the browser, it can be subscribed to at any time.
# _before_navigate(opts)
Parameters
Name | Types | Description |
---|---|---|
opts | {url: URL;type: import('@sveltejs/kit').Navigation["type"];intent: import('./types.js').NavigationIntent;delta?: number;} |
# _goto(url, options, redirect_count, nav_token)
Parameters
Name | Types | Description |
---|---|---|
url | string |
URL |
options | { replaceState: boolean; noScroll?: boolean; keepFocus?: boolean; invalidateAll?: boolean; state?: Record<string, any> } |
|
redirect_count | number |
|
nav_token | {} |
# _hydrate(target, opts)
Parameters
Name | Types | Description |
---|---|---|
target | HTMLElement |
|
opts | {status: number;error: App.Error |
null;node_ids: number[];params: Record<string, string>;route: { id: string |
# _preload_data(intent)
Parameters
Name | Types | Description |
---|---|---|
intent | import('./types.js').NavigationIntent |
# add_navigation_callback(callbacks, callback)
Parameters
Name | Types | Description |
---|---|---|
callbacks | T[] |
|
callback | T |
# after_navigate_callbacks()
# afterNavigate(callback)
A lifecycle function that runs the supplied callback
when the current component mounts, and also whenever we navigate to a new URL. afterNavigate
must be called during a component initialization. It remains active as long as the component is mounted.
Parameters
Name | Types | Description |
---|---|---|
callback | (navigation: import('@sveltejs/kit').AfterNavigate) => void |
# app()
# applyAction(result)
This action updates the form
property of the current page with the given data and updates $page.status
. In case of an error, it redirects to the nearest error page.
Parameters
Name | Types | Description |
---|---|---|
result | import('@sveltejs/kit').ActionResult<Success, Failure> |
# before_navigate_callbacks()
# beforeNavigate(callback)
A navigation interceptor that triggers before we navigate to a new URL, whether by clicking a link, calling goto(...)
, or using the browser back/forward controls. Calling cancel()
will prevent the navigation from completing. If navigation.type === 'leave'
— meaning the user is navigating away from the app (or closing the tab) — calling cancel
will trigger the native browser unload confirmation dialog. In this case, the navigation may or may not be cancelled depending on the user's response. When a navigation isn't to a SvelteKit-owned route (and therefore controlled by SvelteKit's client-side router), navigation.to.route.id
will be null
. If the navigation will (if not cancelled) cause the document to unload — in other words 'leave'
navigations and 'link'
navigations where navigation.to.route === null
— navigation.willUnload
is true
. beforeNavigate
must be called during a component initialization. It remains active as long as the component is mounted.
Parameters
Name | Types | Description |
---|---|---|
callback | (navigation: import('@sveltejs/kit').BeforeNavigate) => void |
# branch()
# branch()
# clear_onward_history(current_history_index, current_navigation_index)
Parameters
Name | Types | Description |
---|---|---|
current_history_index | number |
|
current_navigation_index | number |
# components()
An array of the +layout.svelte
and +page.svelte
component instances that currently live on the page — used for capturing and restoring snapshots. It's updated/manipulated through bind:this
in Root.svelte
.
# container()
# create_data_node(node, previous)
Parameters
Name | Types | Description |
---|---|---|
node | import('types').ServerDataNode |
import('types').ServerDataSkippedNode |
previous | import('./types.js').DataNode |
null |
# create_navigation(current, intent, url, type)
Parameters
Name | Types | Description |
---|---|---|
current | import('./types.js').NavigationState |
|
intent | import('./types.js').NavigationIntent |
undefined |
url | URL |
null |
type | Exclude<import('@sveltejs/kit').NavigationType, 'enter'> |
# current()
# current_history_index()
# current_navigation_index()
# data()
# default_error_loader()
# default_layout_loader()
# diff_search_params(old_url, new_url)
Parameters
Name | Types | Description |
---|---|---|
old_url | URL |
null |
new_url | URL |
# disableScrollHandling()
If called when the page is being updated following a navigation (in onMount
or afterNavigate
or an action, for example), this disables SvelteKit's built-in scroll handling. This is generally discouraged, since it breaks user expectations.
# fulfil()
# get_navigation_intent(url, invalidating)
Resolve the full info (which route, params, etc.) for a client-side navigation from the URL, taking the reroute hook into account. If this isn't a client-side-navigation (or the URL is undefined), returns undefined.
Parameters
Name | Types | Description |
---|---|---|
url | URL |
undefined |
invalidating | boolean |
# get_navigation_result_from_branch(opts)
Parameters
Name | Types | Description |
---|---|---|
opts | {url: URL;params: Record<string, string>;branch: Array<import('./types.js').BranchNode |
undefined>;status: number;error: App.Error |
# goto(url, opts, opts.replaceState, opts.noScroll, opts.keepFocus, opts.invalidateAll, opts.state)
Returns a Promise that resolves when SvelteKit navigates (or fails to navigate, in which case the promise rejects) to the specified url
. For external URLs, use window.location = url
instead of calling goto(url)
.
Parameters
Name | Types | Description |
---|---|---|
url | string |
URL |
opts | Object |
Options related to the navigation |
opts.replaceState | boolean |
If true , will replace the current history entry rather than creating a new one with pushState |
opts.noScroll | boolean |
If true , the browser will maintain its scroll position rather than scrolling to the top of the page after navigation |
opts.keepFocus | boolean |
If true , the currently focused element will retain focus after navigation. Otherwise, focus will be reset to the body |
opts.invalidateAll | boolean |
If true , all load functions of the page will be rerun. See https://svelte.dev/docs/kit/load#rerunning-load-functions for more info on invalidation. |
opts.state | App.PageState |
An optional object that will be available on the $page.state store |
# has_changed(parent_changed, route_changed, url_changed, search_params_changed, uses, params)
Parameters
Name | Types | Description |
---|---|---|
parent_changed | boolean |
|
route_changed | boolean |
|
url_changed | boolean |
|
search_params_changed | Set<string> |
|
uses | import('types').Uses |
undefined |
params | Record<string, string> |
# has_navigated()
True as soon as there happened one client-side navigation (excluding the SvelteKit-initialized initial one when in SPA mode)
# intent()
# invalidate(resource)
Causes any load
functions belonging to the currently active page to re-run if they depend on the url
in question, via fetch
or depends
. Returns a Promise
that resolves when the page is subsequently updated. If the argument is given as a string
or URL
, it must resolve to the same URL that was passed to fetch
or depends
(including query parameters). To create a custom identifier, use a string beginning with [a-z]+:
(e.g. custom:state
) — this is a valid URL. The function
argument can be used define a custom predicate. It receives the full URL
and causes load
to rerun if true
is returned. This can be useful if you want to invalidate based on a pattern instead of a exact match. ts // Example: Match '/path' regardless of the query parameters import { invalidate } from '$app/navigation'; invalidate((url) => url.pathname === '/path');
Parameters
Name | Types | Description |
---|---|---|
resource | string |
URL |
# invalidateAll()
Causes all load
functions belonging to the currently active page to re-run. Returns a Promise
that resolves when the page is subsequently updated.
# invalidated()
# load_cache()
# load_input()
# load_node(options)
Call the load function of the given node, if it exists. If server_data
is passed, this is treated as the initial run and the page endpoint is not requested.
Parameters
Name | Types | Description |
---|---|---|
options | {loader: import('types').CSRPageNodeLoader;parent: () => Promise<Record<string, any>>;url: URL;params: Record<string, string>;route: { id: string |
null };server_data_node: import('./types.js').DataNode |
# load_root_error_page(opts)
Parameters
Name | Types | Description |
---|---|---|
opts | {status: number;error: App.Error;url: URL;route: { id: string |
null }} |
# load_route(intent)
Parameters
Name | Types | Description |
---|---|---|
intent | import('./types.js').NavigationIntent & { preload: {} } |
# message()
# native_navigation(url)
Loads href
the old-fashioned way, with a full page reload. Returns a Promise
that never resolves (to prevent any subsequent work, e.g. history manipulation, from happening)
Parameters
Name | Types | Description |
---|---|---|
url | URL |
# navigate(opts)
Parameters
Name | Types | Description |
---|---|---|
opts | {type: import('@sveltejs/kit').Navigation["type"];url: URL;popped: {state: Record<string, any>;scroll: { x: number, y: number };delta: number;};keepfocus?: boolean;noscroll?: boolean;replace_state?: boolean;state?: Record<string, any>;redirect_count?: number;nav_token?: {};accept?: () => void;block?: () => void;} |
# navigation()
# navigation()
# navigation()
# on_navigate_callbacks()
# onNavigate(callback)
A lifecycle function that runs the supplied callback
immediately before we navigate to a new URL except during full-page navigations. If you return a Promise
, SvelteKit will wait for it to resolve before completing the navigation. This allows you to — for example — use document.startViewTransition
. Avoid promises that are slow to resolve, since navigation will appear stalled to the user. If a function (or a Promise
that resolves to a function) is returned from the callback, it will be called once the DOM has updated. onNavigate
must be called during a component initialization. It remains active as long as the component is mounted.
Parameters
Name | Types | Description |
---|---|---|
callback | (navigation: import('@sveltejs/kit').OnNavigate) => import('types').MaybePromise<(() => void) |
void> |
# page()
# params()
# pending_invalidate()
# preload_error(opts)
Parameters
Name | Types | Description |
---|---|---|
opts | Omit<import('./types.js').NavigationFinished['state'], 'branch'> & { error: App.Error } |
# preload_tokens()
A set of tokens which are associated to current preloads. If a preload becomes a real navigation, it's removed from the set. If a preload token is in the set and the preload errors, the error handling logic (for example reloading) is skipped.
# preloadCode(pathname)
Programmatically imports the code for routes that haven't yet been fetched. Typically, you might call this to speed up subsequent navigation. You can specify routes by any matching pathname such as /about
(to match src/routes/about/+page.svelte
) or /blog/*
(to match src/routes/blog/[slug]/+page.svelte
). Unlike preloadData
, this won't call load
functions. Returns a Promise that resolves when the modules have been imported.
Parameters
Name | Types | Description |
---|---|---|
pathname | string |
# preloadData(href)
Programmatically preloads the given page, which means 1. ensuring that the code for the page is loaded, and 2. calling the page's load function with the appropriate options. This is the same behaviour that SvelteKit triggers when the user taps or mouses over an <a>
element with data-sveltekit-preload-data
. If the next navigation is to href
, the values returned from load will be used, making navigation instantaneous. Returns a Promise that resolves with the result of running the new route's load
functions once the preload is complete.
Parameters
Name | Types | Description |
---|---|---|
href | string |
Page to preload |
# previous()
# pushState(url, state)
Programmatically create a new history entry with the given $page.state
. To use the current URL, you can pass ''
as the first argument. Used for shallow routing.
Parameters
Name | Types | Description |
---|---|---|
url | string |
URL |
state | App.PageState |
# ranges()
# reject()
# replaceState(url, state)
Programmatically replace the current history entry with the given $page.state
. To use the current URL, you can pass ''
as the first argument. Used for shallow routing.
Parameters
Name | Types | Description |
---|---|---|
url | string |
URL |
state | App.PageState |
# requested()
# result()
# result()
# root()
# root_error()
# routes()
# server_data()
# server_data_node()
# server_fallback(url, route, error, status)
Does a full page reload if it wouldn't result in an endless loop in the SPA case
Parameters
Name | Types | Description |
---|---|---|
url | URL |
|
route | { id: string |
null } |
error | App.Error |
|
status | number |
# set()
# slash()
# start(_app, _target, hydrate)
Parameters
Name | Types | Description |
---|---|---|
_app | import('./types.js').SvelteKitApp |
|
_target | HTMLElement |
|
hydrate | Parameters<typeof _hydrate>[1] |
# target()
# token()
# update_service_worker()
Checks whether a service worker is registered, and if it is, tries to update it.
# uses()
# build_selector(resource, opts)
Build the cache key for a given request
Parameters
Name | Types | Description |
---|---|---|
resource | URL |
RequestInfo |
opts | RequestInit |
# dev_fetch(resource, opts)
Parameters
Name | Types | Description |
---|---|---|
resource | RequestInfo |
URL |
opts | RequestInit & Record<string, any> |
undefined |
# initial_fetch(resource, opts)
Should be called on the initial run of load functions that hydrate the page. Saves any requests with cache-control max-age to the cache.
Parameters
Name | Types | Description |
---|---|---|
resource | URL |
string |
opts | RequestInit |
# subsequent_fetch(resource, resolved, opts)
Tries to get the response from the cache, if max-age allows it, else does a fetch.
Parameters
Name | Types | Description |
---|---|---|
resource | URL |
string |
resolved | string |
|
opts | RequestInit |
# values()
# get(key, parse)
Read a value from sessionStorage
Parameters
Name | Types | Description |
---|---|---|
key | string |
|
parse | (value: string) => any |
# set(key, value, stringify)
Write a value to sessionStorage
Parameters
Name | Types | Description |
---|---|---|
key | string |
|
value | any |
|
stringify | (value: any) => string |
# dictionary()
A map of [routeId: string]: [leaf, layouts, errors]
tuples, which is parsed into an array of routes on startup. The numbers refer to the indices in nodes
. If the leaf number is negative, it means it does use a server load function and the complement is the node index. The route layout and error nodes are not referenced, they are always number 0 and 1 and always apply.
# server_loads()
A list of all layout node ids that have a server load function. Pages are not present because it's shorter to encode it on the leaf itself.
# check()
# get_link_info(a, base)
Parameters
Name | Types | Description |
---|---|---|
a | HTMLAnchorElement |
SVGAElement |
base | string |
# get_router_options(element)
Parameters
Name | Types | Description |
---|---|---|
element | HTMLFormElement |
HTMLAnchorElement |
# keepfocus()
# noscroll()
# old_value()
# preload_code()
# preload_data()
# reload()
# replace_state()
# timeout()
# url()
# validate_link_option(element, name, value)
Parameters
Name | Types | Description |
---|---|---|
element | Element |
|
name | T |
|
value | U |
# ActionFailure()
# constructor(status, body)
Parameters
Name | Types | Description |
---|---|---|
status | number |
|
body | {message: string} extends App.Error (App.Error |
string |
# constructor(status, text, message)
Parameters
Name | Types | Description |
---|---|---|
status | number |
|
text | string |
|
message | string |
# replace_implementations(implementations)
This is a grotesque hack that, in dev, allows us to replace the implementations of these classes that you'd get by importing them from @sveltejs/kit
with the ones that are imported via Vite and loaded internally, so that instanceof checks work even though SvelteKit imports this module via Vite and consumers import it via Node
Parameters
Name | Types | Description |
---|---|---|
implementations | {ActionFailure: typeof ActionFailure;HttpError: typeof HttpError;Redirect: typeof Redirect;SvelteKitError: typeof SvelteKitError;} |
# SvelteKitError()
An error that was thrown from within the SvelteKit runtime that is not fatal and doesn't result in a 500, such as a 404. SvelteKitError
goes through handleError
.
# hash(values)
Hash using djb2
Parameters
Name | Types | Description |
---|---|---|
values | import('types').StrictBody[] |
# add_cookies_to_headers(headers, cookies)
Parameters
Name | Types | Description |
---|---|---|
headers | Headers |
|
cookies | import('./page/types.js').Cookie[] |
# combined_cookies()
# cookie_paths()
Tracks all cookies set during dev mode so we can emit warnings when we detect that there's likely cookie misusage due to wrong paths
# cookies()
# defaults()
# delete(name, options)
Parameters
Name | Types | Description |
---|---|---|
name | string |
|
options | import('./page/types.js').Cookie['options'] |
# domain_matches(hostname, constraint)
Parameters
Name | Types | Description |
---|---|---|
hostname | string |
|
constraint | string |
# get(name, opts)
Parameters
Name | Types | Description |
---|---|---|
name | string |
|
opts | import('cookie').CookieParseOptions |
# get_cookie_header(destination, header)
Parameters
Name | Types | Description |
---|---|---|
destination | URL |
|
header | string |
null |
# get_cookies(request, url, trailing_slash)
Parameters
Name | Types | Description |
---|---|---|
request | Request |
|
url | URL |
|
trailing_slash | import('types').TrailingSlash |
# MAX_COOKIE_SIZE()
Cookies that are larger than this size (including the name and other attributes) are discarded by browsers
# new_cookies()
# serialize(name, value, options)
Parameters
Name | Types | Description |
---|---|---|
name | string |
|
value | string |
|
options | import('./page/types.js').Cookie['options'] |
# set(name, value, options)
Parameters
Name | Types | Description |
---|---|---|
name | string |
|
value | string |
|
options | import('./page/types.js').Cookie['options'] |
# set_internal(name, value, options)
Parameters
Name | Types | Description |
---|---|---|
name | string |
|
value | string |
|
options | import('./page/types.js').Cookie['options'] |
# validate_options(options)
Parameters
Name | Types | Description |
---|---|---|
options | import('./page/types.js').Cookie['options'] |
# get_data_json(event, options, nodes)
If the serialized data contains promises, chunks
will be an async iterable containing their resolutions
Parameters
Name | Types | Description |
---|---|---|
event | import('@sveltejs/kit').RequestEvent |
|
options | import('types').SSROptions |
|
nodes | Array<import('types').ServerDataSkippedNode |
import('types').ServerDataNode |
# json_response(json, status)
Parameters
Name | Types | Description |
---|---|---|
json | Record<string, any> |
string |
status | number |
# is_endpoint_request(event)
Parameters
Name | Types | Description |
---|---|---|
event | import('@sveltejs/kit').RequestEvent |
# body()
# etag()
# headers()
# create_fetch(opts)
Parameters
Name | Types | Description |
---|---|---|
opts | {event: import('@sveltejs/kit').RequestEvent;options: import('types').SSROptions;manifest: import('@sveltejs/kit').SSRManifest;state: import('types').SSRState;get_cookie_header: (url: URL, header: string |
null) => string;set_internal: (name: string, value: string, opts: import('./page/types.js').Cookie['options']) => void;} |
# normalize_fetch_input(info, init, url)
Parameters
Name | Types | Description |
---|---|---|
info | RequestInfo |
URL |
init | RequestInit |
undefined |
url | URL |
# constructor(manifest)
Parameters
Name | Types | Description |
---|---|---|
manifest | import('@sveltejs/kit').SSRManifest |
# init(opts)
Parameters
Name | Types | Description |
---|---|---|
opts | {env: Record<string, string>;read: (file: string) => ReadableStream;} |
# prerender_env_handler()
# respond(request, options)
Parameters
Name | Types | Description |
---|---|---|
request | Request |
|
options | import('types').RequestOptions |
# action_json(data, init)
Parameters
Name | Types | Description |
---|---|---|
data | import('@sveltejs/kit').ActionResult |
|
init | ResponseInit |
# action_json_redirect(redirect)
Parameters
Name | Types | Description |
---|---|---|
redirect | import('@sveltejs/kit').Redirect |
# call_action(event, actions)
Parameters
Name | Types | Description |
---|---|---|
event | import('@sveltejs/kit').RequestEvent |
|
actions | NonNullable<import('types').SSRNode['server']['actions']> |
# check_named_default_separate(actions)
Parameters
Name | Types | Description |
---|---|---|
actions | import('@sveltejs/kit').Actions |
# handle_action_request(event, server)
Parameters
Name | Types | Description |
---|---|---|
event | import('@sveltejs/kit').RequestEvent |
|
server | import('types').SSRNode['server'] |
undefined |
# is_action_json_request(event)
Parameters
Name | Types | Description |
---|---|---|
event | import('@sveltejs/kit').RequestEvent |
# is_action_request(event)
Parameters
Name | Types | Description |
---|---|---|
event | import('@sveltejs/kit').RequestEvent |
# stringify_action_response(data, route_id)
Try to devalue.stringify
the data object, and if it fails, return a proper Error with context
Parameters
Name | Types | Description |
---|---|---|
data | any |
|
route_id | string |
# uneval_action_response(data, route_id)
Try to devalue.uneval
the data object, and if it fails, return a proper Error with context
Parameters
Name | Types | Description |
---|---|---|
data | any |
|
route_id | string |
# sha256(data)
SHA-256 hashing function adapted from https://bitwiseshiftleft.github.io/sjcl modified and redistributed under BSD license
Parameters
Name | Types | Description |
---|---|---|
data | string |
# constructor(config, opts)
Parameters
Name | Types | Description |
---|---|---|
config | import('./types.js').CspConfig |
|
opts | import('./types.js').CspOpts |
# generate_nonce()
# hes()
# hes(use_hashes, directives, nonce)
Parameters
Name | Types | Description |
---|---|---|
use_hashes | boolean |
|
directives | import('types').CspDirectives |
|
nonce | string |
# hes(use_hashes, directives, nonce)
Parameters
Name | Types | Description |
---|---|---|
use_hashes | boolean |
|
directives | import('types').CspDirectives |
|
nonce | string |
# needs_csp(directive)
Parameters
Name | Types | Description |
---|---|---|
directive | (import('types').Csp.Source |
import('types').Csp.ActionSource)[] |
# source()
# source()
# action_result()
# branch()
# fetched()
# load_error()
# server_promises()
# create_universal_fetch(event, state, fetched, csr, resolve_opts)
Parameters
Name | Types | Description |
---|---|---|
event | Pick<import('@sveltejs/kit').RequestEvent, 'fetch' |
'url' |
state | import('types').SSRState |
|
fetched | import('./types.js').Fetched[] |
|
csr | boolean |
|
resolve_opts | Pick<Required<import('@sveltejs/kit').ResolveOptions>, 'filterSerializedResponseHeaders'> |
# dependency()
# load_data(opts)
Calls the user's load
function.
Parameters
Name | Types | Description |
---|---|---|
opts | {event: import('@sveltejs/kit').RequestEvent;fetched: import('./types.js').Fetched[];node: import('types').SSRNode |
undefined;parent: () => Promise<Record<string, any>>;resolve_opts: import('types').RequiredResolveOptions;server_data_promise: Promise<import('types').ServerDataNode |
# load_server_data(opts)
Calls the user's server load
function.
Parameters
Name | Types | Description |
---|---|---|
opts | {event: import('@sveltejs/kit').RequestEvent;state: import('types').SSRState;node: import('types').SSRNode |
undefined;parent: () => Promise<Record<string, any>>;} |
# universal_fetch(input, init)
Parameters
Name | Types | Description |
---|---|---|
input | URL |
RequestInfo |
init | RequestInit |
# load_page_nodes(page, manifest)
Parameters
Name | Types | Description |
---|---|---|
page | import('types').PageNodeIndexes |
|
manifest | import('@sveltejs/kit').SSRManifest |
# assets()
# base()
# base_expression()
An expression that will evaluate in the client to determine the resolved base path. We use a relative path when possible to support IPFS, the internet archive, etc.
# get_data(event, options, nodes, csp, global)
If the serialized data contains promises, chunks
will be an async iterable containing their resolutions
Parameters
Name | Types | Description |
---|---|---|
event | import('@sveltejs/kit').RequestEvent |
|
options | import('types').SSROptions |
|
nodes | Array<import('types').ServerDataNode |
null> |
csp | import('./csp.js').Csp |
|
global | string |
# link_header_preloads()
# render_response(opts)
Creates the HTML response.
Parameters
Name | Types | Description |
---|---|---|
opts | {branch: Array<import('./types.js').Loaded>;fetched: Array<import('./types.js').Fetched>;options: import('types').SSROptions;manifest: import('@sveltejs/kit').SSRManifest;state: import('types').SSRState;page_config: { ssr: boolean; csr: boolean };status: number;error: App.Error |
null;event: import('@sveltejs/kit').RequestEvent;resolve_opts: import('types').RequiredResolveOptions;action_result: import('@sveltejs/kit').ActionResult;} |
# fetched()
# headers()
# replacements()
Inside a script element, only </script
and <!--
hold special meaning to the HTML parser. The first closes the script element, so everything after is treated as raw HTML. The second disables further parsing until -->
, so the script element might be unexpectedly kept open until until an unrelated HTML comment in the page. U+2028 LINE SEPARATOR and U+2029 PARAGRAPH SEPARATOR are escaped for the sake of pre-2018 browsers.
# serialize_data(fetched, filter, prerendering)
Generates a raw HTML string containing a safe script element carrying data and associated attributes. It escapes all the special characters needed to guarantee the element is unbroken, but care must be taken to ensure it is inserted in the document at an acceptable position for a script element, and that the resulting string isn't further modified.
Parameters
Name | Types | Description |
---|---|---|
fetched | import('./types.js').Fetched |
|
filter | (name: string, value: string) => boolean |
|
prerendering | boolean |
# values()
# cookies_to_add()
# default_filter()
# default_preload()
# default_transform()
# headers()
# invalidated_data_nodes()
# params()
# respond(request, options, manifest, state)
Parameters
Name | Types | Description |
---|---|---|
request | Request |
|
options | import('types').SSROptions |
|
manifest | import('@sveltejs/kit').SSRManifest |
|
state | import('types').SSRState |
# route()
# trailing_slash()
# allowed_methods(mod)
Parameters
Name | Types | Description |
---|---|---|
mod | Partial<Record<import('types').HttpMethod, any>> |
# clarify_devalue_error(event, error)
Parameters
Name | Types | Description |
---|---|---|
event | import('@sveltejs/kit').RequestEvent |
|
error | Error & { path: string } |
# handle_error_and_jsonify(event, options, error)
Parameters
Name | Types | Description |
---|---|---|
event | import('@sveltejs/kit').RequestEvent |
|
options | import('types').SSROptions |
|
error | any |
# handle_fatal_error(event, options, error)
Parameters
Name | Types | Description |
---|---|---|
event | import('@sveltejs/kit').RequestEvent |
|
options | import('types').SSROptions |
|
error | unknown |
# method_not_allowed(mod, method)
Parameters
Name | Types | Description |
---|---|---|
mod | Partial<Record<import('types').HttpMethod, any>> |
|
method | import('types').HttpMethod |
# redirect_response(status, location)
Parameters
Name | Types | Description |
---|---|---|
status | number |
|
location | string |
# static_error_page(options, status, message)
Return as a response that renders the error.html
Parameters
Name | Types | Description |
---|---|---|
options | import('types').SSROptions |
|
status | number |
|
message | string |
# safe_public_env()
The same as public_env
, but without the proxy. Use for %sveltekit.env.PUBLIC_FOO%
# set_private_env()
# set_public_env()
# set_safe_public_env()
# base()
The base
path of the deployment. Typically this is equivalent to config.kit.paths.base
, but it is calculated from location.pathname
meaning that it will continue to work correctly if the site is deployed to a subdirectory. Note that there is a base
but no assets
, since service workers cannot be used if config.kit.paths.assets
is specified.
# build()
An array of URL strings representing the files generated by Vite, suitable for caching with cache.addAll(build)
. During development, this is an empty array.
# files()
An array of URL strings representing the files in your static directory, or whatever directory is specified by config.kit.files.assets
. You can customize which files are included from static
directory using config.kit.serviceWorker.files
# prerendered()
An array of pathnames corresponding to prerendered pages and endpoints. During development, this is an empty array.
# version()
See config.kit.version
. It's useful for generating unique cache names inside your service worker, so that a later deployment of your app can invalidate old caches.
# __SVELTEKIT_TRACK__()
This makes the use of specific features visible at both dev and build time, in such a way that we can error when they are not supported by the target platform. During dev, globalThis.__SVELTEKIT_TRACK__
is a function that grabs the current event
and route config
(from an AsyncLocalStorage instance) and calls the relevant supports
function on the adapter (e.g. adapter.supports.read(...)
). At build time, if the function containing the __SVELTEKIT_TRACK__
call is untreeshaken, we locate it in the renderChunk
build hook and a) make a note of the chunk that contains it and b) replace it with a comment. Later, we can use this information to establish which routes use which feature, and use the same adapter.supports.read(...)
function to throw an error if the feature would fail in production.
# data()
The serialized version of this contains a serialized representation of any deferred promises, which will be resolved later through chunk nodes.
# kippedNode()
If null
, then there was no load function <- TODO is this outdated now with the recent changes?
# kippedNode()
Signals that the server load
function was not run, and the client should use what it has in memory
# complete()
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.
# filter()
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
# id()
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
# pages()
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
.
# paths()
An array of prerendered paths (without trailing slashes, regardless of the trailingSlash config)
# filter_private_env(env, prefixes)
Parameters
Name | Types | Description |
---|---|---|
env | Record<string, string> |
|
prefixes | {public_prefix: string;private_prefix: string;} |
# filter_public_env(env, prefixes)
Parameters
Name | Types | Description |
---|---|---|
env | Record<string, string> |
|
prefixes | {public_prefix: string;private_prefix: string;} |
# escape_html(str, is_attr)
Escapes unpaired surrogates (which are allowed in js strings but invalid in HTML) and escapes characters that are special.
Parameters
Name | Types | Description |
---|---|---|
str | string |
|
is_attr | boolean |
# escape_html_attr_dict()
When inside a double-quoted attribute value, only &
and "
hold special meaning.
# escape_html_dict()
# check_feature(route_id, config, feature, adapter)
Parameters
Name | Types | Description |
---|---|---|
route_id | string |
|
config | any |
|
feature | string |
|
adapter | import('@sveltejs/kit').Adapter |
undefined |
# all_files()
# copy(source, target, opts)
Parameters
Name | Types | Description |
---|---|---|
source | string |
|
target | string |
|
opts | {filter: (basename: string) => boolean;replace?: Record<string, string>;} |
# files()
# from_fs(str)
Removes /@fs
prefix from given path and posixifies it
Parameters
Name | Types | Description |
---|---|---|
str | string |
# join_relative(str)
Like path.join
, but posixified and with a leading ./
if necessary
Parameters
Name | Types | Description |
---|---|---|
str | string[] |
# relative_path(from, to)
Like path.relative
, but always posixified and with a leading ./
if necessary. Useful for JS imports so the path can safely reside inside of node_modules
. Otherwise paths could be falsely interpreted as package paths.
Parameters
Name | Types | Description |
---|---|---|
from | string |
|
to | string |
# resolve_entry(entry)
Given an entry point like [cwd]/src/hooks, returns a filename like [cwd]/src/hooks.js or [cwd]/src/hooks/index.js
Parameters
Name | Types | Description |
---|---|---|
entry | string |
# walk(cwd, dirs)
Get a list of all files in a directory
Parameters
Name | Types | Description |
---|---|---|
cwd | string |
- the directory to walk |
dirs | boolean |
- whether to include directories in the result |
# dest_dir()
# source_dir()
# result()
# is_content_type(request, types)
Returns true
if the request contains a content-type
header with the given type
Parameters
Name | Types | Description |
---|---|---|
request | Request |
|
types | ...string |
# negotiate(accept, types)
Given an Accept header and a list of possible content types, pick the most suitable one to respond with
Parameters
Name | Types | Description |
---|---|---|
accept | string |
|
types | string[] |
# parts()
# resolve_peer_dependency(dependency)
Resolve a dependency relative to the current working directory, rather than relative to this package
Parameters
Name | Types | Description |
---|---|---|
dependency | string |
# current()
# get_page_config(nodes)
Do a shallow merge (first level) of the config object
Parameters
Name | Types | Description |
---|---|---|
nodes | Array<import('types').SSRNode |
undefined> |
# affects_path(segment)
Returns false
for (group)
segments
Parameters
Name | Types | Description |
---|---|---|
segment | string |
# exec(match, params, matchers)
Parameters
Name | Types | Description |
---|---|---|
match | RegExpMatchArray |
|
params | import('types').RouteParam[] |
|
matchers | Record<string, import('@sveltejs/kit').ParamMatcher> |
# get_route_segments(route)
Splits a route id into its segments, removing segments that don't affect the path (i.e. groups). The root route is represented by /
and will be returned as ['']
.
Parameters
Name | Types | Description |
---|---|---|
route | string |
# parse_route_id(id)
Creates the regex pattern, extracts parameter names, and generates types for a route
Parameters
Name | Types | Description |
---|---|---|
id | string |
# remove_optional_params(id)
Removes optional params from a route ID.
Parameters
Name | Types | Description |
---|---|---|
id | string |
# resolve_route(id, params)
Populate a route ID with params to resolve a pathname.
Parameters
Name | Types | Description |
---|---|---|
id | string |
|
params | Record<string, string |
undefined> |
# result()
# defer()
# allow_nodejs_console_log(url)
Allow URL to be console logged, bypassing disabled properties.
Parameters
Name | Types | Description |
---|---|---|
url | URL |
# decode_pathname(pathname)
Decode pathname excluding %25 to prevent further double decoding of params
Parameters
Name | Types | Description |
---|---|---|
pathname | string |
# decode_uri(uri)
The error when a URL is malformed is not very helpful, so we augment it with the URI
Parameters
Name | Types | Description |
---|---|---|
uri | string |
# disable_hash(url)
Disallow access to url.hash
on the server and in load
Parameters
Name | Types | Description |
---|---|---|
url | URL |
# disable_search(url)
Disallow access to url.search
and url.searchParams
during prerendering
Parameters
Name | Types | Description |
---|---|---|
url | URL |
# make_trackable(url, callback, search_params_callback)
Parameters
Name | Types | Description |
---|---|---|
url | URL |
|
callback | () => void |
|
search_params_callback | (search_param: string) => void |
# normalize_path(path, trailing_slash)
Parameters
Name | Types | Description |
---|---|---|
path | string |
|
trailing_slash | import('types').TrailingSlash |
# strip_hash(url_like)
Returns everything up to the first #
in a URL
Parameters
Name | Types | Description |
---|---|---|
url_like | {href: string} |
# paths()
# props()
# VERSION()
# handle()
# load()
# GET()
# load()
# load()
# config()
# config()
# handleError()
# reroute()
# error_to_pojo(error)
Transform an error into a POJO, by copying its name
, message
and (in dev) stack
, plus any custom properties, plus recursively serialized cause
properties.
Parameters
Name | Types | Description |
---|---|---|
error | Error |
# handleFetch()
# load()
# load()
# load()
# actions()
# load()
# actions()
# actions()
# actions()
# actions()
# load()
# actions()
# load()
# load()
# load()
# load()
# load()
# GET()
# GET()
# load()
# GET()
# GET()
# load()
# load()
# load()
# GET()
# load()
# load()
# load()
# GET()
# POST()
# DELETE()
# load()
# load()
# load()
# load()
# PUT()
# OPTIONS()
# GET()
# GET()
# GET()
# HEAD()
# GET()
# GET()
# GET()
# GET()
# load()
# load()
# load()
# load()
# GET()
# load()
# load()
# load()
# load()
# load()
# actions()
# actions()
# foo()
# load()
# GET()
# headers()
# load()
# load()
# load()
# GET()
# load()
# load()
# load()
# load()
# load()
# load()
# load()
# load()
# load()
# GET()
# POST()
# GET()
# load()
# res.json()
# load()
# load()
# load()
# POST()
# GET()
# POST()
# load()
# load()
# load()
# GET()
# load()
# GET()
# load()
# load()
# load()
# load()
# load()
# load()
# load()
# load()
# load()
# load()
# load()
# load()
# GET()
# load()
# load()
# load()
# load()
# load()
# load()
# load()
# load()
# load()
# POST()
# load()
# load()
# load()
# load()
# load()
# POST()
# load()
# load()
# load()
# GET()
# GET()
# load()
# load()
# load()
# load()
# load()
# GET()
# GET()
# load()
# load()
# load()
# load()
# GET()
# load()
# load()
# load()
# load()
# load()
# values()
# external_glob()
# local_glob()
# GET()
# load()
# load()
# DELETE()
# GET()
# PATCH()
# POST()
# PUT()
# GET()
# load()
# load()
# load()
# GET()
# load()
# GET()
# load()
# load()
# load()
# load()
# load()
# actions()
# actions()
# actions()
# actions()
# load()
# GET()
# load()
# actions()
# actions()
# load()
# load()
# actions()
# GET()
# load()
# load()
# load()
# load()
# load()
# load()
# values()
# load()
# config()
# requests()
# requests()
# test.describe.configure()
# cookies()
# requests()
# requests()
# test.skip()
# config()
# handleError()
# reroute()
# config()
# test.describe.serial()
# config()
# load()
# config()
# test.describe.configure()
# config()
# config()
# test.skip()
# config()
# config()
# test.describe.configure()
# config()
# handle()
# load()
# config()
# requests()
# requests()
# test.describe.configure()
# config()
# config()
# test.describe.configure()
# config()
# entries()
# config()
# config()
# config()
# config()
# config()
# config()
# config()
# config()
# config()
# config()
# config()
# config()
# config()
# config()
# config()
# config()
# config()
# config()
# config()
# config()
# config()
# config()
# config()
# config()
# config()
# config()
# config()
# config()
# GithubFlakyWarningReporter()
# onTestEnd(test)
Parameters
Name | Types | Description |
---|---|---|
test |
|
{import('@playwright/test/reporter').TestCase} |
# handle()
# GET()
# load()
# load()
# load()
# load()
# load()
# load()
# load()
# load()
# load()
# load()
# load()
# load()
# load()
# actions()
# load()
# config()
# config()
# config()
# config()
# config()
# config()
# replace_hydration_attrs(html)
For static content, Svelte v4 will add a data-svelte-h attribute. Replace the hash with something predictable before comparing the output.
Parameters
Name | Types | Description |
---|---|---|
html | string |
# clicknav(selector, options)
Parameters
Name | Types | Description |
---|---|---|
selector | string |
|
options | { timeout: number } |
# config()
# page.evaluate()
# server()
# sockets()
# ...deps()
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. js /// file: src/routes/+page.js let count = 0; export async function load({ depends }) { depends('increase:count'); return { count: count++ }; }
html /// file: src/routes/+page.svelte <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>
# ...deps()
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. js /// file: src/routes/+page.js let count = 0; export async function load({ depends }) { depends('increase:count'); return { count: count++ }; }
html /// file: src/routes/+page.svelte <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>
# adapt(builder)
This function is called after SvelteKit has built your app.
Parameters
Name | Types | Description |
---|---|---|
builder |
|
An object provided by SvelteKit that contains methods for adapting the app |
# afterNavigate()
A lifecycle function that runs the supplied callback
when the current component mounts, and also whenever we navigate to a new URL. afterNavigate
must be called during a component initialization. It remains active as long as the component is mounted.
# App.PageData()
The merged result of all data from all load
functions on the current page. You can type a common denominator through App.PageData
.
# App.PageState()
The page state, which can be manipulated using the pushState
and replaceState
functions from $app/navigation
.
# App.Platform()
A function that is called with the current route config
and prerender
option and returns an App.Platform
object
# applyAction()
This action updates the form
property of the current page with the given data and updates $page.status
. In case of an error, it redirects to the nearest error page.
# assets()
An absolute path that matches config.kit.paths.assets
. > [!NOTE] If a value for config.kit.paths.assets
is specified, it will be replaced with '/_svelte_kit_assets'
during vite dev
or vite preview
, since the assets don't yet live at their eventual URL.
# base()
A string that matches config.kit.paths.base
. Example usage: <a href="{base}/your-page">Link</a>
# base()
The base
path of the deployment. Typically this is equivalent to config.kit.paths.base
, but it is calculated from location.pathname
meaning that it will continue to work correctly if the site is deployed to a subdirectory. Note that there is a base
but no assets
, since service workers cannot be used if config.kit.paths.assets
is specified.
# beforeNavigate()
A navigation interceptor that triggers before we navigate to a new URL, whether by clicking a link, calling goto(...)
, or using the browser back/forward controls. Calling cancel()
will prevent the navigation from completing. If navigation.type === 'leave'
— meaning the user is navigating away from the app (or closing the tab) — calling cancel
will trigger the native browser unload confirmation dialog. In this case, the navigation may or may not be cancelled depending on the user's response. When a navigation isn't to a SvelteKit-owned route (and therefore controlled by SvelteKit's client-side router), navigation.to.route.id
will be null
. If the navigation will (if not cancelled) cause the document to unload — in other words 'leave'
navigations and 'link'
navigations where navigation.to.route === null
— navigation.willUnload
is true
. beforeNavigate
must be called during a component initialization. It remains active as long as the component is mounted.
# build()
An array of URL strings representing the files generated by Vite, suitable for caching with cache.addAll(build)
. During development, this is an empty array.
# building()
SvelteKit analyses your app during the build
step by running it. During this process, building
is true
. This also applies during prerendering.
# complete()
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
# complete()
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.
# compress(directory)
Compress files in directory
with gzip and brotli, where appropriate. Generates .gz
and .br
files alongside the originals.
Parameters
Name | Types | Description |
---|---|---|
directory |
|
The directory containing the files to be compressed |
# config()
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.
# copy(from, to, opts.filter, opts.replace)
Copy a file or directory.
Parameters
Name | Types | Description |
---|---|---|
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 |
# createEntries(fn)
Create separate functions that map to one or more routes of your app.
Parameters
Name | Types | Description |
---|---|---|
fn |
|
A function that groups a set of routes into an entry point |
# data()
Contains the data returned by the route's server load
function (in +layout.server.js
or +page.server.js
), if any.
# delete(name, opts)
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
Parameters
Name | Types | Description |
---|---|---|
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 |
# deserialize()
Use this function to deserialize the response from a form submission. Usage: js import { deserialize } from '$app/forms'; async function handleSubmit(event) { const response = await fetch('/form?/action', { method: 'POST', body: new FormData(event.target) }); const result = deserialize(await response.text()); // ... }
# details(config)
Test support for read
from $app/server
Parameters
Name | Types | Description |
---|---|---|
config |
|
The merged route config |
# dev()
Whether the dev server is running. This is not guaranteed to correspond to NODE_ENV
or MODE
.
# disableScrollHandling()
If called when the page is being updated following a navigation (in onMount
or afterNavigate
or an action, for example), this disables SvelteKit's built-in scroll handling. This is generally discouraged, since it breaks user expectations.
# e()
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
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.
# enhance(form_element, submit)
This action enhances a <form>
element that otherwise would work without JavaScript. The submit
function is called upon submission with the given FormData and the action
that should be triggered. If cancel
is called, the form will not be submitted. You can use the abort controller
to cancel the submission in case another one starts. If a function is returned, that function is called with the response from the server. If nothing is returned, the fallback will be used. If this function or its return value isn't set, it - falls back to updating the form
prop with the returned data if the action is on the same page as the form - updates $page.status
- resets the <form>
element and invalidates all data in case of successful submission with no redirect response - redirects in case of a redirect response - redirects to the nearest error page in case of an unexpected error If you provide a custom function with a callback and want to use the default behavior, invoke update
in your callback.
Parameters
Name | Types | Description |
---|---|---|
form_element |
|
The form element |
submit |
|
Submit callback |
# error(status, body)
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.
Parameters
Name | Types | Description |
---|---|---|
status |
|
The HTTP status code. Must be in the range 400-599. |
body |
|
An object that conforms to the App.Error type. If a string is passed, it will be used as the message property. |
# error(status, body)
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.
Parameters
Name | Types | Description |
---|---|---|
status |
|
The HTTP status code. Must be in the range 400-599. |
body |
|
An object that conforms to the App.Error type. If a string is passed, it will be used as the message property. |
# event()
The reroute
hook allows you to modify the URL before it is used to determine which route to render.
# fail(status)
Create an ActionFailure
object.
Parameters
Name | Types | Description |
---|---|---|
status |
|
The HTTP status code. Must be in the range 400-599. |
# fail(status, data)
Create an ActionFailure
object.
Parameters
Name | Types | Description |
---|---|---|
status |
|
The HTTP status code. Must be in the range 400-599. |
data |
|
Data associated with the failure (e.g. validation errors) |
# 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
# 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
# file()
A function that turns an asset filename into a ReadableStream
. Required for the read
export from $app/server
to work
# filepath()
Determine which files in your static
directory will be available in $service-worker.files
.
# files()
An array of URL strings representing the files in your static directory, or whatever directory is specified by config.kit.files.assets
. You can customize which files are included from static
directory using config.kit.serviceWorker.files
# filter()
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
# fn()
Use this function to opt out of dependency tracking for everything that is synchronously called within the callback. Example: js /// file: src/routes/+page.server.js export async function load({ untrack, url }) { // Untrack url.pathname so that path changes don't trigger a rerun if (untrack(() => url.pathname === '/')) { return { message: 'Welcome!' }; } }
# fn()
Use this function to opt out of dependency tracking for everything that is synchronously called within the callback. Example: js /// file: src/routes/+page.js export async function load({ untrack, url }) { // Untrack url.pathname so that path changes don't trigger a rerun if (untrack(() => url.pathname === '/')) { return { message: 'Welcome!' }; } }
# generateEnvModule()
Generate a module exposing build-time environment variables as $env/dynamic/public
.
# generateFallback()
Generate a fallback page for a static webserver to use when no route is matched. Useful for single-page apps.
# generateManifest(opts)
Generate a server-side manifest to initialise the SvelteKit server with.
Parameters
Name | Types | Description |
---|---|---|
opts |
|
a relative path to the base directory of the app and optionally in which format (esm or cjs) the manifest should be generated |
# get(name, opts)
Gets a cookie that was previously set with cookies.set
, or from the request headers.
Parameters
Name | Types | Description |
---|---|---|
name |
|
the name of the cookie |
opts |
|
the options, passed directly to cookie.parse . See documentation here |
# getAll(opts)
Gets all cookies that were previously set with cookies.set
, or from the request headers.
Parameters
Name | Types | Description |
---|---|---|
opts |
|
the options, passed directly to cookie.parse . See documentation here |
# getBuildDirectory(name)
Resolve a path to the name
directory inside outDir
, e.g. /path/to/.svelte-kit/my-adapter
.
Parameters
Name | Types | Description |
---|---|---|
name |
|
path to the file, relative to the build directory |
# getClientDirectory()
Get the fully resolved path to the directory containing client-side assets, including the contents of your static
directory.
# goto(url, opts)
Returns a Promise that resolves when SvelteKit navigates (or fails to navigate, in which case the promise rejects) to the specified url
. For external URLs, use window.location = url
instead of calling goto(url)
.
Parameters
Name | Types | Description |
---|---|---|
url |
|
Where to navigate to. Note that if you've set config.kit.paths.base and the URL is root-relative, you need to prepend the base path if you want to navigate within the app. |
opts | Object |
Options related to the navigation |
# h()
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.
# http()
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.
# id()
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
# input()
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).
# input()
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.
# input()
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.
# input()
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)
# input(input)
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.
Parameters
Name | Types | Description |
---|---|---|
input |
|
the html chunk and the info if this is the last chunk |
# input(input)
Determines what should be added to the <head>
tag to preload it. By default, js
and css
files will be preloaded.
Parameters
Name | Types | Description |
---|---|---|
input |
|
the type of the file and its path |
# invalidate(resource)
Causes any load
functions belonging to the currently active page to re-run if they depend on the url
in question, via fetch
or depends
. Returns a Promise
that resolves when the page is subsequently updated. If the argument is given as a string
or URL
, it must resolve to the same URL that was passed to fetch
or depends
(including query parameters). To create a custom identifier, use a string beginning with [a-z]+:
(e.g. custom:state
) — this is a valid URL. The function
argument can be used define a custom predicate. It receives the full URL
and causes load
to rerun if true
is returned. This can be useful if you want to invalidate based on a pattern instead of a exact match. ts // Example: Match '/path' regardless of the query parameters import { invalidate } from '$app/navigation'; invalidate((url) => url.pathname === '/path');
Parameters
Name | Types | Description |
---|---|---|
resource |
|
The invalidated URL |
# invalidateAll()
Causes all load
functions belonging to the currently active page to re-run. Returns a Promise
that resolves when the page is subsequently updated.
# isActionFailure(e)
Checks whether this is an action failure thrown by {@link fail}.
Parameters
Name | Types | Description |
---|---|---|
e |
|
The object to check. |
# isDataRequest()
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.
# isHttpError(status)
Checks whether this is an error thrown by {@link error}.
Parameters
Name | Types | Description |
---|---|---|
status |
|
The status to filter for. |
# isRedirect(e)
Checks whether this is a redirect thrown by {@link redirect}.
Parameters
Name | Types | Description |
---|---|---|
e |
|
The object to check. |
# isSubRequest()
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.
# json(data, init)
Create a JSON Response
object from the supplied data.
Parameters
Name | Types | Description |
---|---|---|
data |
|
The value that will be serialized as JSON. |
init |
|
Options such as status and headers that will be added to the response. Content-Type: application/json and Content-Length headers will be added automatically. |
# log()
Print messages to the console. log.info
and log.minor
are silent unless Vite's logLevel
is info
.
# name(name, 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.
Parameters
Name | Types | Description |
---|---|---|
name |
|
header name |
value |
|
header value |
# navigating()
A readable store. When navigating starts, its value is a Navigation
object with from
, to
, type
and (if type === 'popstate'
) delta
properties. When navigating finishes, its value reverts to null
. On the server, this store can only be subscribed to during component initialization. In the browser, it can be subscribed to at any time.
# onNavigate()
A lifecycle function that runs the supplied callback
immediately before we navigate to a new URL except during full-page navigations. If you return a Promise
, SvelteKit will wait for it to resolve before completing the navigation. This allows you to — for example — use document.startViewTransition
. Avoid promises that are slow to resolve, since navigation will appear stalled to the user. If a function (or a Promise
that resolves to a function) is returned from the callback, it will be called once the DOM has updated. onNavigate
must be called during a component initialization. It remains active as long as the component is mounted.
# page()
A readable store whose value contains page data. On the server, this store can only be subscribed to during component initialization. In the browser, it can be subscribed to at any time.
# pages()
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
.
# params()
The parameters of the current page - e.g. for a route like /blog/[slug]
, a { slug: string }
object
# params()
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).
# params()
The parameters of the current page - e.g. for a route like /blog/[slug]
, a { slug: string }
object
# params()
The parameters of the current route - e.g. for a route like /blog/[slug]
, a { slug: string }
object
# parent()
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.
# parent()
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.
# paths()
An array of prerendered paths (without trailing slashes, regardless of the trailingSlash config)
# preloadCode()
Programmatically imports the code for routes that haven't yet been fetched. Typically, you might call this to speed up subsequent navigation. You can specify routes by any matching pathname such as /about
(to match src/routes/about/+page.svelte
) or /blog/*
(to match src/routes/blog/[slug]/+page.svelte
). Unlike preloadData
, this won't call load
functions. Returns a Promise that resolves when the modules have been imported.
# preloadData(href)
Programmatically preloads the given page, which means 1. ensuring that the code for the page is loaded, and 2. calling the page's load function with the appropriate options. This is the same behaviour that SvelteKit triggers when the user taps or mouses over an <a>
element with data-sveltekit-preload-data
. If the next navigation is to href
, the values returned from load will be used, making navigation instantaneous. Returns a Promise that resolves with the result of running the new route's load
functions once the preload is complete.
Parameters
Name | Types | Description |
---|---|---|
href |
|
Page to preload |
# prerendered()
An array of pathnames corresponding to prerendered pages and endpoints. During development, this is an empty array.
# pushState()
Programmatically create a new history entry with the given $page.state
. To use the current URL, you can pass ''
as the first argument. Used for shallow routing.
# redirect(status, location)
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.
Parameters
Name | Types | Description |
---|---|---|
status |
|
The HTTP status code. Must be in the range 300-308. |
location |
|
The location to redirect to. |
# replaceState()
Programmatically replace the current history entry with the given $page.state
. To use the current URL, you can pass ''
as the first argument. Used for shallow routing.
# sequence(handlers)
A helper function for sequencing multiple handle
calls in a middleware-like manner. The behavior for the handle
options is as follows: - transformPageChunk
is applied in reverse order and merged - preload
is applied in forward order, the first option "wins" and no preload
options after it are called - filterSerializedResponseHeaders
behaves the same as preload
js /// file: src/hooks.server.js import { sequence } from '@sveltejs/kit/hooks'; /// type: import('@sveltejs/kit').Handle async function first({ event, resolve }) { console.log('first pre-processing'); const result = await resolve(event, { transformPageChunk: ({ html }) => { // transforms are applied in reverse order console.log('first transform'); return html; }, preload: () => { // this one wins as it's the first defined in the chain console.log('first preload'); return true; } }); console.log('first post-processing'); return result; } /// type: import('@sveltejs/kit').Handle async function second({ event, resolve }) { console.log('second pre-processing'); const result = await resolve(event, { transformPageChunk: ({ html }) => { console.log('second transform'); return html; }, preload: () => { console.log('second preload'); return true; }, filterSerializedResponseHeaders: () => { // this one wins as it's the first defined in the chain console.log('second filterSerializedResponseHeaders'); return true; } }); console.log('second post-processing'); return result; } export const handle = sequence(first, second);
The example above would print: first pre-processing first preload second pre-processing second filterSerializedResponseHeaders second transform first transform second post-processing first post-processing
Parameters
Name | Types | Description |
---|---|---|
handlers |
|
The chain of handle functions |
# serialize(name, value, opts)
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
Parameters
Name | Types | Description |
---|---|---|
name |
|
the name of the cookie |
value |
|
the cookie value |
opts |
|
the options, passed directly to cookie.serialize . See documentation here |
# set(name, value, opts)
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
Parameters
Name | Types | Description |
---|---|---|
name |
|
the name of the cookie |
value |
|
the cookie value |
opts |
|
the options, passed directly to cookie.serialize . See documentation here |
# setHeaders()
If you need to set headers for the response, you can do so using the this method. This is useful if you want the page to be cached, for example: js /// file: src/routes/blog/+page.js export async function load({ fetch, setHeaders }) { const url = `https://cms.example.com/articles.json`; const response = await fetch(url); setHeaders({ age: response.headers.get('age'), 'cache-control': response.headers.get('cache-control') }); return response.json(); }
Setting the same header multiple times (even in separate load
functions) is an error — you can only set a given header once. You cannot add a set-cookie
header with setHeaders
— use the cookies
API in a server-only load
function instead. setHeaders
has no effect when a load
function runs in the browser.
# setHeaders()
If you need to set headers for the response, you can do so using the this method. This is useful if you want the page to be cached, for example: js /// file: src/routes/blog/+page.js export async function load({ fetch, setHeaders }) { const url = `https://cms.example.com/articles.json`; const response = await fetch(url); setHeaders({ age: response.headers.get('age'), 'cache-control': response.headers.get('cache-control') }); return response.json(); }
Setting the same header multiple times (even in separate load
functions) is an error — you can only set a given header once. You cannot add a set-cookie
header with setHeaders
— use the cookies
API instead.
# text(body, init)
Create a Response
object from the supplied body.
Parameters
Name | Types | Description |
---|---|---|
body |
|
The value that will be used as-is. |
init |
|
Options such as status and headers that will be added to the response. A Content-Length header will be added automatically. |
# type()
The type of navigation: - 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
# type()
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
# type()
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
# update(options, invalidateAll)
Call this to get the default behavior of a form submission response.
Parameters
Name | Types | Description |
---|---|---|
options |
|
Set reset: false if you don't want the <form> values to be reset after a successful submission. |
invalidateAll |
|
Set invalidateAll: false if you don't want the action to call invalidateAll after submission. |
# updated()
A readable store whose initial value is false
. If version.pollInterval
is a non-zero value, SvelteKit will poll for new versions of the app and update the store value to true
when it detects one. updated.check()
will force an immediate check, regardless of polling. On the server, this store can only be subscribed to during component initialization. In the browser, it can be subscribed to at any time.
# version()
See config.kit.version
. It's useful for generating unique cache names inside your service worker, so that a later deployment of your app can invalidate old caches.
# willUnload()
Whether or not the navigation will result in the page being unloaded (i.e. not a client-side navigation)
# willUnload()
Since onNavigate
callbacks are called immediately before a client-side navigation, they will never be called with a navigation that unloads the page.
# willUnload()
Since afterNavigate
callbacks are called after a navigation completes, they will never be called with a navigation that unloads the page.
# writeClient(dest)
Write client assets to dest
.
Parameters
Name | Types | Description |
---|---|---|
dest |
|
the destination folder |
# writePrerendered(dest)
Write prerendered files to dest
.
Parameters
Name | Types | Description |
---|---|---|
dest |
|
the destination folder |
# writeServer(dest)
Write server-side code to dest
.
Parameters
Name | Types | Description |
---|---|---|
dest |
|
the destination folder |
# options()
# load_config(options)
Loads and validates svelte.config.js
Parameters
Name | Types | Description |
---|---|---|
options | { cwd: string } |
# all_files()
# copy(source, target, opts)
Parameters
Name | Types | Description |
---|---|---|
source | string |
|
target | string |
|
opts | {filter: (basename: string) => boolean;replace?: Record<string, string>;} |
# files()
# walk(cwd, dirs)
Get a list of all files in a directory
Parameters
Name | Types | Description |
---|---|---|
cwd | string |
- the directory to walk |
dirs | boolean |
- whether to include directories in the result |
# do_build(options, analyse_code)
Parameters
Name | Types | Description |
---|---|---|
options | import('./types.js').Options |
|
analyse_code | (name: string, code: string) => void |
# fulfillers()
# pending()
# process_file(input, output, file, preprocessor, aliases, tsconfig, analyse_code)
Parameters
Name | Types | Description |
---|---|---|
input | string |
|
output | string |
|
file | import('./types.js').File |
|
preprocessor | import('svelte/types/compiler/preprocess').PreprocessorGroup |
undefined |
aliases | Record<string, string> |
|
tsconfig | string |
undefined |
analyse_code | (name: string, code: string) => void |
# timeout()
# emit_dts(input, output, cwd, alias, files, tsconfig)
Generates d.ts files by invoking TypeScript's "emit d.ts files from input files". The files are written to a temporary location and those which should be kept are sanitized ($lib alias resolved) and copied over to the destination folder.
Parameters
Name | Types | Description |
---|---|---|
input | string |
|
output | string |
|
cwd | string |
|
alias | Record<string, string> |
|
files | import('./types.js').File[] |
|
tsconfig | string |
undefined |
# load_tsconfig(tsconfig, filename, ts)
Parameters
Name | Types | Description |
---|---|---|
tsconfig | string |
undefined |
filename | string |
|
ts | import('typescript') |
# transpile_ts(tsconfig, filename, source)
TS -> JS
Parameters
Name | Types | Description |
---|---|---|
tsconfig | string |
undefined |
filename | string |
|
source | string |
# replace_import_path(match, _, import_path)
Parameters
Name | Types | Description |
---|---|---|
match | string |
|
_ | string |
|
import_path | string |
# resolve_aliases(input, file, content, aliases)
Resolves aliases
Parameters
Name | Types | Description |
---|---|---|
input | string |
|
file | string |
Relative to the input |
content | string |
|
aliases | Record<string, string> |
# strip_lang_tags(content)
Strip out lang="X" or type="text/X" tags. Doing it here is only a temporary solution. See https://github.com/sveltejs/kit/issues/2450 for ideas for places where it's handled better.
Parameters
Name | Types | Description |
---|---|---|
content | string |
# write(file, contents)
Parameters
Name | Types | Description |
---|---|---|
file | string |
|
contents | Parameters<typeof fs.writeFileSync>[1] |
# analyse_code(name, content)
Checks a file content for problematic imports and things like import.meta
Parameters
Name | Types | Description |
---|---|---|
name | string |
|
content | string |
# analyse_code(name, content)
Checks a file content for problematic imports and things like import.meta
Parameters
Name | Types | Description |
---|---|---|
name | string |
|
content | string |
# conditions()
# exports()
# imports()
# pkg()
# traverse(exports_map, is_first_level)
Parameters
Name | Types | Description |
---|---|---|
exports_map | Record<string, any> |
|
is_first_level | boolean |
# warnings()
# format(file, content)
Format with Prettier in order to get expected and actual content aligned
Parameters
Name | Types | Description |
---|---|---|
file | string |
|
content | string |
# has_warnings(actual, expected)
Parameters
Name | Types | Description |
---|---|---|
actual | string[] |
|
expected | string[] |
# test_make_package(path, options)
Parameters
Name | Types | Description |
---|---|---|
path | string |
|
options | Partial<import('../src/types.js').Options> |