Modules
Edit this page on GitHubSvelteKit makes a number of modules available to your application.
$app/envpermalink
ts
import {amp ,browser ,dev ,mode ,prerendering } from '$app/env';
amp
istrue
orfalse
depending on the corresponding value in your project configurationbrowser
istrue
orfalse
depending on whether the app is running in the browser or on the serverdev
istrue
in development mode,false
in productionmode
is the Vite mode, which isdevelopment
in dev mode orproduction
during build unless configured otherwise inconfig.kit.vite.mode
.prerendering
istrue
when prerendering,false
otherwise
$app/navigationpermalink
ts
import {afterNavigate ,beforeNavigate ,disableScrollHandling ,goto ,invalidate ,prefetch ,prefetchRoutes } from '$app/navigation';
afterNavigate(({ from, to }: { from: URL, to: URL }) => void)
- a lifecycle function that runs when the components mounts, and after subsequent navigations while the component remains mountedbeforeNavigate(({ from, to, cancel }: { from: URL, to: URL | null, cancel: () => void }) => void)
— a function that runs whenever navigation is triggered whether by clicking a link, callinggoto
, or using the browser back/forward controls. This includes navigation to external sites.to
will benull
if the user is closing the page. Callingcancel
will prevent the navigation from proceedingdisableScrollHandling
will, if called when the page is being updated following a navigation (inonMount
or an action, for example), prevent SvelteKit from applying its normal scroll management. You should generally avoid this, as breaking user expectations of scroll behaviour can be disorienting.goto(href, { replaceState, noscroll, keepfocus, state })
returns aPromise
that resolves when SvelteKit navigates (or fails to navigate, in which case the promise rejects) to the specifiedhref
. The second argument is optional:replaceState
(boolean, defaultfalse
) Iftrue
, will replace the currenthistory
entry rather than creating a new one withpushState
noscroll
(boolean, defaultfalse
) Iftrue
, the browser will maintain its scroll position rather than scrolling to the top of the page after navigationkeepfocus
(boolean, defaultfalse
) Iftrue
, the currently focused element will retain focus after navigation. Otherwise, focus will be reset to the bodystate
(object, default{}
) The state of the new/updated history entry
invalidate(href)
causes anyload
functions belonging to the currently active page to re-run if theyfetch
the resource in question. It returns aPromise
that resolves when the page is subsequently updated.prefetch(href)
programmatically prefetches the given page, which means a) ensuring that the code for the page is loaded, and b) calling the page'sload
function with the appropriate options. This is the same behaviour that SvelteKit triggers when the user taps or mouses over an<a>
element with sveltekit:prefetch. If the next navigation is tohref
, the values returned fromload
will be used, making navigation instantaneous. Returns aPromise
that resolves when the prefetch is complete.prefetchRoutes(routes)
— programmatically prefetches the code for routes that haven't yet been fetched. Typically, you might call this to speed up subsequent navigation. If no argument is given, all routes will be fetched; otherwise, you can specify routes by any matching pathname such as/about
(to matchsrc/routes/about.svelte
) or/blog/*
(to matchsrc/routes/blog/[slug].svelte
). Unlikeprefetch
, this won't callload
for individual pages. Returns aPromise
that resolves when the routes have been prefetched.
$app/pathspermalink
ts
import {base ,assets } from '$app/paths';
base
— a root-relative (i.e. begins with a/
) string that matchesconfig.kit.paths.base
, or the empty string if unspecifiedassets
— an absolute URL that matchesconfig.kit.paths.assets
, if specified, otherwise equal tobase
If a value for
config.kit.paths.assets
is specified, it will be replaced with'/_svelte_kit_assets'
duringsvelte-kit dev
orsvelte-kit preview
, since the assets don't yet live at their eventual URL.
$app/storespermalink
ts
import {getStores ,navigating ,page ,session ,updated } from '$app/stores';
Stores are contextual — they are added to the context of your root component. This means that session
and page
are unique to each request on the server, rather than shared between multiple requests handled by the same server simultaneously, which is what makes it safe to include user-specific data in session
.
Because of that, the stores are not free-floating objects: they must be accessed during component initialisation, like anything else that would be accessed with getContext
.
getStores
is a convenience function aroundgetContext
that returns{ navigating, page, session, updated }
. This needs to be called at the top-level or synchronously during component or page initialisation.
The stores themselves attach to the correct context at the point of subscription, which means you can import and use them directly in components without boilerplate. However, it still needs to be called synchronously on component or page initialisation when the $
-prefix isn't used. Use getStores
to safely .subscribe
asynchronously instead.
navigating
is a readable store. When navigating starts, its value is{ from, to }
, wherefrom
andto
are bothURL
instances. When navigating finishes, its value reverts tonull
.page
contains an object with the currenturl
,params
,stuff
,status
anderror
.session
is a writable store whose initial value is whatever was returned fromgetSession
. It can be written to, but this will not cause changes to persist on the server — this is something you must implement yourself.updated
is a readable store whose initial value is false. Ifversion.pollInterval
is a non-zero value, SvelteKit will poll for new versions of the app and update the store value totrue
when it detects one.updated.check()
will force an immediate check, regardless of polling.
$libpermalink
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.
$service-workerpermalink
This module is only available to service workers.
ts
import {build ,files ,timestamp } from '$service-worker';
build
is an array of URL strings representing the files generated by Vite, suitable for caching withcache.addAll(build)
files
is an array of URL strings representing the files in yourstatic
directory, or whatever directory is specified byconfig.kit.files.assets
. You can customize which files are included fromstatic
directory usingconfig.kit.serviceWorker.files
timestamp
is the result of callingDate.now()
at build time. It's useful for generating unique cache names inside your service worker, so that a later deployment of your app can invalidate old caches
@sveltejs/kit/hookspermalink
This module provides a helper function to sequence multiple handle
calls.
src/hooks.js
ts
import {sequence } from '@sveltejs/kit/hooks';async functionfirst ({event ,resolve }) {console .log ('first pre-processing');constresult = awaitresolve (event );console .log ('first post-processing');returnresult ;}async functionsecond ({event ,resolve }) {console .log ('second pre-processing');constresult = awaitresolve (event );console .log ('second post-processing');returnresult ;}export consthandle =sequence (first ,second );
The example above would print:
first pre-processing
second pre-processing
second post-processing
first post-processing