```dts
function form<
Schema extends StandardSchemaV1<
RemoteFormInput,
Record
>,
Output
>(
validate: true extends HasNonOptionalBoolean<
StandardSchemaV1.InferInput
>
? 'Error: Boolean fields in form schemas that accept false must be optional (e.g. `v.optional(v.boolean(), false)`) because checkbox inputs do not send a false value when unchecked.'
: Schema,
fn: (
data: StandardSchemaV1.InferOutput,
issue: RemoteFormInvalidField<
StandardSchemaV1.InferInput
>
) => MaybePromise
): RemoteForm, Output>;
```
## getRequestEvent
` for queries
declared with a Standard Schema).
Arguments that fail validation or exceed `limit` are recorded as failures in
the response to the client.
See [Client-requested refreshes](/docs/kit/remote-functions#Single-flight-mutations-Client-requested-refreshes)
for usage in a remote `command` or `form`.
```ts
import { requested } from '$app/server';
for (const { arg, query } of requested(getPost, 5)) {
// `arg` is the validated argument; `query` is bound to the client's
// cache key. It's safe to throw away this promise -- SvelteKit will
// await it and forward any errors to the client.
void query.refresh();
}
```
As a shorthand for the above, you can also call `refreshAll` on the result:
```ts
import { requested } from '$app/server';
await requested(getPost, 5).refreshAll();
```
Works with `query.batch` as well — refreshes for individual entries are
collected into a single batched call.
For live queries, the same applies, but with `reconnect` and `reconnectAll`.
```dts
function requested (
query: RemoteQueryFunction ,
limit: number
): RemoteQueryRequestedResult;
```
```dts
function requested (
query: RemoteLiveQueryFunction ,
limit: number
): RemoteLiveQueryRequestedResult;
```
## RemoteCommand
The type of a remote `command` function. See [Remote functions](/docs/kit/remote-functions#command) for full documentation.
```dts
type RemoteCommand = {
(
arg: undefined extends Input ? Input | void : Input
): Promise & {
updates(
...updates: RemoteQueryUpdate[]
): Promise;
};
/** The number of pending command executions */
get pending(): number;
};
```
## RemoteForm
The type of a remote `form` function. See [Remote functions](/docs/kit/remote-functions#form) for full documentation.
```dts
type RemoteForm<
Input extends RemoteFormInput | void,
Output
> = RemoteForm_ ;
```
## RemoteFormEnhanceCallback
The callback passed to a remote form's `enhance` method. See [Remote functions](/docs/kit/remote-functions#form) for full documentation.
```dts
type RemoteFormEnhanceCallback<
Input extends RemoteFormInput | void =
RemoteFormInput | void,
Output = any
> = (
form: RemoteFormEnhanceInstance
) => MaybePromise;
```
## RemoteFormEnhanceInstance
The form instance as received inside an `enhance` callback. See [Remote functions](/docs/kit/remote-functions#form) for full documentation.
```dts
type RemoteFormEnhanceInstance<
Input extends RemoteFormInput | void =
RemoteFormInput | void,
Output = any
> = Omit<
RemoteForm ,
'enhance' | 'element'
> & {
readonly element: HTMLFormElement;
};
```
## RemoteFormField
Form field accessor type that provides name(), value(), and issues() methods
```dts
type RemoteFormField =
RemoteFormFieldMethods & {
/**
* Returns an object that can be spread onto an input element with the correct type attribute,
* aria-invalid attribute if the field is invalid, and appropriate value/checked property getters/setters.
* @example
* ```svelte
*
*
*
* ```
*/
as>(
...args: AsArgs
): InputElementProps>;
};
```
## RemoteFormFieldType
```dts
type RemoteFormFieldType = {
[K in keyof InputTypeMap]: T extends InputTypeMap[K]
? K
: never;
}[keyof InputTypeMap];
```
## RemoteFormFieldValue
```dts
type RemoteFormFieldValue =
| string
| string[]
| number
| boolean
| File
| File[]
| ImageInputValue;
```
## RemoteFormFields
Recursive type to build form fields structure with proxy access
```dts
type RemoteFormFields =
WillRecurseIndefinitely extends true
? RecursiveFormFields
: NonNullable extends
string | number | boolean | File
? RemoteFormField>
: IsImageInputValue> extends true
? RemoteFormField<
NonNullable & ImageInputValue
> &
Pick<
RemoteFormFieldContainer,
'allIssues'
> & {
[K in KeysOfUnion]-?: RemoteFormFields<
ValueOfUnionKey
>;
}
: // [NonNullable] is used to prevent distributing over union while still allowing
// nullable wrappers (e.g. `string[] | undefined` from a schema with `.default([])`)
// to be treated as arrays; only the last condition should distribute over unions
[NonNullable] extends [string[] | File[]]
? RemoteFormField> & {
[K in number]: RemoteFormField<
NonNullable[number]
>;
}
: [NonNullable] extends [Array]
? RemoteFormFieldContainer> & {
[K in number]: RemoteFormFields;
}
: RemoteFormFieldContainer & {
[K in KeysOfUnion]-?: RemoteFormFields<
ValueOfUnionKey
>;
};
```
## RemoteFormInput
```dts
interface RemoteFormInput {/*…*/}
```
```dts
[key: string]: MaybeArray
| undefined;
```
## RemoteFormInvalidField
A function and proxy object used to imperatively create validation errors in form handlers.
Access properties to create field-specific issues: `issue.fieldName('message')`.
The type structure mirrors the input data structure for type-safe field access.
Call `invalid(issue.foo(...), issue.nested.bar(...))` to throw a validation error.
```dts
type RemoteFormInvalidField =
WillRecurseIndefinitely extends true
? Record
: NonNullable extends
string | number | boolean | File
? (message: string) => StandardSchemaV1.Issue
: NonNullable extends Array
? {
[K in number]: RemoteFormInvalidField;
} & ((message: string) => StandardSchemaV1.Issue)
: NonNullable extends RemoteFormInput
? {
[K in keyof T]-?: RemoteFormInvalidField<
T[K]
>;
} & ((
message: string
) => StandardSchemaV1.Issue)
: Record;
```
## RemoteFormIssue
```dts
interface RemoteFormIssue {/*…*/}
```
```dts
message: string;
```
## RemoteLiveQuery
```dts
type RemoteLiveQuery = RemoteResource &
AsyncIterable & {
/** `true` if the live stream is currently connected. */
readonly connected: boolean;
/** `true` once the current live stream iterator is done. */
readonly done: boolean;
/** Reconnects the live stream immediately. */
reconnect(): Promise;
};
```
## RemoteLiveQueryFunction
The type of a remote `query.live` function. See [Remote functions](/docs/kit/remote-functions#query.live) for full documentation.
The optional `Validated` generic parameter represents the argument type *after* the
query's schema has validated and (optionally) transformed it, and matches the type
yielded by [`requested`](/docs/kit/$app-server#requested).
```dts
type RemoteLiveQueryFunction<
Input,
Output,
_Validated = Input
> = (
arg: undefined extends Input ? Input | void : Input
) => RemoteLiveQuery;
```
## RemoteLiveQueryRequestedEntry
A single entry yielded by [`requested`](/docs/kit/$app-server#requested)
when called with a `query.live`. `arg` is the validated argument; `query` is a
`RemoteLiveQuery` bound to the client's original cache key, so `reconnect()` targets
the correct client subscription.
```dts
type RemoteLiveQueryRequestedEntry = {
arg: Validated;
query: RemoteLiveQuery;
/** Explicitly ignore this requested update. */
ignore: () => void;
};
```
## RemoteLiveQueryRequestedResult
```dts
type RemoteLiveQueryRequestedResult =
Iterable<
RemoteLiveQueryRequestedEntry
> &
AsyncIterable<
RemoteLiveQueryRequestedEntry
> & {
/**
* Call `reconnect` on all live queries selected by this `requested` invocation.
* This is identical to:
* ```ts
* import { requested } from '$app/server';
*
* for await (const { query } of requested(liveQuery, ...)) {
* void query.reconnect();
* }
* ```
*/
reconnectAll: () => Promise;
/** Explicitly ignore all updates selected by this `requested` invocation. */
ignoreAll: () => Promise;
};
```
## RemotePrerenderFunction
The type of a remote `prerender` function. See [Remote functions](/docs/kit/remote-functions#prerender) for full documentation.
```dts
type RemotePrerenderFunction = (
arg: undefined extends Input ? Input | void : Input
) => RemoteResource;
```
## RemoteQuery
```dts
type RemoteQuery = RemoteResource & {
/**
* On the client, this function will update the value of the query without re-fetching it.
*
* On the server, this can be called in the context of a `command` or `form` and the specified data will accompany the action response back to the client.
* This prevents SvelteKit needing to refresh all queries on the page in a second server round-trip.
*/
set(value: T): void;
/**
* On the client, this function will re-fetch the query from the server.
*
* On the server, this can be called in the context of a `command` or `form` and the refreshed data will accompany the action response back to the client.
* This prevents SvelteKit needing to refresh all queries on the page in a second server round-trip.
*/
refresh(): Promise;
/**
* Temporarily override a query's value during a [single-flight mutation](https://svelte.dev/docs/kit/remote-functions#Single-flight-mutations) to provide optimistic updates.
*
* ```svelte
*
*
*
* ```
*/
withOverride(
update: (current: T) => T
): RemoteQueryOverride;
};
```
## RemoteQueryFunction
The return value of a remote `query` function. See [Remote functions](/docs/kit/remote-functions#query) for full documentation.
The optional `Validated` generic parameter represents the argument type *after* the
query's schema has validated and (optionally) transformed it — this is the type the
query's implementation function receives on the server, and the type yielded by
[`requested`](/docs/kit/$app-server#requested). For queries declared
with [Standard Schema](https://standardschema.dev/) it differs from `Input` when the
schema contains a transform (e.g. `v.pipe(v.number(), v.transform(String))` has
`Input = number` but `Validated = string`). For `'unchecked'` validators and queries
without arguments it defaults to `Input`.
```dts
type RemoteQueryFunction<
Input,
Output,
_Validated = Input
> = (
arg: undefined extends Input ? Input | void : Input
) => RemoteQuery;
```
## RemoteQueryOverride
```dts
type RemoteQueryOverride = () => void;
```
## RemoteQueryRequestedResult
```dts
type RemoteQueryRequestedResult =
Iterable> &
AsyncIterable> & {
/**
* Call `refresh` on all queries selected by this `requested` invocation.
* This is identical to:
* ```ts
* import { requested } from '$app/server';
*
* for await (const { query } of requested(getPost, ...)) {
* void query.refresh();
* }
* ```
*/
refreshAll: () => Promise;
/** Explicitly ignore all updates selected by this `requested` invocation. */
ignoreAll: () => Promise;
};
```
## RemoteQueryUpdate
```dts
type RemoteQueryUpdate =
| RemoteQuery
| RemoteLiveQuery
| RemoteQueryFunction
| RemoteLiveQueryFunction
| RemoteQueryOverride;
```
## RemoteResource
```dts
type RemoteResource = Promise & {
/** The error in case the query fails. */
get error(): App.Error | undefined;
/** `true` before the first result is available and during refreshes */
get loading(): boolean;
} & (
| {
/** The current value of the query. Undefined until `ready` is `true` */
get current(): undefined;
ready: false;
}
| {
/** The current value of the query. Undefined until `ready` is `true` */
get current(): T;
ready: true;
}
);
```
## RequestedEntry
A single entry yielded by [`requested`](/docs/kit/$app-server#requested)
when called with a regular `query`. `arg` is the validated argument (the input *after*
the query's schema validated and transformed it, if applicable); `query` is a
`RemoteQuery` bound to the client's original cache key, so `refresh()` / `set()` will
update the correct client entry.
```dts
type RequestedEntry = {
arg: Validated;
query: RemoteQuery;
/** Explicitly ignore this requested update. */
ignore: () => void;
};
```
## RequestedResult
```dts
type RequestedResult =
| RemoteQueryRequestedResult
| RemoteLiveQueryRequestedResult;
```
## query
```dts
namespace query {
/**
* Creates a batch query function that collects multiple calls and executes them in a single request
*
* See [Remote functions](https://svelte.dev/docs/kit/remote-functions#query.batch) for full documentation.
*
* @since 2.35
*/
function batch (
validate: 'unchecked',
fn: (
args: Input[]
) => MaybePromise<(arg: Input, idx: number) => Output>
): RemoteQueryFunction ;
/**
* Creates a batch query function that collects multiple calls and executes them in a single request
*
* See [Remote functions](https://svelte.dev/docs/kit/remote-functions#query.batch) for full documentation.
*
* @since 2.35
*/
function batch(
schema: Schema,
fn: (
args: StandardSchemaV1.InferOutput[]
) => MaybePromise<
(
arg: StandardSchemaV1.InferOutput,
idx: number
) => Output
>
): RemoteQueryFunction<
StandardSchemaV1.InferInput,
Output,
StandardSchemaV1.InferOutput
>;
/**
* Creates a live remote query. When called from the browser, the function will be invoked on the server via a streaming `fetch` call.
*
* See [Remote functions](https://svelte.dev/docs/kit/remote-functions#query.live) for full documentation.
*
* */
function live(
fn: (
arg: void
) => RemoteLiveQueryUserFunctionReturnType
): RemoteLiveQueryFunction;
function live (
validate: 'unchecked',
fn: (
arg: Input
) => RemoteLiveQueryUserFunctionReturnType
): RemoteLiveQueryFunction ;
function live(
schema: Schema,
fn: (
arg: StandardSchemaV1.InferOutput
) => RemoteLiveQueryUserFunctionReturnType
): RemoteLiveQueryFunction<
StandardSchemaV1.InferInput,
Output,
StandardSchemaV1.InferOutput
>;
}
```
# $app/service-worker
This module can only be imported in service workers.
```js
// @noErrors
import { self } from '$app/service-worker';
```
## self
The execution context of a service worker. This export exists to make it easier to
use service workers with the correct types, provided the importing module is governed
by a `tsconfig.json` that extends [`$app/tsconfig/service-worker`](/docs/kit/$app-tsconfig-service-worker).
```dts
const self: ServiceWorkerGlobalScope;
```
# $app/state
SvelteKit makes three read-only state objects available via the `$app/state` module — `page`, `navigating` and `updated`.
```js
// @noErrors
import { navigating, page, updated } from '$app/state';
```
## navigating
A read-only object representing an in-progress navigation, with `from`, `to`, `type` and (if `type === 'popstate'`) `delta` properties.
Values are `null` when no navigation is occurring, or during server rendering.
```dts
const navigating:
| Navigation
| {
from: null;
to: null;
type: null;
willUnload: null;
delta: null;
complete: null;
};
```
## page
A read-only reactive object with information about the current page, serving several use cases:
- retrieving the combined `data` of all pages/layouts anywhere in your component tree (also see [loading data](/docs/kit/load))
- retrieving the current value of the `form` prop anywhere in your component tree (also see [form actions](/docs/kit/form-actions))
- retrieving the page state that was set through `goto` (also see [goto](/docs/kit/$app-navigation#goto) and [shallow routing](/docs/kit/shallow-routing))
- retrieving metadata such as the URL you're on, the current route and its parameters, the target of a shallow navigation, and whether or not there was an error
```svelte
Currently at {page.url.pathname}
{#if page.error}
Problem detected
{:else}
All systems operational
{/if}
```
Changes to `page` are available exclusively with runes. (The legacy reactivity syntax will not reflect any changes)
```svelte
```
On the server, values can only be read during rendering (in other words _not_ in e.g. `load` functions). In the browser, the values can be read at any time.
```dts
const page: Page;
```
## updated
A read-only reactive value that's initially `false`. SvelteKit checks for new versions on data, remote, and form action responses (via the `x-sveltekit-version` header), when the tab regains focus or becomes visible, and on a poll interval (see [`version.pollInterval`](/docs/kit/@sveltejs-kit-vite#version)). `updated.current` is set to `true` when a new version is detected. `updated.check()` will force an immediate check, regardless of polling.
```dts
const updated: {
get current(): boolean;
check(): Promise;
};
```
## Page
The shape of the [`page`](/docs/kit/$app-state#page) reactive object.
```dts
interface Page<
Params extends AppLayoutParams<'/'> =
AppLayoutParams<'/'>,
RouteId extends AppRouteId | null = AppRouteId | null
> {/*…*/}
```
```dts
url: ReadonlyURL & { readonly pathname: ResolvedPathname | (string & {}) };
```
The URL of the current page.
```dts
params: Params;
```
The parameters of the current page - e.g. for a route like `/blog/[slug]`, a `{ slug: string }` object.
```dts
route: {/*…*/};
```
Info about the current route.
```dts
id: RouteId;
```
The ID of the current route - e.g. for `src/routes/blog/[slug]`, it would be `/blog/[slug]`. It is `null` when no route is matched.
```dts
status: number;
```
HTTP status code of the current page.
```dts
error: App.Error | null;
```
The error object of the current page, if any. Filled from the `handleError` hooks.
```dts
data: App.PageData & Record
;
```
The merged result of all data from all `load` functions on the current page. You can type a common denominator through `App.PageData`.
```dts
state: App.PageState;
```
The page state, which can be manipulated using [`goto`](/docs/kit/$app-navigation#goto) from `$app/navigation`.
```dts
shallow: {/*…*/} | null;
```
Information about the target of the current shallow navigation, or `null` if no shallow navigation has occurred.
```dts
params: AppLayoutParams<'/'> | null;
```
Parameters of the target route, or `null` if the URL does not resolve to a route.
```dts
route: { id: AppRouteId } | null;
```
Info about the target route, or `null` if the URL does not resolve to a route.
```dts
url: ReadonlyURL;
```
The normalized URL passed to `goto(..., { shallow: true })`.
```dts
form: any;
```
Filled only after a form submission. See [form actions](/docs/kit/form-actions) for more info.
## ReadonlyURL
```dts
type ReadonlyURL = Readonly<
Omit & {
searchParams: ReadonlyURLSearchParams;
}
>;
```
## ReadonlyURLSearchParams
```dts
type ReadonlyURLSearchParams = Omit<
URLSearchParams,
'set' | 'append' | 'delete' | 'sort'
>;
```
# $app/tsconfig
This module contains TypeScript configuration tailored for your app. Your own config should extend it — a typical `tsconfig.json` looks like this:
```json
/// file: tsconfig.json
{
"extends": "$app/tsconfig",
"include": ["src", "test"],
"exclude": ["src/service-worker"]
}
```
You can extend this configuration with your own `compilerOptions`. Overriding the following properties may cause things to break — SvelteKit will warn you if this happens:
- `paths` — this is derived from the (deprecated) [`alias`](@sveltejs-kit-vite#alias) config option, together with any [subpath imports](https://nodejs.org/api/packages.html#subpath-imports) specified in your `package.json`, to align behaviour between Vite and TypeScript. Ideally, configure subpath imports rather than using `paths` directly
- `types` — your app needs to be able to 'see' generated module declarations for things like [environment variables](environment-variables), and as such this array must include `"$app/types"`
- `isolatedModules` — must be `true`, as Vite compiles modules one at a time
- `verbatimModuleSyntax` — must be `true`, so that you can safely use type imports in `.svelte` files
Note that the example configuration above excludes `src/service-worker`, because service workers need to be in their own TypeScript project. If you are using a service worker, create a `src/service-worker/tsconfig.json` that extends [`$app/tsconfig/service-worker`]($app-tsconfig-service-worker).
# $app/tsconfig/service-worker
This module contains TypeScript configuration tailored for your service worker:
```json
/// file: src/service-worker/tsconfig.json
{
"extends": "$app/tsconfig/service-worker"
}
```
You can extend this configuration with your own `compilerOptions`, adhering to the same restrictions as [`$app/tsconfig`]($app-tsconfig).
# $app/types
This module contains generated types for the routes in your app.
Available since 2.26
```js
// @noErrors
import type { RouteId, PageRouteId, EndpointRouteId, RouteParams, LayoutParams } from '$app/types';
```
## AssetPath
A union of all the filenames of assets contained in your `static` directory, relative to the `base` path.
```dts
type AssetPath = 'favicon.png' | 'robots.txt' | (string & {});
```
## RouteId
A union of all the route IDs in your app — the union of `PageRouteId` and `EndpointRouteId`. Used for `page.route.id` and `event.route.id`.
```dts
type RouteId = '/' | '/my-route' | '/my-other-route/[param]' | '/my-endpoint';
```
## PageRouteId
A union of the route IDs in your app that have a `+page`.
A route ID can be in both `PageRouteId` and `EndpointRouteId`, if its directory contains both a `+page` and a `+server`. In the example below, `/my-route` has both.
```dts
type PageRouteId = '/' | '/my-route' | '/my-other-route/[param]';
```
## EndpointRouteId
A union of the route IDs in your app that have a `+server`.
A route ID can be in both `PageRouteId` and `EndpointRouteId`, if its directory contains both a `+page` and a `+server`. In the example below, `/my-route` has both.
```dts
type EndpointRouteId = '/my-route' | '/my-endpoint';
```
## Path
A union of all valid paths in your app, relative to the `base` path.
```dts
type Path = '' | 'my-route' | `my-other-route/${string}` & {};
```
## ResolvedPathname
Similar to `Path`, but prefixed with a [base path](@sveltejs-kit-vite#paths). Used for `page.url.pathname`.
```dts
type ResolvedPathname = `${'' | `/${string}`}/` | `${'' | `/${string}`}/my-route` | `${'' | `/${string}`}/my-other-route/${string}` | {};
```
## RouteParams
A utility for getting the parameters associated with a given route.
```ts
// @errors: 2552
type BlogParams = RouteParams<'/blog/[slug]'>; // { slug: string }
```
```dts
type RouteParams = { /* generated */ } | Record;
```
## LayoutParams
A utility for getting the parameters associated with a given layout, which is similar to `RouteParams` but also includes optional parameters for any child route. It accepts the route ID of any directory containing a layout, including layout-only directories that are not part of `RouteId`.
```dts
type LayoutParams = { /* generated */ };
```
# #lib
When scaffolding a new SvelteKit project through the [`sv` CLI](/docs/cli/overview), it automatically creates a `#lib` import alias for your `src/lib` directory, by adding the following to your `package.json`:
```json
{
"imports": {
"#lib": "./src/lib/index.js",
"#lib/*": "./src/lib/*"
}
}
```
The `#` prefix leverages Node's built-in [subpath imports](https://nodejs.org/api/packages.html#subpath-imports) feature, which reserves `#` for package-internal aliases. Vite and TypeScript both resolve these natively.
> Previously, this alias was `$lib` and was automatically configured by SvelteKit. It is now `#lib` and must be declared in your `package.json` `imports` field. `import { foo } from '$lib/foo.js'` becomes `import { foo } from '#lib/foo.js'`.
```svelte
A reusable component
```
```svelte
```
# Command Line Interface
SvelteKit projects use [Vite](https://vitejs.dev), meaning you'll mostly use its CLI (albeit via `npm run dev/build/preview` scripts):
- `vite dev` — start a development server
- `vite build` — build a production version of your app
- `vite preview` — run the production version locally
However SvelteKit includes its own CLI for initialising your project:
## svelte-kit sync
`svelte-kit sync` creates the `tsconfig.json` and all generated types (which you can import as `./$types` inside routing files) for your project. When you create a new project, it is listed as the `prepare` script and will be run automatically as part of the npm lifecycle, so you should not ordinarily have to run this command.
# Types
## Generated types
The `RequestHandler` and `Load` types both accept a `Params` argument allowing you to type the `params` object. For example this endpoint expects `foo`, `bar` and `baz` params:
```js
/// file: src/routes/[foo]/[bar]/[baz]/+server.js
// @errors: 2355 2322 1360
/**
* @type {import('@sveltejs/kit').RequestHandler<{
* foo: string;
* bar: string;
* baz: string
* }>}
*/
export async function GET({ params }) {
// ...
}
```
Needless to say, this is cumbersome to write out, and less portable (if you were to rename the `[foo]` directory to `[qux]`, the type would no longer reflect reality).
To solve this problem, SvelteKit generates `.d.ts` files for each of your endpoints and pages:
```ts
/// file: .svelte-kit/types/src/routes/[foo]/[bar]/[baz]/$types.d.ts
import type * as Kit from '@sveltejs/kit';
type RouteParams = {
foo: string;
bar: string;
baz: string;
};
export type RequestHandler = Kit.RequestHandler;
export type PageLoad = Kit.Load;
```
These files can be imported into your endpoints and pages as siblings, thanks to the [`rootDirs`](https://www.typescriptlang.org/tsconfig#rootDirs) option in your TypeScript configuration:
```js
/// file: src/routes/[foo]/[bar]/[baz]/+server.js
// @filename: $types.d.ts
import type * as Kit from '@sveltejs/kit';
type RouteParams = {
foo: string;
bar: string;
baz: string;
}
export type RequestHandler = Kit.RequestHandler;
// @filename: index.js
// @errors: 2355 2322
// ---cut---
/** @type {import('./$types').RequestHandler} */
export async function GET({ params }) {
// ...
}
```
```js
/// file: src/routes/[foo]/[bar]/[baz]/+page.js
// @filename: $types.d.ts
import type * as Kit from '@sveltejs/kit';
type RouteParams = {
foo: string;
bar: string;
baz: string;
}
export type PageLoad = Kit.Load;
// @filename: index.js
// @errors: 2355
// ---cut---
/** @type {import('./$types').PageLoad} */
export async function load({ params, fetch }) {
// ...
}
```
The return types of the load functions are then available through the `$types` module as `PageData` and `LayoutData` respectively, while the union of the return values of all `Actions` is available as `ActionData`.
Starting with version 2.16.0, two additional helper types are provided: `PageProps` defines `data: PageData`, as well as `form: ActionData`, when there are actions defined, while `LayoutProps` defines `data: LayoutData`, as well as `children: Snippet`.
```svelte
```
> Before 2.16.0:
> ```svelte
>
>
> ```
>
> Using Svelte 4:
> ```svelte
>
>
> ```
>
> `{ "extends": "$app/tsconfig" }`
## app.d.ts
The `app.d.ts` file is home to the ambient types of your apps, i.e. types that are available without explicitly importing them.
Always part of this file is the `App` namespace. This namespace contains several types that influence the shape of certain SvelteKit features you interact with.
It's possible to tell SvelteKit how to type objects inside your app by declaring the `App` namespace. By default, a new project will have a file called `src/app.d.ts` containing the following:
```ts
declare global {
namespace App {
// interface Error {}
// interface Locals {}
// interface PageData {}
// interface PageState {}
// interface Platform {}
}
}
export {};
```
The `export {}` line exists because without it, the file would be treated as an _ambient module_ which prevents you from adding `import` declarations.
If you need to add ambient `declare module` declarations, do so in a separate file like `src/ambient.d.ts`.
By populating these interfaces, you will gain type safety when using `event.locals`, `event.platform`, and `data` from `load` functions.
## Error
Defines the common shape of expected and unexpected errors. Expected errors are thrown using the `error` function. Every error passes through the `handleError` hooks, which must return this shape (with `status` and `message` optional, since they default to those of the caught error).
```dts
interface Error {/*…*/}
```
```dts
status: number;
```
```dts
message: string;
```
## Locals
The interface that defines `event.locals`, which can be accessed in server [hooks](/docs/kit/hooks) (`handle`, and `handleError`), server-only `load` functions, and `+server.js` files.
```dts
interface Locals {}
```
## PageData
Defines the common shape of the [page.data state](/docs/kit/$app-state#page) - that is, the data that is shared between all pages.
The `Load` and `ServerLoad` functions in `./$types` will be narrowed accordingly.
Use optional properties for data that is only present on specific pages. Do not add an index signature (`[key: string]: any`).
```dts
interface PageData {}
```
## PageState
The shape of the `page.state` object, which can be manipulated using [`goto`](/docs/kit/$app-navigation#goto).
```dts
interface PageState {}
```
## Platform
If your adapter provides [platform-specific context](/docs/kit/adapters#Platform-specific-context) via `event.platform`, you can specify it here.
```dts
interface Platform {}
```
# $service-worker
The `service-worker` module existed in SvelteKit 2, and provided access to the following exports:
## base
A root-relative path representing the application's base path. Use [`resolve(...)`]($app-paths#resolve) from `$app/paths` instead.
## build
A `string[]` array of files generated by Vite. Empty during development. Use [`immutable`]($app-manifest#immutable) from `$app/manifest` instead.
## files
A `string[]` array of files in your `static` directory. Use [`assets`]($app-manifest#assets) from `$app/manifest` instead.
## prerendered
A `string[]` array of prerendered pages. Empty during dev. Use [`prerendered`]($app-manifest#prerendered) from `$app/manifest` instead.
## version
The value of [`config.version.name`](@sveltejs-kit-vite#version), used for populating caches. Use [`version`]($app-env#version) from `$app/env` instead.
# $app/environment
This module was deprecated in SvelteKit 3 in favour of [$app/env]($app-env). It will be removed in SvelteKit 4.
# $app/stores
This module contained store-based equivalents of the exports from [`$app/state`]($app-state) but was removed in 3.0.
# $env/dynamic/private
This module was deprecated in SvelteKit 3 in favour of [explicit environment variables](environment-variables). It will be removed in SvelteKit 4.
# $env/dynamic/public
This module was deprecated in SvelteKit 3 in favour of [explicit environment variables](environment-variables). It will be removed in SvelteKit 4.
# $env/static/private
This module was deprecated in SvelteKit 3 in favour of [explicit environment variables](environment-variables). It will be removed in SvelteKit 4.
# $env/static/public
This module was deprecated in SvelteKit 3 in favour of [explicit environment variables](environment-variables). It will be removed in SvelteKit 4.
# Start of Svelte CLI documentation
# Overview
The command line interface (CLI), `sv`, is a toolkit for creating and maintaining Svelte applications.
## Usage
The easiest way to run `sv` is with [`npx`](https://docs.npmjs.com/cli/v8/commands/npx) (or the equivalent command if you're using a different package manager — for example, `pnpm dlx` if you're using [pnpm](https://pnpm.io/)):
```sh
npx sv
```
If you're inside a project where `sv` is already installed, this will use the local installation, otherwise it will download the latest version and run it without installing it, which is particularly useful for [`sv create`](sv-create).
## Acknowledgements
Thank you to [Christopher Brown](https://github.com/chbrown) who originally owned the `sv` name on npm for graciously allowing it to be used for the Svelte CLI. You can find the original `sv` package at [`@chbrown/sv`](https://www.npmjs.com/package/@chbrown/sv).
# Frequently asked questions
## How do I run the `sv` CLI?
Running `sv` looks slightly different for each package manager. Here is a list of the most common commands:
- **npm** : `npx sv create`
- **pnpm** : `pnpm dlx sv create`
- **Bun** : `bunx sv create`
- **Deno** : `deno run npm:sv create`
- **Yarn** : `yarn dlx sv create`
## `npx sv` is not working
Some package managers prefer to run locally installed tools instead of downloading and executing packages from the registry. This issue mostly occurs with `npm` and `yarn`. This usually results in an error message or looks like the command you were trying to execute did not do anything.
Here is a list of issues with possible solutions that users have encountered in the past:
- [`npx sv` create does nothing](https://github.com/sveltejs/cli/issues/472)
- [`sv` command name collides with `runit`](https://github.com/sveltejs/cli/issues/259)
- [`sv` in windows powershell conflicts with `Set-Variable`](https://github.com/sveltejs/cli/issues/317)
# sv create
`sv create` sets up a new SvelteKit project, with options to [setup additional functionality](sv-add#Official-add-ons).
## Usage
```sh
npx sv create [options] [path]
```
## Options
### `--from-playground `
Create a SvelteKit project from a [playground](/playground) URL. This downloads all playground files, detects external dependencies, and sets up a complete SvelteKit project structure with everything ready to go.
Example:
```sh
npx sv create --from-playground="https://svelte.dev/playground/hello-world"
```
### `--template `
Which project template to use:
- `minimal` — barebones scaffolding for your new app
- `demo` — showcase app with a word guessing game that works without JavaScript
- `library` — template for a Svelte library, set up with `svelte-package`
- `addon` — template for a community add-on, ready to be tested & published
### `--types `
Whether and how to add typechecking to the project:
- `ts` — default to `.ts` files and use `lang="ts"` for `.svelte` components
- `jsdoc` — use [JSDoc syntax](https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html) for types
### `--no-types`
Prevent typechecking from being added. Not recommended!
### `--add [add-ons...]`
Add add-ons to the project in the `create` command. Following the same format as [sv add](sv-add#Usage).
Example:
```sh
npx sv create --add eslint prettier [path]
```
### `--no-add-ons`
Run the command without the interactive add-ons prompt
### `--no-download-check`
Do not warn about downloads from community add-ons.
> Svelte maintainers have not reviewed community add-ons for malicious code! Use at your discretion.
### `--addon-name `
Specify the package name when creating an addon template. Accepts `@/` or ``. When omitted, you will be prompted for the name.
### `--install `
Installs dependencies with a specified package manager:
- `npm`
- `pnpm`
- `yarn`
- `bun`
- `deno`
### `--no-install`
Prevents installing dependencies.
### `--no-dir-check`
Skip checking whether the target directory is empty.
# sv add
`sv add` updates an existing project with new functionality.
## Usage
```sh
npx sv add
```
```sh
npx sv add [add-ons]
```
You can select multiple space-separated add-ons from [the list below](#Official-add-ons), or you can use the interactive prompt.
## Options
### `-C`, `--cwd`
Path to the root of your Svelte(Kit) project.
### `--no-git-check`
Do not warn about uncommitted changes.
### `--no-download-check`
Do not warn about downloads from community add-ons.
> Svelte maintainers have not reviewed community add-ons for malicious code! Use at your discretion.
### `--install `
Installs dependencies with a specified package manager:
- `npm`
- `pnpm`
- `yarn`
- `bun`
- `deno`
### `--no-install`
Do not prompt to install dependencies.
## Official add-ons
- [`ai-tools`](ai-tools)
- [`better-auth`](better-auth)
- [`drizzle`](drizzle)
- [`enhanced-img`](enhanced-img)
- [`eslint`](eslint)
- [`mdsvex`](mdsvex)
- [`paraglide`](paraglide)
- [`playwright`](playwright)
- [`prettier`](prettier)
- [`storybook`](storybook)
- [`sveltekit-adapter`](sveltekit-adapter)
- [`tailwindcss`](tailwind)
- [`vitest`](vitest)
## Community add-ons
> Svelte maintainers have not reviewed community add-ons for malicious code!
Community add-ons are npm packages published by the community. Look out for add-ons from your favourite libraries and tools. _(soon)_ Many developers are building `sv` add-ons to make their integrations a one-liner. You can find them on [npmx](https://www.npmx.dev/search?q=keyword:sv-add) by searching for the keyword: `sv-add`.
```sh
# Install a community addon-on
npx sv add my-addon
# Also works with org names
npx sv add @supacool/sv
# As a shorthand, packages named `sv` can be omitted
npx sv add @supacool
# Use a local add-on (for development or internal use)
npx sv add file:../path/to/my-addon
# Mix and match official and community add-ons
npx sv add eslint @supacool
# Also works when creating a new project directly
npx sv create --add eslint @supacool
```
> On Windows PowerShell, `@` is a special character that should be escaped with single quotes. For example: `npx sv add '@supacool'`.
Want to create your own? Check the [Add-on Docs](community).
# sv check
`sv check` finds errors and warnings in your project, such as:
- unused CSS
- accessibility hints
- JavaScript/TypeScript compiler errors
Requires Node 16 or later.
## Installation
You will need to have the `svelte-check` package installed in your project:
```sh
npm i -D svelte-check
```
## Usage
```sh
npx sv check
```
## Options
### `--workspace `
Path to your workspace. All subdirectories except `node_modules` and those listed in `--ignore` are checked.
### `--output `
How to display errors and warnings. See [machine-readable output](#Machine-readable-output).
- `human`
- `human-verbose`
- `machine`
- `machine-verbose`
### `--watch`
Keeps the process alive and watches for changes.
### `--preserveWatchOutput`
Prevents the screen from being cleared in watch mode.
### `--tsconfig `
Pass a path to a `tsconfig` or `jsconfig` file. The path can be relative to the workspace path or absolute. Doing this means that only files matched by the `files`/`include`/`exclude` pattern of the config file are diagnosed. It also means that errors from TypeScript and JavaScript files are reported. If not given, will traverse upwards from the project directory looking for the next `jsconfig`/`tsconfig.json` file.
### `--no-tsconfig`
Use this if you only want to check the Svelte files found in the current directory and below and ignore any `.js`/`.ts` files (they will not be type-checked)
### `--ignore `
Files/folders to ignore, relative to workspace root. Paths should be comma-separated and quoted. Example:
```sh
npx sv check --ignore "dist,build"
```
Only has an effect when used in conjunction with `--no-tsconfig`. When used in conjunction with `--tsconfig`, this will only have effect on the files watched, not on the files that are diagnosed, which is then determined by the `tsconfig.json`.
### `--fail-on-warnings`
If provided, warnings will cause `sv check` to exit with an error code.
### `--compiler-warnings `
A quoted, comma-separated list of `code:behaviour` pairs where `code` is a [compiler warning code](../svelte/compiler-warnings) and `behaviour` is either `ignore` or `error`:
```sh
npx sv check --compiler-warnings "css_unused_selector:ignore,a11y_missing_attribute:error"
```
### `--diagnostic-sources `
A quoted, comma-separated list of sources that should run diagnostics on your code. By default, all are active:
- `js` (includes TypeScript)
- `svelte`
- `css`
Example:
```sh
npx sv check --diagnostic-sources "js,svelte"
```
### `--threshold `
Filters the diagnostics:
- `warning` (default) — both errors and warnings are shown
- `error` — only errors are shown
## Troubleshooting
[See the language-tools documentation](https://github.com/sveltejs/language-tools/blob/master/docs/README.md) for more information on preprocessor setup and other troubleshooting.
## Machine-readable output
Setting the `--output` to `machine` or `machine-verbose` will format output in a way that is easier to read
by machines, e.g. inside CI pipelines, for code quality checks, etc.
Each row corresponds to a new record. Rows are made up of columns that are separated by a
single space character. The first column of every row contains a timestamp in milliseconds
which can be used for monitoring purposes. The second column gives us the "row type", based
on which the number and types of subsequent columns may differ.
The first row is of type `START` and contains the workspace folder (wrapped in quotes). Example:
```
1590680325583 START "/home/user/language-tools/packages/language-server/test/plugins/typescript/testfiles"
```
Any number of `ERROR` or `WARNING` records may follow. Their structure is identical and depends on the output argument.
If the argument is `machine` it will tell us the filename, the starting line and column numbers, and the error message. The filename is relative to the workspace directory. The filename and the message are both wrapped in quotes. Example:
```
1590680326283 ERROR "codeactions.svelte" 1:16 "Cannot find module 'blubb' or its corresponding type declarations."
1590680326778 WARNING "imported-file.svelte" 0:37 "Component has unused export property 'prop'. If it is for external reference only, please consider using `export const prop`"
```
If the argument is `machine-verbose` it will tell us the filename, the starting line and column numbers, the ending line and column numbers, the error message, the code of diagnostic, the human-friendly description of the code and the human-friendly source of the diagnostic (eg. svelte/typescript). The filename is relative to the workspace directory. Each diagnostic is represented as an [ndjson](https://en.wikipedia.org/wiki/JSON_streaming#Newline-Delimited_JSON) line prefixed by the timestamp of the log. Example:
```
1590680326283 {"type":"ERROR","fn":"codeaction.svelte","start":{"line":1,"character":16},"end":{"line":1,"character":23},"message":"Cannot find module 'blubb' or its corresponding type declarations.","code":2307,"source":"js"}
1590680326778 {"type":"WARNING","filename":"imported-file.svelte","start":{"line":0,"character":37},"end":{"line":0,"character":51},"message":"Component has unused export property 'prop'. If it is for external reference only, please consider using `export
const prop`","code":"unused-export-let","source":"svelte"}
```
The output concludes with a `COMPLETED` message that summarizes total numbers of files, errors and warnings that were encountered during the check. Example:
```
1590680326807 COMPLETED 20 FILES 21 ERRORS 1 WARNINGS 3 FILES_WITH_PROBLEMS
```
If the application experiences a runtime error, this error will appear as a `FAILURE` record. Example:
```
1590680328921 FAILURE "Connection closed"
```
## Credits
- Vue's [VTI](https://github.com/vuejs/vetur/tree/master/vti) which laid the foundation for `svelte-check`
## FAQ
### Why is there no option to only check specific files (for example only staged files)?
`svelte-check` needs to 'see' the whole project for checks to be valid. Suppose you renamed a component prop but didn't update any of the places where the prop is used — the usage sites are all errors now, but you would miss them if checks only ran on changed files.
# sv migrate
`sv migrate` migrates Svelte and SvelteKit codebases. Newer migrations use the task-based migration system in `sv`. Legacy migrations are delegated to [`svelte-migrate@1`](https://www.npmjs.com/package/svelte-migrate) and are kept available for older projects, but no longer receive updates.
Before migrating, make sure the project is committed and read the migration's linked changelog or migration guide. Migration code cannot account for every application, so review the resulting diff and run your project's checks after every step.
## Usage
```sh
npx sv migrate
```
When no migration is specified, `sv migrate` prompts you to pick one.
You can also specify a migration directly via the CLI:
```sh
npx sv migrate [migration]
```
For task-based migrations, `sv migrate` shows the migration tasks before applying them. Prerequisite tasks always run, and the remaining tasks can be selected interactively or with `--tasks`.
To make migration changes easier to review, run one selectable task at a time and commit the result before starting the next one. The task system is intended to create focused commits, not independent migration paths. Do not expect a project to work after running only a few tasks. Most projects need all applicable tasks before the migration is complete.
After a successful task-based migration, `sv` formats the changes using the project's `format` or `fmt` script when one exists, otherwise it formats changed files with Prettier when available. It then prompts to install updated dependencies. Some transformations leave `@migration-task` comments where manual work is required; search the project for that exact marker before considering the migration complete.
## Task-based migrations
### `sveltekit-3`
Upgrades a SvelteKit 2 app to SvelteKit 3. Read the [SvelteKit 3 changelog](https://github.com/sveltejs/kit/blob/main/packages/kit/CHANGELOG.md#300) before running it.
The migration is divided into these tasks:
- `package-json` (prerequisite) updates package versions for SvelteKit 3.
- `tsconfig` (prerequisite) extends the generated `$app/tsconfig` instead of `.svelte-kit/tsconfig.json`.
- `svelte-config` moves supported configuration from `svelte.config.*` into `vite.config.*` and updates imports of the old config where possible.
- `environment` replaces legacy environment modules with `$app/env` and creates `src/env.js` or `src/env.ts` declarations when needed.
- `paths` migrates deprecated `$app/paths` APIs and path types.
- `external-redirects` opts external redirects into the new redirect behavior.
- `shallow-routing` replaces shallow-routing APIs with `goto` calls.
- `params` consolidates route parameter matchers into `src/params.js` or `src/params.ts`.
- `app-state` migrates `$app/stores` usage to `$app/state`.
The migration only changes patterns it can identify safely. Review `@migration-task` comments and the SvelteKit 3 changelog for changes that require manual work.
### `app-state`
Migrates `$app/stores` usage to `$app/state` in `.svelte` files. See the [migration guide](/docs/kit/migrating-to-sveltekit-2#SvelteKit-2.12:-$app-stores-deprecated) for more details.
## Legacy migrations
The migrations below run through `svelte-migrate@1`. They remain available so older projects can move forward, but they no longer receive fixes or support for newly discovered code patterns. Commit your project first and carefully review their output.
### `svelte-5`
Upgrades a Svelte 4 app to use Svelte 5, and updates individual components to use [runes](../svelte/what-are-runes) and other Svelte 5 syntax ([see migration guide](../svelte/v5-migration-guide)).
### `self-closing-tags`
Replaces all the self-closing non-void elements in your `.svelte` files. See the [pull request](https://github.com/sveltejs/kit/pull/12128) for more details.
### `svelte-4`
Upgrades a Svelte 3 app to use Svelte 4 ([see migration guide](../svelte/v4-migration-guide)).
### `sveltekit-2`
Upgrades a SvelteKit 1 app to SvelteKit 2 ([see migration guide](../kit/migrating-to-sveltekit-2)).
### `package`
Upgrades a library using `@sveltejs/package` version 1 to version 2. See the [pull request](https://github.com/sveltejs/kit/pull/8922) for more details.
### `routes`
Upgrades a pre-release SvelteKit app to use the filesystem routing conventions in SvelteKit 1. See the [pull request](https://github.com/sveltejs/kit/discussions/5774) for more details.
## Options
These options apply to both task-based and legacy migrations.
### `--cwd `
Run the migration in a different working directory. The path defaults to the current directory and must contain a `package.json`.
### `--no-git-check`
By default, `sv migrate` prompts before making changes when the git working tree is dirty. Use `--no-git-check` to skip this check.
### `--confirm`
Skip the final confirmation prompt before applying the migration. This does not skip migration selection or the dirty-working-tree check; provide the migration name and corresponding options for non-interactive use.
## Task-based migration options
These options do not apply to legacy migrations. Legacy migrations do not support task or file selection, and manage their own dependency installation behavior.
### `--files `
Limit the files saved by the migration to those matching a glob. This is an advanced escape hatch, not a way to run a complete migration on part of a project. Tasks often make related changes across configuration, source, and generated files; excluding any of them can leave imports, configuration, or types inconsistent and the project temporarily broken.
A task may still attempt to edit or create a file outside the glob. `sv migrate` does not save that file and reports it under **Unmodified files**. Review that list and rerun the relevant task without the filter, with a broader filter, or make the omitted changes manually.
When used with `--cwd`, the glob is relative to the working directory.
### `--tasks [task...]`
Select migration tasks without the interactive task prompt. Prerequisite tasks always run because they lay the foundation for the remaining tasks.
Use `--tasks` without any task IDs to print all available tasks for the migration without running them.
Use `--tasks all` to run every task, or `--tasks prerequisite` to run only the prerequisite tasks.
To keep changes reviewable, pass one task ID at a time, review and commit the result, then run the next task. Use `--tasks all` primarily for automation or when a single combined diff is intentional.
### `--install `
Install dependencies with a specified package manager:
- `npm`
- `pnpm`
- `yarn`
- `bun`
- `deno`
### `--no-install`
Skip installing dependencies after the migration.
# ai-tools
The [Svelte AI tools](/docs/ai/overview) can help your LLM write better Svelte code.
## Usage
```sh
npx sv add ai-tools
```
## What you get
You can add the tooling either through the official Svelte plugin or as individual tools.
- The Svelte plugin bundles everything (MCP server, [skills](https://svelte.dev/docs/ai/skills) and sub-agents) and keeps itself up to date. It's available for Claude Code and OpenCode. For Claude Code it's enabled through a committed `.claude/settings.json` - the first time you open the project you'll be asked to trust the workspace, then it installs automatically (no `/plugin install` needed).
- Individual tools, for clients without a plugin (or when you want to pick exactly what to add):
- An MCP configuration for [local](https://svelte.dev/docs/ai/local-setup) or [remote](https://svelte.dev/docs/ai/remote-setup) setup
- A [README for agents](https://agents.md/) to help you use the MCP server effectively
- [Skills](https://svelte.dev/docs/ai/skills) for clients that support them
- Sub-agents for clients that support them
## Options
### ide
The client(s) you want to use like `'claude-code'`, `'cursor'`, `'gemini'`, `'opencode'`, `'vscode'`, `'other'`.
```sh
npx sv add ai-tools="ide:cursor,vscode"
```
### delivery
How to add the tooling: `'plugin'` (the Svelte plugin, recommended) or `'tools'` (individual tools). Only asked when a selected client supports a plugin.
```sh
npx sv add ai-tools="ide:claude-code+delivery:plugin"
```
### tools
Which individual tools to add when not using the plugin, like `'mcp'`, `'svelte-code-writer'`, `'svelte-core-bestpractices'`, `'svelte-file-editor'`.
```sh
npx sv add ai-tools="ide:cursor+delivery:tools+tools:mcp,svelte-file-editor"
```
### mcpSetup
The MCP setup you want to use (`'local'` or `'remote'`). Only relevant when adding the MCP server as an individual tool.
```sh
npx sv add ai-tools="mcpSetup:local"
```
# better-auth
[Better Auth](https://www.better-auth.com/) is a framework-agnostic authentication library for TypeScript.
## Usage
```sh
npx sv add better-auth
```
## What you get
- a complete auth setup for SvelteKit with Drizzle as the database adapter
- email/password authentication enabled by default
- optional demo registration and login pages
## Options
### demo
Which demo pages to include. Available values: `password` (Email & Password), `github` (GitHub OAuth).
```sh
# Email & Password only (default)
npx sv add better-auth="demo:password"
# GitHub OAuth only
npx sv add better-auth="demo:github"
# Both Email & Password and GitHub OAuth
npx sv add better-auth="demo:password,github"
```
# drizzle
[Drizzle ORM](https://orm.drizzle.team/) is a TypeScript ORM offering both relational and SQL-like query APIs, and which is serverless-ready by design.
## Usage
```sh
npx sv add drizzle
```
## What you get
- a setup that keeps your database access in SvelteKit's server files
- an `.env` file to store your credentials
- compatibility with the Better Auth add-on
- an optional Docker configuration to help with running a local database
## Options
### database
Which database variant to use:
- `postgresql` — the most popular open source database
- `mysql` — another popular open source database
- `sqlite` — file-based database not requiring a database server
```sh
npx sv add drizzle="database:postgresql"
```
### client
The SQL client to use, depends on `database`:
- For `postgresql`: `postgres.js`, `neon`,
- For `mysql`: `mysql2`, `planetscale`
- For `sqlite`: `better-sqlite3`, `libsql`, `turso`
```sh
npx sv add drizzle="database:postgresql+client:postgres.js"
```
Drizzle is compatible with well over a dozen database drivers. We just offer a few of the most common ones here for simplicity, but if you'd like to use another one you can choose one as a placeholder and swap it out for another after setup by choosing from [Drizzle's full list of compatible drivers](https://orm.drizzle.team/docs/connect-overview#next-steps).
### docker
Whether to add Docker Compose configuration. Only available for [`database`](#Options-database) `postgresql` or `mysql`
```sh
npx sv add drizzle="database:postgresql+client:postgres.js+docker:yes"
```
# enhanced-img
[`@sveltejs/enhanced-img`](https://svelte.dev/docs/kit/images) serves smaller file formats like `avif` or `webp`, generates the right sizes for different devices, and sets `width` and `height` to avoid layout shift.
## Usage
```sh
npx sv add enhanced-img
```
## What you get
- the `enhancedImages` Vite plugin
- rewrite applicable ` ` tags to ``
- `sharp` added to the allowed builds when using pnpm
# eslint
[ESLint](https://eslint.org/) finds and fixes problems in your code.
## Usage
```sh
npx sv add eslint
```
## What you get
- the relevant packages installed including `eslint-plugin-svelte`
- an `eslint.config.js` file
- updated `.vscode/extensions.json`
- configured to work with TypeScript and `prettier` if you're using those packages
# experimental
Enables experimental Svelte and [SvelteKit](https://svelte.dev/docs/kit/configuration#experimental) features.
## Usage
```sh
npx sv add experimental
```
## What you get
- the selected experimental flags set in your config
## Options
### features
Which experimental flags to enable:
- `async` — `await` in components
- `remoteFunctions` — remote functions
- `forkPreloads` — forked preloading
```sh
npx sv add experimental="features:async,remoteFunctions"
```
# mdsvex
[mdsvex](https://mdsvex.pngwn.io) is a markdown preprocessor for Svelte components - basically MDX for Svelte. It allows you to use Svelte components in your markdown, or markdown in your Svelte components.
## Usage
```sh
npx sv add mdsvex
```
## What you get
- mdsvex installed and configured in your `svelte.config.js`
# paraglide
[Paraglide from Inlang](https://inlang.com/m/gerre34r/library-inlang-paraglideJs) is a compiler-based i18n library that emits tree-shakable message functions with small bundle sizes, no async waterfalls, full type-safety, and more.
## Usage
```sh
npx sv add paraglide
```
## What you get
- Inlang project settings
- paraglide Vite plugin
- SvelteKit `reroute` and `handle` hooks
- `text-direction` and `lang` attributes in `app.html`
- updated `.gitignore`
- an optional demo page showing how to use paraglide
## Options
### languageTags
The languages you'd like to support specified as IETF BCP 47 language tags.
```sh
npx sv add paraglide="languageTags:en,es"
```
### demo
Whether to generate an optional demo page showing how to use paraglide.
```sh
npx sv add paraglide="demo:yes"
```
# playwright
[Playwright](https://playwright.dev) browser testing.
## Usage
```sh
npx sv add playwright
```
## What you get
- scripts added in your `package.json`
- a Playwright config file
- an updated `.gitignore`
- a demo test
# prettier
[Prettier](https://prettier.io) is an opinionated code formatter.
## Usage
```sh
npx sv add prettier
```
## What you get
- scripts in your `package.json`
- `.prettierignore` and `.prettierrc` files
- updates to your eslint config if you're using that package
# storybook
[Storybook](https://storybook.js.org/) is a frontend component workshop.
## Usage
```sh
npx sv add storybook
```
## What you get
- `npx storybook init` run for you from the same convenient `sv` CLI used for all other add-ons
- [Storybook for SvelteKit](https://storybook.js.org/docs/get-started/frameworks/sveltekit) or [Storybook for Svelte & Vite](https://storybook.js.org/docs/get-started/frameworks/svelte-vite) with default config provided, easy mocking of many SvelteKit modules, automatic link handling, and more.
# sveltekit-adapter
[SvelteKit adapters](/docs/kit/adapters) allow you to deploy your site to numerous platforms. This add-on allows you to configure officially provided SvelteKit adapters, but a number of [community-provided adapters](https://www.sveltesociety.dev/packages?category=sveltekit-adapters) are also available.
## Usage
```sh
npx sv add sveltekit-adapter
```
## What you get
- the chosen SvelteKit adapter installed and configured in your `svelte.config.js`
## Options
### adapter
Which SvelteKit adapter to use:
- `auto` — [`@sveltejs/adapter-auto`](/docs/kit/adapter-auto) automatically chooses the proper adapter to use, but is less configurable
- `node` — [`@sveltejs/adapter-node`](/docs/kit/adapter-node) generates a standalone Node server
- `static` — [`@sveltejs/adapter-static`](/docs/kit/adapter-static) allows you to use SvelteKit as a static site generator (SSG)
- `vercel` — [`@sveltejs/adapter-vercel`](/docs/kit/adapter-vercel) allows you to deploy to Vercel
- `cloudflare` — [`@sveltejs/adapter-cloudflare`](/docs/kit/adapter-cloudflare) allows you to deploy to Cloudflare
- `netlify` — [`@sveltejs/adapter-netlify`](/docs/kit/adapter-netlify) allows you to deploy to Netlify
```sh
npx sv add sveltekit-adapter="adapter:node"
```
### cloudflare target
Whether to deploy to Cloudflare Workers or Pages. Only available for `cloudflare` adapter.
```sh
npx sv add sveltekit-adapter="adapter:cloudflare+cfTarget:workers"
```
# tailwindcss
[Tailwind CSS](https://tailwindcss.com/) allows you to rapidly build modern websites without ever leaving your HTML.
## Usage
```sh
npx sv add tailwindcss
```
## What you get
- Tailwind setup following the [Tailwind for SvelteKit guide](https://tailwindcss.com/docs/installation/framework-guides/sveltekit)
- Tailwind Vite plugin
- updated `layout.css` and `+layout.svelte` (for SvelteKit) or `app.css` and `App.svelte` (for non-SvelteKit Vite apps)
- integration with `prettier` if using that package
## Options
### plugins
Which plugin to use:
- `typography` — [`@tailwindcss/typography`](https://github.com/tailwindlabs/tailwindcss-typography)
- `forms` — [`@tailwindcss/forms`](https://github.com/tailwindlabs/tailwindcss-forms)
```sh
npx sv add tailwindcss="plugins:typography"
```
# vitest
[Vitest](https://vitest.dev/) is a Vite-native testing framework.
## Usage
```sh
npx sv add vitest
```
## What you get
- the relevant packages installed and scripts added to your `package.json`
- client/server-aware testing setup for Svelte in your Vite config file
- demo tests
## Options
### usages
Which test types to use:
- `unit` — unit testing
- `component` — component testing
```sh
npx sv add vitest="usages:unit,component"
```
# [create your own]
This guide covers how to create, test, and publish community add-ons for the Svelte CLI.
## Quick start
The easiest way to create an add-on is by using the `addon` template:
```sh
npx sv create --template addon [path]
```
The newly created project will have a `README.md` and `CONTRIBUTING.md` to guide you along.
## Project structure
Typically, an add-on looks like this:
```js
import { transforms } from '@sveltejs/sv-utils';
import { defineAddon, defineAddonOptions } from 'sv';
export default defineAddon({
id: 'addon-name',
shortDescription: 'a better description of what your addon does ;)',
options: defineAddonOptions()
.add('who', {
question: 'To whom should the addon say hello?',
type: 'string' // boolean | number | select | multiselect
})
.build(),
setup: ({ dependsOn, isKit, unsupported, addOption }) => {
if (!isKit) unsupported('Requires SvelteKit');
dependsOn('vitest');
// dynamically add options (e.g. based on workspace state or fetched data)
// addOption('key', { question: '...', type: 'boolean', default: true });
},
run: ({ isKit, cancel, sv, options, file, language, directory }) => {
// Add "Hello [who]!" to the root page
sv.file(
directory.kitRoutes + '/+page.svelte',
transforms.svelte(({ ast, svelte }) => {
svelte.addFragment(ast, `Hello ${options.who}!
`);
})
);
},
nextSteps: ({ options }) => ['enjoy the add-on!']
});
```
The CLI is split into two packages with a clear boundary:
- [**`sv`**](sv) = **where and when** to do it. It owns paths, workspace detection, dependency tracking, and file I/O. The engine orchestrates add-on execution.
- [**`@sveltejs/sv-utils`**](sv-utils) = **what** to do to content. It provides parsers, language tooling, and typed transforms. Everything here is pure - no file system, no workspace awareness.
This separation means transforms are testable without a workspace and composable across add-ons.
## Development
You can run your add-on locally using the `file:` protocol:
```sh
cd /path/to/test-project
npx sv add file:../path/to/my-addon
```
This allows you to iterate quickly without publishing to npm.
The `file:` protocol also works for custom or private add-ons that you don't intend to publish - for example, to standardize project setup across your team or organization.
> The `demo-add` script automatically builds your add-on before running it.
## Testing
The `sv/testing` module provides utilities for testing your add-on. `createSetupTest` is a factory that takes your vitest imports and returns a `setupTest` function. It creates real SvelteKit projects from templates, runs your add-on, and gives you access to the resulting files.
```js
import { expect } from '@playwright/test';
import fs from 'node:fs';
import path from 'node:path';
import { createSetupTest } from 'sv/testing';
import * as vitest from 'vitest';
import addon from './index.js';
const { test, testCases } = createSetupTest(vitest)(
{ addon },
{
kinds: [
{
type: 'default',
options: {
'your-addon-name': { who: 'World' }
}
}
],
filter: (testCase) => testCase.variant.includes('kit'),
browser: false
}
);
test.concurrent.for(testCases)('my-addon $kind.type $variant', async (testCase, ctx) => {
const cwd = ctx.cwd(testCase);
const page = fs.readFileSync(path.resolve(cwd, 'src/routes/+page.svelte'), 'utf8');
expect(page).toContain('Hello World!');
});
```
Your `vitest.config.js` must include the global setup from `sv/testing`:
```js
import { defineConfig } from 'vitest/config';
export default defineConfig({
test: {
include: ['tests/**/*.test.{js,ts}'],
globalSetup: ['tests/setup/global.js']
}
});
```
And the global test setup script `tests/setup/global.js`:
```js
import path from 'node:path';
import { setupGlobal } from 'sv/testing';
// test projects are scaffolded into `/.test-output`
const TEST_DIR = path.resolve(import.meta.dirname, '..', '..', '.test-output');
export default setupGlobal({ TEST_DIR });
```
## Publishing
### Bundling
Community add-ons are bundled with [tsdown](https://tsdown.dev/) into a single file. Everything is bundled except `sv`. (It is a peer dependency provided at runtime.)
`sv` ships its own copy of [`@sveltejs/sv-utils`](sv-utils), so an add-on that leaves it unbundled will still load. Nothing verifies the version: your add-on runs against whatever `sv` provides, and following its breaking changes is up to you. Bundle it to stay on a version you control.
### `package.json`
Your add-on must have `sv` as a peer dependency. Any `dependencies` declared will **not** be available at runtime, everything must be bundled:
```jsonc
{
"name": "@my-org/sv",
"version": "1.0.0",
"type": "module",
// bundled entry point (tsdown outputs .mjs for ESM)
"exports": {
".": { "default": "./dist/index.mjs" }
},
"publishConfig": {
"access": "public"
},
// packages declared here will not be available during runtime, it must be bundled
"dependencies": {},
"peerDependencies": {
// minimum version required to run by this add-on
"sv": "^0.13.0"
},
// Add the "sv-add" keyword so users can discover your add-on with https://www.npmx.dev/search?q=keyword:sv-add
"keywords": ["sv-add", "svelte", "sveltekit"]
}
```
### Package names
Naming follows the same [restrictions](https://npmx.dev/package/validate-npm-package-name#user-content-naming-rules) as on npm:
```sh
npx sv add my-addon
npx sv add @my-org/sv
npx sv add @my-org/foo
```
An add-on published as `@/sv` can also be installed as `@`. The following all resolve to the same package:
```sh
npx sv add @my-org
npx sv add @my-org/sv
npx sv add @my-org/sv@latest
```
For a specific version, append `@`:
```sh
npx sv add @my-org/sv@1.2.3
npx sv add my-addon@1.2.3
```
### Entry points
The CLI looks for `./sv` first. If that is not found, it defaults to the `.` entry point. This means you have two options:
1. **Default export** (for a dedicated add-on package):
```json
{
"name": "@my-org/sveltekit-addon",
"exports": {
".": "./dist/addon.mjs"
}
}
```
2. **`./sv` export** (for packages that also export other functionality):
```json
{
"name": "@my-org/sveltekit-addon",
"exports": {
".": "./dist/main.mjs",
"./sv": "./dist/addon.mjs"
}
}
```
### Publish to npm
```sh
npm login
npm publish
```
> `prepublishOnly` automatically runs the build before publishing.
## Next steps
You can optionally display guidance in the console after your add-on runs:
```js
import { color } from '@sveltejs/sv-utils';
export default defineAddon({
// ...
nextSteps: ({ options }) => [
`Run ${color.command('npm run dev')} to start developing`,
`Check out the docs at https://...`
]
});
```
## Version compatibility
Your add-on should specify a minimum `sv` version in `peerDependencies`. Your users will get a compatibility warning if their `sv` version has a different major version than what was specified.
## Examples
See the [official add-on source code](https://github.com/sveltejs/cli/tree/main/packages/sv/src/addons) for some real world examples.
# sv
`sv` exposes a programmatic API for creating projects and running add-ons.
## `defineAddon`
Creates an add-on definition. See [create your own](community) for a full guide.
```js
import { transforms } from '@sveltejs/sv-utils';
import { defineAddon, defineAddonOptions } from 'sv';
export default defineAddon({
id: 'my-addon',
options: defineAddonOptions().build(),
// called before run - declare dependencies, environment requirements, and dynamic options
setup: ({ dependsOn, unsupported, addOption, isKit }) => {
if (!isKit) unsupported('Requires SvelteKit');
dependsOn('eslint');
// dynamically add options based on workspace state or fetched data
addOption('theme', {
question: 'Which theme?',
type: 'select',
default: 'dark',
options: [{ value: 'dark' }, { value: 'light' }]
});
},
// the actual work — add files, edit files, declare dependencies
run: ({ sv, options, cancel }) => {
// add a dependency
sv.devDependency('my-lib', '^1.0.0');
// create or edit files using transforms from @sveltejs/sv-utils
sv.file('src/lib/foo.ts', (content) => {
return 'export const foo = true;';
});
// remove a file (respects the migration file filter)
sv.removeFile('src/lib/obsolete.ts');
// edit multiple existing files
sv.files(
{
include: 'src/**/*.{js,ts,svelte}',
exclude: 'src/**/+layout.{js,ts,svelte}',
where: (content) => content.includes('old-value')
},
(content, path) => content.replaceAll('old-value', 'new-value')
);
sv.file(
'src/routes/+page.svelte',
transforms.svelte(({ ast, svelte }) => {
svelte.addFragment(ast, 'Hello!
');
})
);
// cancel at any point if something is wrong
// cancel('reason');
},
// displayed after the add-on runs
nextSteps: ({ options }) => ['Run `npm run dev` to get started']
});
```
The `sv` object in `run` provides `file`, `files`, `removeFile`, `dependency`, `devDependency`, and `execute`. For file transforms (AST-based editing of scripts, Svelte components, CSS, JSON, etc.) and package manager helpers, see [`@sveltejs/sv-utils`](sv-utils).
### Typed dynamic options
If your add-on adds options dynamically in `setup` (e.g. from a fetch), you can pass a type parameter to `defineAddon` to get strong typing for those options:
```ts
import { defineAddon, defineAddonOptions } from 'sv';
// ---cut---
const addon = defineAddon<{ theme: string }>()({
id: 'my-addon',
options: defineAddonOptions().build(),
setup: ({ addOption }) => {
addOption('theme', {
question: 'Which theme?',
type: 'string',
default: 'dark'
});
},
run: ({ options }) => {
options.theme; // string
}
});
```
The type parameter maps value types (`boolean`, `string`, `number`) to question definitions. Without it, `defineAddon` stays strict and only allows statically defined options.
### Typed dynamic options
If your add-on adds options dynamically in `setup` (e.g. from a fetch), you can pass a type parameter to `defineAddon` to get strong typing for those options:
```ts
import { defineAddon, defineAddonOptions } from 'sv';
// ---cut---
const addon = defineAddon<{ theme: string }>()({
id: 'my-addon',
options: defineAddonOptions().build(),
setup: ({ addOption }) => {
addOption('theme', {
question: 'Which theme?',
type: 'string',
default: 'dark'
});
},
run: ({ options }) => {
options.theme; // string
}
});
```
The type parameter maps value types (`boolean`, `string`, `number`) to question definitions. Without it, `defineAddon` stays strict and only allows statically defined options.
### Typed dynamic options
If your add-on adds options dynamically in `setup` (e.g. from a fetch), you can pass a type parameter to `defineAddon` to get strong typing for those options:
```ts
import { defineAddon, defineAddonOptions } from 'sv';
// ---cut---
const addon = defineAddon<{ theme: string }>()({
id: 'my-addon',
options: defineAddonOptions().build(),
setup: ({ addOption }) => {
addOption('theme', {
question: 'Which theme?',
type: 'string',
default: 'dark'
});
},
run: ({ options }) => {
options.theme; // string
}
});
```
The type parameter maps value types (`boolean`, `string`, `number`) to question definitions. Without it, `defineAddon` stays strict and only allows statically defined options.
## `defineAddonOptions`
Builder for add-on options. Chained with `.add()` and finalized with `.build()`.
```js
import { defineAddonOptions } from 'sv';
const options = defineAddonOptions()
.add('database', {
question: 'Which database?',
type: 'select',
default: 'postgresql',
options: [{ value: 'postgresql' }, { value: 'mysql' }, { value: 'sqlite' }]
})
.add('docker', {
question: 'Add a docker-compose file?',
type: 'boolean',
default: false,
// only ask when database is not sqlite
condition: (opts) => opts.database !== 'sqlite'
})
.build();
```
Options are asked in order. The `condition` callback receives the answers collected so far — return `false` to skip the question (its value will be `undefined`).
## `create`
Programmatically create a new Svelte project.
```js
import { create } from 'sv';
create({
cwd: './my-app',
name: 'my-app',
template: 'minimal',
types: 'typescript'
});
```
## `add`
Programmatically run add-ons against an existing project.
```js
import { add, officialAddons } from 'sv';
await add({
cwd: './my-app',
addons: { prettier: officialAddons.prettier },
options: { prettier: {} },
packageManager: 'npm'
});
```
# sv-utils
`@sveltejs/sv-utils` is an add-on utility for parsing, transforming, and generating code..
```sh
npm install -D @sveltejs/sv-utils
```
## transforms
`transforms` is a collection of parser-aware functions that lets you modify the files via abstract syntax tree (AST). It accepts a callback function. The return value is designed to be be passed directly into `sv.file()`. The parser choice is baked into the transform type - you can't accidentally parse a vite config as Svelte because you never call a parser yourself.
Each transform injects relevant utilities into the callback, so you only need one import:
```js
import { transforms } from '@sveltejs/sv-utils';
transforms.script(/* ... */);
transforms.svelte(/* ... */);
// ...
```
### `transforms.script`
Transform a JavaScript/TypeScript file. The callback receives `{ ast, comments, content, js }`.
```js
// @noErrors
import { transforms } from '@sveltejs/sv-utils';
sv.file(
file.viteConfig,
transforms.script(({ ast, js }) => {
js.imports.addDefault(ast, { as: 'foo', from: 'foo' });
js.vite.addPlugin(ast, { code: 'foo()' });
})
);
```
### `transforms.svelte`
Transform a Svelte component. The callback receives `{ ast, content, svelte, js }`.
```js
// @noErrors
import { transforms } from '@sveltejs/sv-utils';
sv.file(
layoutPath,
transforms.svelte(({ ast, svelte }) => {
svelte.addFragment(ast, ' ');
})
);
```
### `transforms.svelteScript`
Transform a Svelte component with a `'
# Analyze a file
npx @sveltejs/mcp svelte-autofixer ./src/lib/Component.svelte
# Target Svelte 4
npx @sveltejs/mcp svelte-autofixer ./Component.svelte --svelte-version 4
```
**Important:** When passing code with runes (`$state`, `$derived`, etc.) via the terminal, escape the `$` character as `\$` to prevent shell variable substitution.
## Workflow
1. **Uncertain about syntax?** Run `list-sections` then `get-documentation` for relevant topics
2. **Reviewing/debugging?** Run `svelte-autofixer` on the code to detect issues
3. **Always validate** - Run `svelte-autofixer` before finalizing any Svelte component
````