Modules
Edit this page on GitHubSvelteKit makes a number of modules available to your application.
$app/environment permalink
tsbrowser ,dev ,building ,version } from '$app/environment';
browser permalink
true if the app is running in the browser.
ts
dev permalink
Whether the dev server is running. This is not guaranteed to correspond to NODE_ENV or MODE.
ts
building permalink
SvelteKit analyses your app during the build step by running it. During this process, building is true. This also applies during prerendering.
ts
version permalink
The value of config.kit.version.name.
ts
$app/forms permalink
tsapplyAction ,deserialize ,enhance } from '$app/forms';
applyAction permalink
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.
ts
deserialize permalink
Use this function to deserialize the response from a form submission. Usage:
tsdeserialize } from '$app/forms';async functionhandleSubmit (event ) {constresponse = awaitfetch ('/form?/action', {method : 'POST',body : newFormData (event .target )});constresult =deserialize (awaitresponse .text ());// ...}
ts
enhance permalink
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 formprop 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.
ts
$app/navigation permalink
tsafterNavigate ,beforeNavigate ,disableScrollHandling ,goto ,invalidate ,invalidateAll ,preloadCode ,preloadData } from '$app/navigation';
afterNavigate permalink
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.
ts
beforeNavigate permalink
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 the navigation would have directly unloaded the current page, calling cancel will trigger the native
browser unload confirmation dialog. In these cases, navigation.willUnload is true.
When a navigation isn't client side, navigation.to.route.id will be null.
beforeNavigate must be called during a component initialization. It remains active as long as the component is mounted.
ts
disableScrollHandling permalink
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.
ts
goto permalink
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).
ts
invalidate permalink
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.
tsinvalidate } from '$app/navigation';invalidate ((url ) =>url .pathname === '/path');
ts
invalidateAll permalink
Causes all load functions belonging to the currently active page to re-run. Returns a Promise that resolves when the page is subsequently updated.
ts
preloadCode permalink
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.
ts
preloadData permalink
Programmatically preloads the given page, which means
- ensuring that the code for the page is loaded, and
- 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 when the preload is complete.
ts
$app/paths permalink
tsassets ,base } from '$app/paths';
assets permalink
An absolute path that matches config.kit.paths.assets.
If a value for
config.kit.paths.assetsis specified, it will be replaced with'/_svelte_kit_assets'duringvite devorvite preview, since the assets don't yet live at their eventual URL.
ts
base permalink
A string that matches config.kit.paths.base.
Example usage: <a href="{base}/your-page">Link</a>
ts
$app/stores permalink
tsgetStores ,navigating ,page ,updated } from '$app/stores';
getStores permalink
ts
navigating permalink
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.
ts
page permalink
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.
ts
updated permalink
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.
ts
$env/dynamic/private permalink
This module provides access to runtime environment variables, as defined by the platform you're running on. For example if you're using adapter-node (or running vite preview), this is equivalent to process.env. This module only includes variables that do not begin with config.kit.env.publicPrefix.
This module cannot be imported into client-side code.
tsenv } from '$env/dynamic/private';console .log (env .DEPLOYMENT_SPECIFIC_VARIABLE );
In
dev,$env/dynamicalways includes environment variables from.env. Inprod, this behavior will depend on your adapter.
$env/dynamic/public permalink
Similar to $env/dynamic/private, but only includes variables that begin with config.kit.env.publicPrefix (which defaults to PUBLIC_), and can therefore safely be exposed to client-side code.
Note that public dynamic environment variables must all be sent from the server to the client, causing larger network requests — when possible, use $env/static/public instead.
tsenv } from '$env/dynamic/public';console .log (env .PUBLIC_DEPLOYMENT_SPECIFIC_VARIABLE );
$env/static/private permalink
Environment variables loaded by Vite from .env files and process.env. Like $env/dynamic/private, this module cannot be imported into client-side code. This module only includes variables that do not begin with config.kit.env.publicPrefix.
Unlike $env/dynamic/private, the values exported from this module are statically injected into your bundle at build time, enabling optimisations like dead code elimination.
tsAPI_KEY } from '$env/static/private';
Note that all environment variables referenced in your code should be declared (for example in an .env file), even if they don't have a value until the app is deployed:
MY_FEATURE_FLAG=""You can override .env values from the command line like so:
MY_FEATURE_FLAG="enabled" npm run dev$env/static/public permalink
Similar to $env/static/private, except that it only includes environment variables that begin with config.kit.env.publicPrefix (which defaults to PUBLIC_), and can therefore safely be exposed to client-side code.
Values are replaced statically at build time.
tsPUBLIC_BASE_URL } from '$env/static/public';
$lib permalink
This is a simple alias to src/lib, or whatever directory is specified as config.kit.files.lib. It allows you to access common components and utility modules without ../../../../ nonsense.
$lib/server
				permalink
A subdirectory of $lib. SvelteKit will prevent you from importing any modules in $lib/server into client-side code. See server-only modules.
$service-worker permalink
tsbase ,build ,files ,prerendered ,version } from '$service-worker';
This module is only available to service workers.
base permalink
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.
ts
build permalink
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.
ts
files permalink
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
ts
prerendered permalink
An array of pathnames corresponding to prerendered pages and endpoints. During development, this is an empty array.
ts
version permalink
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.
ts
@sveltejs/kit permalink
tserror ,fail ,json ,redirect ,resolvePath ,text } from '@sveltejs/kit';
error permalink
error permalink
ts
fail permalink
Create an ActionFailure object.
ts
json permalink
Create a JSON Response object from the supplied data.
ts
redirect permalink
Create a Redirect object. If thrown 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.
ts
resolvePath permalink
Populate a route ID with params to resolve a pathname.
ts
text permalink
Create a Response object from the supplied body.
ts
@sveltejs/kit/hooks permalink
tssequence } from '@sveltejs/kit/hooks';
sequence permalink
A helper function for sequencing multiple handle calls in a middleware-like manner.
The behavior for the handle options is as follows:
- transformPageChunkis applied in reverse order and merged
- preloadis applied in forward order, the first option "wins" and no- preloadoptions after it are called
- filterSerializedResponseHeadersbehaves the same as- preload
tssequence } from '@sveltejs/kit/hooks';Binding element 'html' implicitly has an 'any' type.7031Binding element 'html' implicitly has an 'any' type.async functionfirst ({event ,resolve }) {console .log ('first pre-processing');constresult = awaitresolve (event , {transformPageChunk : ({html }) => {// transforms are applied in reverse orderconsole .log ('first transform');returnhtml ;},preload : () => {// this one wins as it's the first defined in the chainconsole .log ('first preload');}});Binding element 'event' implicitly has an 'any' type.Binding element 'resolve' implicitly has an 'any' type.7031console .log ('first post-processing'); 
7031Binding element 'event' implicitly has an 'any' type.Binding element 'resolve' implicitly has an 'any' type.returnresult ;}Binding element 'html' implicitly has an 'any' type.7031Binding element 'html' implicitly has an 'any' type.async functionsecond ({event ,resolve }) {console .log ('second pre-processing');constresult = awaitresolve (event , {transformPageChunk : ({html }) => {console .log ('second transform');returnhtml ;},preload : () => {console .log ('second preload');},filterSerializedResponseHeaders : () => {// this one wins as it's the first defined in the chainconsole .log ('second filterSerializedResponseHeaders');}});console .log ('second post-processing');returnresult ;}export consthandle =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-processingts
@sveltejs/kit/node permalink
tsgetRequest ,setResponse } from '@sveltejs/kit/node';
getRequest permalink
ts
setResponse permalink
ts
@sveltejs/kit/node/polyfills permalink
tsinstallPolyfills } from '@sveltejs/kit/node/polyfills';
installPolyfills permalink
Make various web APIs available as globals:
- crypto
- fetch
- Headers
- Request
- Response
ts
@sveltejs/kit/vite permalink
tssveltekit } from '@sveltejs/kit/vite';
sveltekit permalink
Returns the SvelteKit Vite plugins.
ts