Modules
Edit this page on GitHubSvelteKit makes a number of modules available to your application.
$app/envpermalink
import { amp, browser, dev, mode, prerendering } from '$app/env';ampistrueorfalsedepending on the corresponding value in your project configurationbrowseristrueorfalsedepending on whether the app is running in the browser or on the serverdevistruein development mode,falsein productionmodeis the Vite mode, which isdevelopmentin dev mode orproductionduring build unless configured otherwise inconfig.kit.vite.mode.prerenderingistruewhen prerendering,falseotherwise
$app/navigationpermalink
import {
disableScrollHandling,
goto,
invalidate,
prefetch,
prefetchRoutes,
beforeNavigate,
afterNavigate
} 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.towill benullif the user is closing the page. Callingcancelwill prevent the navigation from proceedingdisableScrollHandlingwill, if called when the page is being updated following a navigation (inonMountor 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 aPromisethat 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 currenthistoryentry rather than creating a new one withpushStatenoscroll(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 anyloadfunctions belonging to the currently active page to re-run if theyfetchthe resource in question. It returns aPromisethat 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'sloadfunction 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 fromloadwill be used, making navigation instantaneous. Returns aPromisethat 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 callloadfor individual pages. Returns aPromisethat resolves when the routes have been prefetched.
$app/pathspermalink
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.assetsis specified, it will be replaced with'/_svelte_kit_assets'duringsvelte-kit devorsvelte-kit preview, since the assets don't yet live at their eventual URL.
$app/storespermalink
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.
getStoresis a convenience function aroundgetContextthat 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.
navigatingis a readable store. When navigating starts, its value is{ from, to }, wherefromandtoare bothURLinstances. When navigating finishes, its value reverts tonull.pagecontains an object with the currenturl,params,stuff,statusanderror.sessionis 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.updatedis a readable store whose initial value is false. Ifversion.pollIntervalis a non-zero value, SvelteKit will poll for new versions of the app and update the store value totruewhen 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.
import { build, files, timestamp } from '$service-worker';buildis an array of URL strings representing the files generated by Vite, suitable for caching withcache.addAll(build)filesis an array of URL strings representing the files in yourstaticdirectory, or whatever directory is specified byconfig.kit.files.assets. You can customize which files are included fromstaticdirectory usingconfig.kit.serviceWorker.filestimestampis 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.
import { sequence } from '@sveltejs/kit/hooks';
async function first({ event, resolve }) {
console.log('first pre-processing');
const result = await resolve(event);
console.log('first post-processing');
return result;
}
async function second({ event, resolve }) {
console.log('second pre-processing');
const result = await resolve(event);
console.log('second post-processing');
return result;
}
export const handle = sequence(first, second);The example above would print:
first pre-processing
second pre-processing
second post-processing
first post-processing