Modules
Edit this page on GitHubSvelteKit makes a number of modules available to your application.
$app/envpermalink
import { browser, dev, mode, prerendering, prod, server } from '$app/env';
browserpermalink
true
if the app is running in the browser.
const browser: boolean;
devpermalink
true
in development mode, false
in production.
const dev: boolean;
modepermalink
The Vite.js mode the app is running in. Configure in config.kit.vite.mode
.
Vite.js loads the dotenv file associated with the provided mode, .env.[mode]
or .env.[mode].local
.
By default, svelte-kit dev
runs with mode=development
and svelte-kit build
runs with mode=production
.
const mode: string;
prerenderingpermalink
true
when prerendering, false
otherwise.
const prerendering: boolean;
prodpermalink
true
in production mode, false
in development.
const prod: boolean;
serverpermalink
true
if the app is running on the server.
const server: boolean;
$app/navigationpermalink
import {
afterNavigate,
beforeNavigate,
disableScrollHandling,
goto,
invalidate,
prefetch,
prefetchRoutes
} from '$app/navigation';
afterNavigatepermalink
A lifecycle function that runs when the page mounts, and also whenever SvelteKit navigates to a new URL but stays on this component.
function afterNavigate(
fn: (navigation: { from: URL | null; to: URL }) => void
): void;
beforeNavigatepermalink
A navigation interceptor that triggers before we navigate to a new URL (internal or external) whether by clicking a link, calling goto
, or using the browser back/forward controls.
This is helpful if we want to conditionally prevent a navigation from completing or lookup the upcoming url.
function beforeNavigate(
fn: (navigation: {
from: URL;
to: URL | null;
cancel: () => void;
}) => void
): void;
disableScrollHandlingpermalink
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.
function disableScrollHandling(): void;
gotopermalink
Returns a Promise that resolves when SvelteKit navigates (or fails to navigate, in which case the promise rejects) to the specified href
.
function goto(
href: string,
opts?: {
replaceState?: boolean;
noscroll?: boolean;
keepfocus?: boolean;
state?: any;
}
): Promise<void>;
invalidatepermalink
Causes any load
functions belonging to the currently active page to re-run if they fetch
the resource in question, or re-fetches data from a page endpoint if the invalidated resource is the page itself. Returns a Promise
that resolves when the page is subsequently updated.
function invalidate(
dependency: string | ((href: string) => boolean)
): Promise<void>;
prefetchpermalink
Programmatically prefetches 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 sveltekit:prefetch
.
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 prefetch is complete.
function prefetch(href: string): Promise<void>;
prefetchRoutespermalink
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 match src/routes/about.svelte
) or /blog/*
(to match src/routes/blog/[slug].svelte
).
Unlike prefetch, this won't call load for individual pages. Returns a Promise that resolves when the routes have been prefetched.
function prefetchRoutes(routes?: string[]): Promise<void>;
$app/pathspermalink
import { base, assets } from '$app/paths';
assetspermalink
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'
duringsvelte-kit dev
orsvelte-kit preview
, since the assets don't yet live at their eventual URL.
const assets: `https://${string}` | `http://${string}`;
basepermalink
A string that matches config.kit.paths.base
. It must start, but not end with /
(e.g. /base-path
), unless it is the empty string.
const base: `/${string}`;
$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, you must subscribe to the stores during component initialization (which happens automatically if you reference the store value, e.g. as $page
, in a component) before you can use them.
getStorespermalink
A convenience function around getContext
. 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.
function getStores(): {
navigating: typeof navigating;
page: typeof page;
session: typeof session;
updated: typeof updated;
};
navigatingpermalink
A readable store.
When navigating starts, its value is { from: URL, to: URL }
,
When navigating finishes, its value reverts to null
.
const navigating: Readable<Navigation | null>;
pagepermalink
A readable store whose value contains page data.
const page: Readable<Page>;
sessionpermalink
A writable store whose initial value is whatever was returned from getSession
.
It can be written to, but this will not cause changes to persist on the server — this is something you must implement yourself.
const session: Writable<App.Session>;
updatedpermalink
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.
const updated: Readable<boolean> & { check: () => boolean };
$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
import { build, files, prerendered, version } from '$service-worker';
This module is only available to service workers.
buildpermalink
An array of URL strings representing the files generated by Vite, suitable for caching with cache.addAll(build)
.
const build: string[];
filespermalink
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
const files: string[];
prerenderedpermalink
An array of pathnames corresponding to prerendered pages and endpoints.
const prerendered: string[];
versionpermalink
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.
const version: string;
@sveltejs/kit/hookspermalink
sequencepermalink
A helper function for sequencing multiple handle
calls in a middleware-like manner.
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
@sveltejs/kit/nodepermalink
Utilities used by adapters for Node-like environments.
getRequestpermalink
function getRequest(
base: string,
request: import('http').IncomingMessage
): Promise<Request>;
setResponsepermalink
function setResponse(
res: import('http').ServerResponse,
response: Response
): void;
@sveltejs/kit/node/polyfillspermalink
A polyfill for fetch
and its related interfaces, used by adapters for environments that don't provide a native implementation.
installPolyfillspermalink
Make various web APIs available as globals:
crypto
fetch
Headers
Request
Response
function installPolyfills(): void;