kit-monorepo (main) doxdox documentation

monorepo for @sveltejs/kit and friends

# commands()

# default()

# get_adapter()

# import_from_cwd(name)

Parameters

Name Types Description
name string

# module()

# fetch(req, env, context)

Parameters

Name Types Description
req Request
env any
context any

# get_asset_from_kv(req, env, context)

Parameters

Name Types Description
req Request
env any
context any

# is_error(status)

Parameters

Name Types Description
status number

# res()

# developers.cloudflare.com()

# validate_config(builder, config_file)

Parameters

Name Types Description
builder import('@sveltejs/kit').Builder
config_file string

# generate_headers(app_dir)

Parameters

Name Types Description
app_dir 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

# matches(a, b)

Parameters

Name Types Description
a RouteSegment[]
b RouteSegment[]

# name()

# config()

# handler(request, context)

Parameters

Name Types Description
request Request
context any

# is_static_file(request)

Parameters

Name Types Description
request Request

# h()

# m()

# split_headers(headers)

Splits headers into two categories: single value and multi value

Parameters

Name Types Description
headers Headers

# init(manifest)

Parameters

Name Types Description
manifest import('@sveltejs/kit').SSRManifest

# 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()

# env(name, fallback)

Parameters

Name Types Description
name string
fallback any

# get_origin(headers)

Parameters

Name Types Description
headers import('http').IncomingHttpHeaders

# handle(i)

Parameters

Name Types Description
i number

# return()

# sequence(handlers)

Parameters

Name Types Description
handlers import('polka').Middleware[]

# serve(path, client)

Parameters

Name Types Description
path string
client boolean

# 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= cookie. Making a 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('.').ServerlessConfig

# functions()

# generate_edge_function(name, config, routes)

Parameters

Name Types Description
name string
config import('.').EdgeConfig
routes import('@sveltejs/kit').RouteDefinition<import('.').EdgeConfig>[]

# generate_serverless_function()

# groups()

# hash_config(config)

Parameters

Name Types Description
config import('.').EdgeConfig & import('.').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('.').Config
dir string

# unmatched_paths()

# valid_routes()

For a route to be considered 'valid', it must be an API route with a GET handler

# write(file, data)

Parameters

Name Types Description
file string
data string

# 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

# transform(html)

Parameters

Name Types Description
html string

# create()

# matches_condition(condition, options)

Parameters

Name Types Description
condition import('./types/internal.js').Condition
options import('./types/internal.js').Options

# merge(target, source)

Parameters

Name Types Description
target any
source any

# sort_files(files)

Sort files so that those which apply more generically come first so they can be overwritten by files for more precise cases later.

Parameters

Name Types Description
files import('./types/internal.js').Common['files']

# sort_keys(obj)

Parameters

Name Types Description
obj Record<string, any>

# sorted()

# to_valid_package_name(name)

Parameters

Name Types Description
name string

# convert_typescript(content)

Parameters

Name Types Description
content string

# exclude()

# files()

# generate_templates(shared)

Parameters

Name Types Description
shared Set<string>

# include()

# replace_async(string, regexp, replacer)

Parameters

Name Types Description
string string
regexp RegExp
replacer { (m: any, attrs: string, typescript: string): Promise<string>; (arg0: any): any; }

# shared()

# strip_jsdoc(content)

Parameters

Name Types Description
content string

# config()

# config()

# config()

# config()

# config()

# config()

# actions()

# game.answers()

An array of strings like '__x_c' corresponding to the guesses, where 'x' means an exact match, and 'c' means a close match (right letter, wrong place)

# game.answers.length()

The correct answer, revealed if the game is over

# game.guesses()

The player's guessed words so far

# load()

# update()

Modify game state in reaction to a keypress. If client-side JavaScript is available, this will happen in the browser instead of here

# enter(letters)

Update game state based on a guess of a five-letter word. Returns true if the guess was valid, false otherwise

Parameters

Name Types Description
letters string[]

# toString()

Serialize game state so it can be set as a cookie

# set_reduced_motion(event)

Parameters

Name Types Description
event MediaQueryListEvent

# allowed()

The list of valid guesses, of which the list of possible words is a subset

# words()

The list of possible words

# config()

# config()

# config()

# patch_package_json(pkg)

Parameters

Name Types Description
pkg any

# resolve_path(path)

Resolve the given path relative to the current file

Parameters

Name Types Description
path string

# create(cwd, options)

Create a new SvelteKit project.

Parameters

Name Types Description
cwd string - Path to the directory to create
options import('./internal').Options

# copy(from, to, rename)

Parameters

Name Types Description
from string
to string
rename (basename: string) => string

# dist(path)

Parameters

Name Types Description
path string

# get_package_manager()

Supports npm, pnpm, Yarn, cnpm, bun and any other package manager that sets the npm_config_user_agent env variable. Thanks to https://github.com/zkochan/packages/tree/main/which-pm-runs for this code!

# identity(x)

Parameters

Name Types Description
x T

# mkdirp(dir)

Parameters

Name Types Description
dir string

# package_manager()

# rimraf(path)

Parameters

Name Types Description
path string

# enhancedImages()

# fallback()

# get_widths(width, sizes)

Parameters

Name Types Description
width number
sizes string null

# 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()

# 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/types/compiler/interfaces').TemplateNode
src_var_name string

# enter(node)

Parameters

Name Types Description
node import('svelte/types/compiler/interfaces').TemplateNode

# image(opts)

Parameters

Name Types Description
opts {plugin_context: import('vite').Rollup.PluginContextvite_config: import('vite').ResolvedConfigimagetools_plugin: import('vite').Plugin}

# images()

URL to image details

# img_attributes_to_markdown(content, attributes, details)

Parameters

Name Types Description
content string
attributes Array<import('svelte/types/compiler/interfaces').BaseDirective import('svelte/types/compiler/interfaces').Attribute
details {src: string,width: string number,height: string

# img_to_picture(content, node, image)

Parameters

Name Types Description
content string
node import('svelte/types/compiler/interfaces').TemplateNode
image import('vite-imagetools').Picture

# imports()

# is_quote(content, index)

Parameters

Name Types Description
content string
index number

# parseObject(str)

Parameters

Name Types Description
str string

# process(resolved_id, opts)

Parameters

Name Types Description
resolved_id string
opts {plugin_context: import('vite').Rollup.PluginContextimagetools_plugin: import('vite').Plugin}

# stringToNumber(param)

Parameters

Name Types Description
param string number

# update_element(node, src_attribute)

Parameters

Name Types Description
node import('svelte/types/compiler/interfaces').TemplateNode
src_attribute { type: string, start: number, end: number, raw: string }

# user_height()

# user_width()

# handle_error(e)

Parameters

Name Types Description
e unknown

# 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

# compress_file(file, format)

Parameters

Name Types Description
file string
format 'gz' 'br'

# 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

# process_config(config)

Parameters

Name Types Description
config import('@sveltejs/kit').Config

# validate_config(config)

Parameters

Name Types Description
config import('@sveltejs/kit').Config

# 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']

# assert_string(input, keypath)

Parameters

Name Types Description
input string
keypath string

# boolean(fallback)

Parameters

Name Types Description
fallback boolean

# directives()

# fun(fallback)

Parameters

Name Types Description
fallback (...args: any) => any

# list(options)

Parameters

Name Types Description
options string[]

# number(fallback)

Parameters

Name Types Description
fallback number

# 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

# string_array(fallback)

Parameters

Name Types Description
fallback string[] undefined

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

# create_static_types(id, env)

Parameters

Name Types Description
id EnvType
env import('types').Env

# declarations()

# add_assets(id)

Parameters

Name Types Description
id string

# 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[];}

# get_nodes(indexes)

Parameters

Name Types Description
indexes Array<number undefined>

# 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()

# visit(id)

Parameters

Name Types Description
id string

# attributes()

# crawl(html, base)

Parameters

Name Types Description
html string
base string

# hrefs()

# ids()

# decode(str)

Parameters

Name Types Description
str string

# 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()

# 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()

# output_filename(path, is_html)

Parameters

Name Types Description
path string
is_html boolean

# 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

# add(fn)

Parameters

Name Types Description
fn () => any

# fulfil()

# queue(concurrency)

Parameters

Name Types Description
concurrency number

# reject()

# tasks()

# fulfils()

# sleep(ms)

Parameters

Name Types Description
ms number

# 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_assets(config)

Parameters

Name Types Description
config import('types').ValidatedConfig

# 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()

# normalize_route_id(id)

Parameters

Name Types Description
id string

# prevent_conflicts(routes)

Parameters

Name Types Description
routes import('types').RouteData[]

# route()

# routes()

# walk(depth, id, segment, parent)

Parameters

Name Types Description
depth number
id string
segment string
parent import('types').RouteData null

# simplified()

# simplify_node(node)

Parameters

Name Types Description
node import('types').PageNode

# simplify_route(route)

Parameters

Name Types Description
route import('types').RouteData

# EMPTY()

# get_parts(segment)

Parameters

Name Types Description
segment string

# parts()

# segment_cache()

# sort_routes(routes)

Parameters

Name Types Description
routes import('types').RouteData[]

# sort_static(a, b)

Sort two strings lexicographically, except foobar outranks foo

Parameters

Name Types Description
a string
b string

# split(id)

Parameters

Name Types Description
id string

# split_route_id(id)

Parameters

Name Types Description
id 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()

# write(file, code)

Parameters

Name Types Description
file string
code string

# write_if_changed(file, code)

Parameters

Name Types Description
file string
code string

# read_description(filename)

Parameters

Name Types Description
filename string

# 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

# relative(file)

Parameters

Name Types Description
file 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

# config_relative(file)

Parameters

Name Types Description
file string

# config_relative(file)

Parameters

Name Types Description
file 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

# load_user_tsconfig(cwd)

Parameters

Name Types Description
cwd string

# maybe_file(cwd, file)

Parameters

Name Types Description
cwd string
file string

# paths()

# project_relative(file)

Parameters

Name Types Description
file string

# remove_trailing_slashstar(file)

Parameters

Name Types Description
file string

# 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_matcher(matcher)

Parameters

Name Types Description
matcher string

# 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_ext_with_js(file_path)

Parameters

Name Types Description
file_path string

# 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()

# c(param)

Parameters

Name Types Description
param Parameters<import('./$types').Action>[0]

# load()

test

# load()

test

# load()

# load(event)

Parameters

Name Types Description
event Parameters<import('./$types').Get>[0]

# load()

# load(event)

Parameters

Name Types Description
event Parameters<import('./$types').Get>[0]

# load()

# load(event)

Parameters

Name Types Description
event Parameters<import('./$types').Get>[0]

# 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()

# match(param)

Parameters

Name Types Description
param string

# match(param)

Parameters

Name Types Description
param string

# 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()

# err(msg)

Parameters

Name Types Description
msg string

# 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()

# logger(opts)

Parameters

Name Types Description
opts { verbose: boolean }

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

# walk(current)

Parameters

Name Types Description
current string

# 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'); } }); 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'); }, filterSerializedResponseHeaders: () => { // this one wins as it's the first defined in the chain console.log('second filterSerializedResponseHeaders'); } }); 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

# 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()

# installPolyfills()

Make various web APIs available as globals: - crypto - File

# ...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 invalidated 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'; export let data; 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 invalidated 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'; export let data; const increase = async () => { await invalidate('increase:count'); } </script> <p>{data.count}<p> <button on:click={increase}>Increase Count</button>

# _()

private fields

# 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.Error()

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

# App.Error()

The content of the error.

# App.Locals()

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

# 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

# App.Platform()

Additional data made available through the adapter.

# cancel()

Call this to prevent the navigation from starting.

# 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()

The fully resolved svelte.config.js.

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

# cookies()

Get or set cookies related to the current request

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

# env()

A map of environment variables

# 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!' }; } }

# form()

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

# from()

Where navigation was triggered from

# 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

# getAppPath()

Get the application path including any configured base path, e.g. my-base-path/_app.

# 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

# getClientAddress()

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

# getClientDirectory()

Get the fully resolved path to the directory containing client-side assets, including the contents of your static directory.

# getServerDirectory()

Get the fully resolved path to the directory containing server-side code.

# 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()

The ID of the current route - e.g. for src/routes/blog/[slug], it would be /blog/[slug]

# id()

The ID of the current route - e.g. for src/routes/blog/[slug], it would be /blog/[slug]

# id()

The ID of the current route - e.g. for src/routes/blog/[slug], it would be /blog/[slug]

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

# key()

Any additional options required by tooling that integrates with Svelte.

# location()

The location to redirect to.

# log()

Print messages to the console. log.info and log.minor are silent unless Vite's logLevel is info.

# mkdirp()

Create dir and any required parent directories.

# name()

The name of the adapter, using for logging. Will typically correspond to the package name.

# 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

# param()

The shape of a param matcher. See matching for more info.

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

# prerendered()

Information about prerendered pages and assets, if any.

# request()

The original request object

# rimraf()

Remove dir and all its contents.

# route()

Info about the current route

# route()

Info about the target route

# route()

Info about the current route

# route()

Info about the current route

# routes()

An array of all routes (including prerendered)

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

# sets()

Find all the assets imported by server files belonging to routes

# sets()

A [file]: size map of all assets imported by server code

# status()

Http status code of the current page

# status()

The HTTP status code, in the range 400-599.

# status()

The HTTP status code, in the range 300-308.

# to()

Where navigation is going to/has gone to

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

# url()

The URL of the current page

# url()

The URL that is navigated to

# url()

The URL of the current page

# url()

The requested URL.

# 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()

# assets_base(config)

Parameters

Name Types Description
config import('types').ValidatedKitConfig

# 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()

# is_http_method(str)

Parameters

Name Types Description
str string

# resolve_symlinks(manifest, file)

Parameters

Name Types Description
manifest import('vite').Manifest
file string

# seen()

# stylesheets()

# traverse(current, add_js)

Parameters

Name Types Description
current string
add_js boolean

# add(node)

Parameters

Name Types Description
node import('vite').ModuleNode

# add_by_url(url)

Parameters

Name Types Description
url string

# branches()

# debounce(to_run)

Parameters

Name Types Description
to_run () => void

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

# error_template(opts)

Parameters

Name Types Description
opts { status: number; message: string }

# find_deps(vite, node, deps)

Parameters

Name Types Description
vite import('vite').ViteDevServer
node import('vite').ModuleNode
deps Set<import('vite').ModuleNode>

# fix_stack_trace(error)

Parameters

Name Types Description
error Error

# 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

# loud_ssr_load_module(url)

Parameters

Name Types Description
url string

# manifest()

# manifest_data()

# manifest_error()

# matchers()

# remove_static_middlewares(server)

Parameters

Name Types Description
server import('connect').Server

# result()

# styles()

# timeout()

# watch(event, cb)

Parameters

Name Types Description
event string
cb (file: string) => void

# check(id)

Parameters

Name Types Description
id string should be posixified

# 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()

# getModuleInfo(id)

Parameters

Name Types Description
id string

# remove_query_from_id(path)

Parameters

Name Types Description
path string

# buildStart()

Clears the output directories.

# closeBundle()

Runs the adapter.

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

# configResolved()

Stores the final config.

# configurePreviewServer()

Adds the SvelteKit middleware to do SSR in preview mode.

# configureServer()

Adds the SvelteKit middleware to do SSR in dev mode.

# 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

# 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()

# plugin_virtual_modules()

# preprocess()

# 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

# server_manifest()

# set_assets(path)

Parameters

Name Types Description
path string

# sveltekit()

Returns the SvelteKit Vite plugins.

# 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()

# is_file(path)

Parameters

Name Types Description
path string

# mutable(dir)

Parameters

Name Types Description
dir string

# 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()

# scoped(scope, handler)

Parameters

Name Types Description
scope string
handler Handler

# alias()

# escape_for_regexp(str)

Parameters

Name Types Description
str string

# 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

# browser()

true if the app is running in the browser.

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

# version()

The value of config.kit.version.name.

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

# resolveRoute()

Populate a route ID with params to resolve a pathname.

# read(asset)

Read the contents of an imported asset from the filesystem

Parameters

Name Types Description
asset string

# get_store(name)

Parameters

Name Types Description
name Name

# 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_code(pathname)

Parameters

Name Types Description
pathname 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 === nullnavigation.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()

# capture_snapshot(index)

Parameters

Name Types Description
index number

# 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()

# depends(deps)

Parameters

Name Types Description
deps string[]

# deserialize_uses(uses)

Parameters

Name Types Description
uses any

Returns

import('types').Uses

# 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

# get_url_path(pathname)

Parameters

Name Types Description
pathname string

# 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://kit.svelte.dev/docs/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)

# hydrated()

this being true means we SSR'd

# 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_data(url, invalid)

Parameters

Name Types Description
url URL
invalid boolean[]

# 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(element, priority)

Parameters

Name Types Description
element Element
priority number

# 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()

# restore_snapshot(index)

Parameters

Name Types Description
index number

# result()

# result()

# root()

# root_error()

# routes()

# scroll_positions()

history index -> { x, y }

# 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]

# tap(event)

Parameters

Name Types Description
event Event

# target()

# token()

# update_scroll_positions(index)

Parameters

Name Types Description
index number

# update_url(url)

Parameters

Name Types Description
url URL

# 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()

# create_layout_loader(id)

Parameters

Name Types Description
id number undefined

# create_leaf_loader(id)

Parameters

Name Types Description
id number

# exec(path)

Parameters

Name Types Description
path string

# parse(app)

Parameters

Name Types Description
app import('./types.js').SvelteKitApp

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

# id()

url.pathname + url.search

# invalidating()

Whether we are invalidating or navigating

# nodes()

A list of all the error/layout/page nodes used in the app

# params()

The route parameters

# route()

The route that matches path

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

# url()

The destination URL

# check()

# get_link_info(a, base)

Parameters

Name Types Description
a HTMLAnchorElement SVGAElement
base string

# get_option_state(value)

Parameters

Name Types Description
value string null

# get_router_options(element)

Parameters

Name Types Description
element HTMLFormElement HTMLAnchorElement

# is_external_url(url, base)

Parameters

Name Types Description
url URL
base string

# keepfocus()

# noscroll()

# notifiable_store(value)

Parameters

Name Types Description
value any

# old_value()

# preload_code()

# preload_data()

# reload()

# replace_state()

# resolve_url(url)

Parameters

Name Types Description
url string URL

# set(new_value)

Parameters

Name Types Description
new_value any

# subscribe(run)

Parameters

Name Types Description
run (value: any) => void

# 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, location)

Parameters

Name Types Description
status 300 301
location string

# constructor(status, text, message)

Parameters

Name Types Description
status number
text string
message string

# constructor(status, data)

Parameters

Name Types Description
status number
data T

# 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()

# conjoin(array)

Parameters

Name Types Description
array string[]

# 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

# getAll(opts)

Parameters

Name Types Description
opts import('cookie').CookieParseOptions

# MAX_COOKIE_SIZE()

Cookies that are larger than this size (including the name and other attributes) are discarded by browsers

# new_cookies()

# path_matches(path, constraint)

Parameters

Name Types Description
path string
constraint string

# 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

# Promise(thing)

Parameters

Name Types Description
thing any

# redirect_json_response(redirect)

Parameters

Name Types Description
redirect Redirect

# is_endpoint_request(event)

Parameters

Name Types Description
event import('@sveltejs/kit').RequestEvent

# body()

# etag()

# get_public_env(request)

Parameters

Name Types Description
request Request

# 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

# response()

# 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_incorrect_fail_use(error)

Parameters

Name Types Description
error HttpError Error

# 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

# validate_action_return(data)

Parameters

Name Types Description
data any

# base64(bytes)

Parameters

Name Types Description
bytes Uint8Array

# encode(str)

Parameters

Name Types Description
str string

# frac(x)

Parameters

Name Types Description
x number

# init()

The SHA-256 initialization vector

# key()

The SHA-256 hash key

# precompute()

Function to precompute init and key.

# reverse_endianness(bytes)

Parameters

Name Types Description
bytes Uint8Array

# 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

# add_script(content)

Parameters

Name Types Description
content string

# add_script(content)

Parameters

Name Types Description
content string

# add_style(content)

Parameters

Name Types Description
content string

# add_style(content)

Parameters

Name Types Description
content 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

# action_result()

# branch()

# fetched()

# load_error()

# MAX_DEPTH()

The maximum request depth permitted before assuming we're stuck in an infinite loop

# server_promises()

# ...deps(deps)

Parameters

Name Types Description
deps string[]

# 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>>;}

# stream_to_string(stream)

Parameters

Name Types Description
stream ReadableStream<Uint8Array>

# universal_fetch(input, init)

Parameters

Name Types Description
input URL RequestInfo
init RequestInit

# validate_load_response(data, id)

Parameters

Name Types Description
data any
id string

# 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, 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>
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()

# url()

URL but stripped from the potential /__data.json suffix and its search param

# 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

# is_pojo(body)

Parameters

Name Types Description
body any

# 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

# stringify_uses(node)

Parameters

Name Types Description
node import('types').ServerDataNode

# warn_with_callsite(message, offset)

Parameters

Name Types Description
message string
offset number

# fix_stack_trace(error)

Parameters

Name Types Description
error any

# private_env()

$env/dynamic/private

# public_env()

$env/dynamic/public. When prerendering, this will be a proxy that forbids reads

# safe_public_env()

The same as public_env, but without the proxy. Use for %sveltekit.env.PUBLIC_FOO%

# set_fix_stack_trace(value)

Parameters

Name Types Description
value (error: Error) => string

# set_private_env()

# set_public_env()

# set_safe_public_env()

# validate_depends(route_id, dep)

Parameters

Name Types Description
route_id string
dep string

# b64_decode(text)

Parameters

Name Types Description
text string

# b64_encode(buffer)

Parameters

Name Types Description
buffer ArrayBuffer

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

# depth()

Allows us to prevent event.fetch from making infinitely looping internal requests

# error()

True if we're currently attempting to render an error page

# event()

A hook called before handle during dev, so that AsyncLocalStorage can be populated

# fonts()

external font files

# imports()

external JS files

# index()

index into the components array in client/manifest.js

# 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

# stylesheets()

external CSS files

# assets()

A map of path to { type } objects.

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

# file()

The location of the .html file relative to the output directory

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

# redirects()

A map of redirects encountered during prerendering.

# type()

The MIME type of the asset

# compact(arr)

Removes nullish values from an array.

Parameters

Name Types Description
arr Array<T>

# 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;}

# get_message(error)

Parameters

Name Types Description
error unknown

# get_status(error)

Parameters

Name Types Description
error unknown

# escape_html_attr(str)

Formats a string to be used as an attribute's value in raw HTML. It escapes unpaired surrogates (which are allowed in js strings but invalid in HTML), escapes characters that are special in attributes, and surrounds the whole string in double-quotes.

Parameters

Name Types Description
str string

# escape_html_attr_dict()

When inside a double-quoted attribute value, only & and " hold special meaning.

# hint_for_supported_files(key, ext)

Parameters

Name Types Description
key string
ext string

# validate(module, file)

Parameters

Name Types Description
module any
file string

# validator(expected)

Parameters

Name Types Description
expected Set<string>

# 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[]

# mkdirp(dir)

Parameters

Name Types Description
dir string

# posixify(str)

Parameters

Name Types Description
str string

# read(file)

Parameters

Name Types Description
file 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

# rimraf(path)

Parameters

Name Types Description
path string

# to_fs(str)

Prepend given path with /@fs prefix

Parameters

Name Types Description
str 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

# walk_dir(dir)

Parameters

Name Types Description
dir string

# dest_dir()

# source_dir()

# write(file, contents)

Parameters

Name Types Description
file string
contents string

# once(fn)

Parameters

Name Types Description
fn () => T

# 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

# is_form_content_type(request)

Parameters

Name Types Description
request Request

# 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()

# 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

# escape(str)

Parameters

Name Types Description
str 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()

# create_async_iterator()

Create an async iterator and a function to push values into it

# defer()

# add_data_suffix(pathname)

Parameters

Name Types Description
pathname string

# allow_nodejs_console_log(url)

Allow URL to be console logged, bypassing disabled properties.

Parameters

Name Types Description
url URL

# decode_params(params)

Parameters

Name Types Description
params Record<string, string>

# 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

# has_data_suffix(pathname)

Parameters

Name Types Description
pathname string

# is_root_relative(path)

Parameters

Name Types Description
path string

# 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

# resolve(base, path)

Parameters

Name Types Description
base string
path string

# SCHEME()

Matches a URI scheme. See https://www.rfc-editor.org/rfc/rfc3986#section-3.1

# strip_data_suffix(pathname)

Parameters

Name Types Description
pathname string

# 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()

# 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()

# 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(body)

Parameters

Name Types Description
body string

# POST()

# load()

# post(body)

Parameters

Name Types Description
body string

# load()

# load()

# GET()

# GET()

# load()

# load()

# load()

# load()

# load()

# GET()

# GET()

# load()

# load()

# load()

# load()

# GET()

# load()

# load()

# load()

# load()

# load()

# to_pojo(query)

Parameters

Name Types Description
query URLSearchParams

# values()

# 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()

# to_pojo(query)

Parameters

Name Types Description
query URLSearchParams

# 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()

# read(file)

Parameters

Name Types Description
file string

# config()

# config()

# read(file)

Parameters

Name Types Description
file string

# config()

# config()

# read(file)

Parameters

Name Types Description
file string

# 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

# read_errors()

handleError defines the shape

# ...urls(urls)

Parameters

Name Types Description
urls string[]

# beforeNavigate(fn)

Parameters

Name Types Description
fn (url: URL) => void boolean

# clicknav(selector, options)

Parameters

Name Types Description
selector string
options { timeout: number }

# config()

# get_computed_style(selector, prop)

Parameters

Name Types Description
selector string
prop string

# goto(url, opts)

Parameters

Name Types Description
url string
opts { replaceState: boolean }

# in_view(selector)

Parameters

Name Types Description
selector string

# page.evaluate(url)

Parameters

Name Types Description
url string

# page.evaluate()

# page.evaluate(url)

Parameters

Name Types Description
url string

# read_errors(path)

Parameters

Name Types Description
path string

# 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 invalidated 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'; export let data; 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 invalidated 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'; export let data; const increase = async () => { await invalidate('increase:count'); } </script> <p>{data.count}<p> <button on:click={increase}>Increase Count</button>

# _()

private fields

# 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.Error()

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

# App.Error()

The content of the error.

# App.Locals()

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

# 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

# App.Platform()

Additional data made available through the adapter.

# 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()

A map of path to { type } objects.

# assets()

An absolute path that matches config.kit.paths.assets. > 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 === nullnavigation.willUnload is true. beforeNavigate must be called during a component initialization. It remains active as long as the component is mounted.

# browser()

true if the app is running in the browser.

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

# cancel()

Call this to prevent the navigation from starting.

# 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()

The fully resolved svelte.config.js.

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

# cookies()

Get or set cookies related to the current request

# 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

# createReadableStream()

Converts a file on disk to a readable stream

# 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 one 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

# env()

A map of environment variables

# 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

# file()

The location of the .html file relative to the output directory

# 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!' }; } }

# fonts()

external font files

# form()

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

# from()

Where navigation was triggered from

# 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

# getAppPath()

Get the application path including any configured base path, e.g. my-base-path/_app.

# 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

# getClientAddress()

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

# getClientDirectory()

Get the fully resolved path to the directory containing client-side assets, including the contents of your static directory.

# getServerDirectory()

Get the fully resolved path to the directory containing server-side code.

# 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()

The ID of the current route - e.g. for src/routes/blog/[slug], it would be /blog/[slug]

# id()

The ID of the current route - e.g. for src/routes/blog/[slug], it would be /blog/[slug]

# id()

The ID of the current route - e.g. for src/routes/blog/[slug], it would be /blog/[slug]

# 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

# imports()

external JS files

# index()

index into the components array in client/manifest.js

# 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

# installPolyfills()

Make various web APIs available as globals: - crypto - File

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

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

# key()

Any additional options required by tooling that integrates with Svelte.

# location()

The location to redirect to.

# log()

Print messages to the console. log.info and log.minor are silent unless Vite's logLevel is info.

# mkdirp()

Create dir and any required parent directories.

# name()

The name of the adapter, using for logging. Will typically correspond to the package name.

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

# param()

The shape of a param matcher. See matching for more info.

# 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()

Information about prerendered pages and assets, if any.

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

# read()

Read the contents of an imported asset from the filesystem

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

# redirects()

A map of redirects encountered during prerendering.

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

# request()

The original request object

# resolveRoute()

Populate a route ID with params to resolve a pathname.

# rimraf()

Remove dir and all its contents.

# route()

Info about the current route

# route()

Info about the target route

# route()

Info about the current route

# route()

Info about the current route

# routes()

An array of all routes (including prerendered)

# 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 h