Skip to main content

Modules

Edit this page on GitHub

SvelteKit makes a number of modules available to your application.

$app/environmentpermalink

import { browser, dev, prerendering } from '$app/environment';

browserpermalink

true if the app is running in the browser.

const browser: boolean;

devpermalink

Whether the dev server is running. This is not guaranteed to correspond to NODE_ENV or MODE.

const dev: boolean;

prerenderingpermalink

true when prerendering, false otherwise.

const prerendering: boolean;

$app/formspermalink

import { enhance, applyAction } from '$app/forms';

applyActionpermalink

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.

function applyAction<
  Success extends Record<string, unknown> | undefined = Record<string, any>,
  Invalid extends Record<string, unknown> | undefined = Record<string, any>
>(result: ActionResult<Success, Invalid>): Promise<void>;

enhancepermalink

This action enhances a <form> element that otherwise would work without JavaScript.

function enhance<
  Success extends Record<string, unknown> | undefined = Record<string, any>,
  Invalid extends Record<string, unknown> | undefined = Record<string, any>
>(
  form: HTMLFormElement,
  /**   * 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`   * - 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   */  submit?: SubmitFunction<Success, Invalid>
): { destroy: () => void };

$app/navigationpermalink

import {
  afterNavigate,
  beforeNavigate,
  disableScrollHandling,
  goto,
  invalidate,
  invalidateAll,
  prefetch,
  prefetchRoutes
} from '$app/navigation';

afterNavigatepermalink

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.

function afterNavigate(callback: (navigation: Navigation) => void): void;

beforeNavigatepermalink

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.

When navigating to an external URL, navigation.to will be null.

beforeNavigate must be called during a component initialization. It remains active as long as the component is mounted.

function beforeNavigate(
  callback: (navigation: Navigation & { 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 url.

function goto(
  url: string | URL,
  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 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.

// Example: Match '/path' regardless of the query parameters
invalidate((url) => url.pathname === '/path');
function invalidate(url: string | URL | ((url: URL) => boolean)): Promise<void>;

invalidateAllpermalink

Causes all load functions belonging to the currently active page to re-run. Returns a Promise that resolves when the page is subsequently updated.

function invalidateAll(): Promise<void>;

prefetchpermalink

Programmatically prefetches 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-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' during vite dev or vite 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, updated } from '$app/stores';

Stores on the server are contextual — they are added to the context of your root component. This means that page is unique to each request, rather than shared between multiple requests handled by the same server simultaneously.

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.

In the browser, we don't need to worry about this, and stores can be accessed from anywhere. Code that will only ever run on the browser can refer to (or subscribe to) any of these stores at any time.

getStorespermalink

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.

function getStores(): {
  navigating: typeof navigating;
  page: typeof page;
  updated: typeof updated;
};

navigatingpermalink

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.

const navigating: Readable<Navigation | null>;

pagepermalink

A readable store whose value contains page data.

const page: Readable<Page>;

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

$env/dynamic/privatepermalink

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.

import { env } from '$env/dynamic/private';
console.log(env.DEPLOYMENT_SPECIFIC_VARIABLE);

In dev, $env/dynamic always includes environment variables from .env. In prod, this behavior will depend on your adapter.

$env/dynamic/publicpermalink

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.

import { env } from '$env/dynamic/public';
console.log(env.PUBLIC_DEPLOYMENT_SPECIFIC_VARIABLE);

$env/static/privatepermalink

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.

import { API_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/publicpermalink

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.

import { PUBLIC_BASE_URL } from '$env/static/public';

$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/kitpermalink

The following can be imported from @sveltejs/kit:

errorpermalink

Creates an HttpError object with an HTTP status code and an optional message. This object, if thrown during request handling, will cause SvelteKit to return an error response without invoking handleError

function error(status: number, body: App.PageError): HttpError;

errorpermalink

function error(
  status: number,
  // this overload ensures you can omit the argument or pass in a string if App.PageError is of type { message: string }  body?: { message: string } extends App.PageError
    ? App.PageError | string | undefined
    : never
): HttpError;

invalidpermalink

Generates a ValidationError object.

function invalid<T extends Record<string, unknown> | undefined>(
  status: number,
  data?: T
): ValidationError<T>;

jsonpermalink

Generates a JSON Response object from the supplied data.

function json(data: any, init?: ResponseInit): Response;

redirectpermalink

Creates a Redirect object. If thrown during request handling, SvelteKit will return a redirect response.

function redirect(status: number, location: string): Redirect;

@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';
 
/** @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;
}
});
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;
}
});
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 transform
first transform
second post-processing
first post-processing
function sequence(...handlers: Handle[]): Handle;

@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;

@sveltejs/kit/vitepermalink

sveltekitpermalink

Returns the SvelteKit Vite plugins.

function sveltekit(): Plugin[];
previous Hooks
We stand with Ukraine. Donate → We stand with Ukraine. Petition your leaders. Show your support.