`](../svelte/svelte-head). Guidance on how to write descriptive titles and descriptions, along with other suggestions on making content understandable by search engines, can be found on Google's [Lighthouse SEO audits](https://web.dev/lighthouse-seo/) documentation.### Sitemaps[Sitemaps](https://developers.google.com/search/docs/advanced/sitemaps/build-sitemap) help search engines prioritize pages within your site, particularly when you have a large amount of content. You can create a sitemap dynamically using an endpoint:```js/// file: src/routes/sitemap_xml/+server.jsexport async function GET() { return new Response( ` `.trim(), { headers: { 'Content-Type': 'application/xml' } } );}```### AMPAn unfortunate reality of modern web development is that it is sometimes necessary to create an [Accelerated Mobile Pages (AMP)](https://amp.dev/) version of your site. In SvelteKit this can be done by setting the [`inlineStyleThreshold`](configuration#inlineStyleThreshold) option...```js/// file: svelte.config.js/** @type {import('@sveltejs/kit').Config} */const config = { kit: { // since isn't // allowed, inline all styles inlineStyleThreshold: Infinity }};export default config;```...disabling `csr` in your root `+layout.js`/`+layout.server.js`...```js/// file: src/routes/+layout.server.jsexport const csr = false;```...adding `amp` to your `app_html````html...```...and transforming the HTML using `transformPageChunk` along with `transform` imported from `@sveltejs/amp`:```js/// file: src/hooks.server.jsimport * as amp from '@sveltejs/amp';/** @type {import('@sveltejs/kit').Handle} */export async function handle({ event, resolve }) { let buffer = ''; return await resolve(event, { transformPageChunk: ({ html, done }) => { buffer += html; if (done) return amp.transform(buffer); } });}```To prevent shipping any unused CSS as a result of transforming the page to amp, we can use [`dropcss`](https://www.npmjs.com/package/dropcss):```js// @filename: ambient.d.tsdeclare module 'dropcss';// @filename: index.js// ---cut---/// file: src/hooks.server.js// @errors: 2307import * as amp from '@sveltejs/amp';import dropcss from 'dropcss';/** @type {import('@sveltejs/kit').Handle} */export async function handle({ event, resolve }) { let buffer = ''; return await resolve(event, { transformPageChunk: ({ html, done }) => { buffer += html; if (done) { let css = ''; const markup = amp .transform(buffer) .replace('⚡', 'amp') // dropcss can't handle this character .replace(/`; }); css = dropcss({ css, html: markup }).css; return markup.replace('', `${css}`); } } });}```# @sveltejs/kit```js// @noErrorsimport { Server, VERSION, error, fail, isActionFailure, isHttpError, isRedirect, json, normalizeUrl, redirect, text} from '@sveltejs/kit';```## Server```dtsclass Server {/*…*/}```
```dtsconstructor(manifest: SSRManifest);```
```dtsinit(options: ServerInitOptions): Promise
;```
```dtsrespond(request: Request, options: RequestOptions): Promise
;```
## VERSION```dtsconst VERSION: string;```
## errorThrows an error with a HTTP status code and an optional message.When called during request handling, this will cause SvelteKit toreturn an error response without invoking `handleError`.Make sure you're not catching the thrown error, which would prevent SvelteKit from handling it.```dtsfunction error(status: number, body: App.Error): never;```
```dtsfunction error( status: number, body?: { message: string; } extends App.Error ? App.Error | string | undefined : never): never;```
## failCreate an `ActionFailure` object. Call when form submission fails.```dtsfunction fail(status: number): ActionFailure;```
```dtsfunction fail( status: number, data: T): ActionFailure;```
## isActionFailureChecks whether this is an action failure thrown by `fail`.```dtsfunction isActionFailure(e: unknown): e is ActionFailure;```
## isHttpErrorChecks whether this is an error thrown by `error`.```dtsfunction isHttpError( e: unknown, status?: T): e is HttpError_1 & { status: T extends undefined ? never : T;};```
## isRedirectChecks whether this is a redirect thrown by `redirect`.```dtsfunction isRedirect(e: unknown): e is Redirect_1;```
## jsonCreate a JSON `Response` object from the supplied data.```dtsfunction json(data: any, init?: ResponseInit): Response;```
## normalizeUrlAvailable since 2.18.0 Strips possible SvelteKit-internal suffixes and trailing slashes from the URL pathname.Returns the normalized URL as well as a method for adding the potential suffix backbased on a new pathname (possibly including search) or URL.```js// @errors: 7031import { normalizeUrl } from '@sveltejs/kit';const { url, denormalize } = normalizeUrl('/blog/post/__data.json');console.log(url.pathname); // /blog/postconsole.log(denormalize('/blog/post/a')); // /blog/post/a/__data.json``````dtsfunction normalizeUrl(url: URL | string): { url: URL; wasNormalized: boolean; denormalize: (url?: string | URL) => URL;};```
## redirectRedirect a request. When called during request handling, SvelteKit will return a redirect response.Make sure you're not catching the thrown redirect, which would prevent SvelteKit from handling it.Most common status codes: * `303 See Other`: redirect as a GET request (often used after a form POST request) * `307 Temporary Redirect`: redirect will keep the request method * `308 Permanent Redirect`: redirect will keep the request method, SEO will be transferred to the new page[See all redirect status codes](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#redirection_messages)```dtsfunction redirect( status: | 300 | 301 | 302 | 303 | 304 | 305 | 306 | 307 | 308 | ({} & number), location: string | URL): never;```
## textCreate a `Response` object from the supplied body.```dtsfunction text(body: string, init?: ResponseInit): Response;```
## ActionShape of a form action method that is part of `export const actions = {...}` in `+page.server.js`.See [form actions](/docs/kit/form-actions) for more information.```dtstype Action< Params extends AppLayoutParams<'/'> = AppLayoutParams<'/'>, OutputData extends Record
| void = Record< string, any > | void, RouteId extends AppRouteId | null = AppRouteId | null> = ( event: RequestEvent) => MaybePromise;``` ## ActionFailure```dtsinterface ActionFailure
{/*…*/}``````dts[uniqueSymbol]: true;```
## ActionResultWhen calling a form action via fetch, the response will be one of these shapes.```svelte`- `leave`: The app is being left either because the tab is being closed or a navigation to a different document is occurring- `link`: Navigation was triggered by a link click- `goto`: Navigation was triggered by a `goto(...)` call or a redirect- `popstate`: Navigation was triggered by back/forward navigation```dtstype NavigationType = | 'enter' | 'form' | 'leave' | 'link' | 'goto' | 'popstate';```
## NumericRange```dtstype NumericRange< TStart extends number, TEnd extends number> = Exclude, LessThan>;```
## OnNavigateThe argument passed to [`onNavigate`](/docs/kit/$app-navigation#onNavigate) callbacks.```dtstype OnNavigate = Navigation & { /** * The type of navigation: * - `form`: The user submitted a `
` * - `link`: Navigation was triggered by a link click * - `goto`: Navigation was triggered by a `goto(...)` call or a redirect * - `popstate`: Navigation was triggered by back/forward navigation */ type: Exclude; /** * Since `onNavigate` callbacks are called immediately before a client-side navigation, they will never be called with a navigation that unloads the page. */ willUnload: false;};``` ## PageThe shape of the [`page`](/docs/kit/$app-state#page) reactive object and the [`$page`](/docs/kit/$app-stores) store.```dtsinterface Page< Params extends AppLayoutParams<'/'> = AppLayoutParams<'/'>, RouteId extends AppRouteId | null = AppRouteId | null> {/*…*/}```
```dtsurl: URL & { pathname: ResolvedPathname };```
The URL of the current page.
```dtsparams: Params;```
The parameters of the current page - e.g. for a route like `/blog/[slug]`, a `{ slug: string }` object.
```dtsroute: {/*…*/}```
Info about the current route.
```dtsid: 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.
```dtsstatus: number;```
HTTP status code of the current page.
```dtserror: App.Error | null;```
The error object of the current page, if any. Filled from the `handleError` hooks.
```dtsdata: 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`.
```dtsstate: App.PageState;```
The page state, which can be manipulated using the [`pushState`](/docs/kit/$app-navigation#pushState) and [`replaceState`](/docs/kit/$app-navigation#replaceState) functions from `$app/navigation`.
```dtsform: any;```
Filled only after a form submission. See [form actions](/docs/kit/form-actions) for more info.
## ParamMatcherThe shape of a param matcher. See [matching](/docs/kit/advanced-routing#Matching) for more info.```dtstype ParamMatcher = (param: string) => boolean;```
## PrerenderOption```dtstype PrerenderOption = boolean | 'auto';```
## RedirectThe object returned by the [`redirect`](/docs/kit/@sveltejs-kit#redirect) function.```dtsinterface Redirect {/*…*/}```
```dtsstatus: 300 | 301 | 302 | 303 | 304 | 305 | 306 | 307 | 308;```
The [HTTP status code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#redirection_messages), in the range 300-308.
```dtslocation: string;```
The location to redirect to.
## RemoteCommandThe return value of a remote `command` function. See [Remote functions](/docs/kit/remote-functions#command) for full documentation.## RemoteFormThe return value of a remote `form` function. See [Remote functions](/docs/kit/remote-functions#form) for full documentation.## RemoteFormFieldForm field accessor type that provides name(), value(), and issues() methods```dtstype 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```dtstype RemoteFormFieldType = { [K in keyof InputTypeMap]: T extends InputTypeMap[K] ? K : never;}[keyof InputTypeMap];```
## RemoteFormFieldValue```dtstype RemoteFormFieldValue = | string | string[] | number | boolean | File | File[];```
## RemoteFormFieldsRecursive type to build form fields structure with proxy access```dtstype RemoteFormFields = WillRecurseIndefinitely extends true ? RecursiveFormFields : NonNullable extends | string | number | boolean | File ? RemoteFormField>: T extends string[] | File[] ? RemoteFormField & { [K in number]: RemoteFormField; } : T extends Array? RemoteFormFieldContainer & { [K in number]: RemoteFormFields; } : RemoteFormFieldContainer & { [K in keyof T]-?: RemoteFormFields; };```
## RemoteFormInput```dtsinterface RemoteFormInput {/*…*/}```
```dts[key: string]: MaybeArray
;```
## RemoteFormIssue```dtsinterface RemoteFormIssue {/*…*/}```
```dtsmessage: string;```
## RemotePrerenderFunctionThe return value of a remote `prerender` function. See [Remote functions](/docs/kit/remote-functions#prerender) for full documentation.```dtstype RemotePrerenderFunction = ( arg: Input) => RemoteResource;```
## RemoteQuery```dtstype 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 the value of a query. This is used with the `updates` method of a [command](https://svelte.dev/docs/kit/remote-functions#command-Updating-queries) or [enhanced form submission](https://svelte.dev/docs/kit/remote-functions#form-enhance) to provide optimistic updates. * * ```svelte * * * { * await submit().updates( * todos.withOverride((todos) => [...todos, { text: data.get('text') }]) * ); * })}> * * Add Todo * * ``` */ withOverride( update: (current: Awaited) => Awaited): RemoteQueryOverride;};```
## RemoteQueryFunctionThe return value of a remote `query` function. See [Remote functions](/docs/kit/remote-functions#query) for full documentation.```dtstype RemoteQueryFunction = ( arg: Input) => RemoteQuery;```
## RemoteQueryOverride```dtsinterface RemoteQueryOverride {/*…*/}```
```dtsrelease(): void;```
## RemoteResource```dtstype RemoteResource
= Promise> & { /** The error in case the query fails. Most often this is a [`HttpError`](https://svelte.dev/docs/kit/@sveltejs-kit#HttpError) but it isn't guaranteed to be. */ get error(): any; /** `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(): Awaited; ready: true; } );``` ## RequestEvent```dtsinterface RequestEvent< Params extends AppLayoutParams<'/'> = AppLayoutParams<'/'>, RouteId extends AppRouteId | null = AppRouteId | null> {/*…*/}```
```dtscookies: Cookies;```
Get or set cookies related to the current request
```dtsfetch: typeof fetch;```
`fetch` is equivalent to the [native `fetch` web API](https://developer.mozilla.org/en-US/docs/Web/API/fetch), with a few additional features:- It can be used to make credentialed requests on the server, as it inherits the `cookie` and `authorization` headers for the page request.- It can make relative requests on the server (ordinarily, `fetch` requires a URL with an origin when used in a server context).- Internal requests (e.g. for `+server.js` routes) go directly to the handler function when running on the server, without the overhead of an HTTP call.- During server-side rendering, the response will be captured and inlined into the rendered HTML by hooking into the `text` and `json` methods of the `Response` object. Note that headers will _not_ be serialized, unless explicitly included via [`filterSerializedResponseHeaders`](/docs/kit/hooks#Server-hooks-handle)- During hydration, the response will be read from the HTML, guaranteeing consistency and preventing an additional network request.You can learn more about making credentialed requests with cookies [here](/docs/kit/load#Cookies).
```dtsgetClientAddress: () => string;```
The client's IP address, set by the adapter.
```dtslocals: App.Locals;```
Contains custom data that was added to the request within the [`server handle hook`](/docs/kit/hooks#Server-hooks-handle).
```dtsparams: Params;```
The parameters of the current route - e.g. for a route like `/blog/[slug]`, a `{ slug: string }` object.
```dtsplatform: Readonly
| undefined;```Additional data made available through the adapter.
```dtsrequest: Request;```
The original request object.
```dtsroute: {/*…*/}```
Info about the current route.
```dtsid: 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.
```dtssetHeaders: (headers: Record
) => void;```If you need to set headers for the response, you can do so using the this method. This is useful if you want the page to be cached, for example:```js// @errors: 7031/// file: src/routes/blog/+page.jsexport async function load({ fetch, setHeaders }) { const url = `https://cms.example.com/articles.json`; const response = await fetch(url); setHeaders({ age: response.headers.get('age'), 'cache-control': response.headers.get('cache-control') }); return response.json();}```Setting the same header multiple times (even in separate `load` functions) is an error — you can only set a given header once.You cannot add a `set-cookie` header with `setHeaders` — use the [`cookies`](/docs/kit/@sveltejs-kit#Cookies) API instead.
```dtsurl: URL;```
The requested URL.
```dtsisDataRequest: boolean;```
`true` if the request comes from the client asking for `+page/layout.server.js` data. The `url` property will be stripped of the internal informationrelated to the data request in this case. Use this property instead if the distinction is important to you.
```dtsisSubRequest: boolean;```
`true` for `+server.js` calls coming from SvelteKit without the overhead of actually making an HTTP request. This happens when you make same-origin `fetch` requests on the server.
```dtstracing: {/*…*/}```
- available since v2.31.0
Access to spans for tracing. If tracing is not enabled, these spans will do nothing.
```dtsenabled: boolean;```
Whether tracing is enabled.
```dtsroot: Span;```
The root span for the request. This span is named `sveltekit.handle.root`.
```dtscurrent: Span;```
The span associated with the current `handle` hook, `load` function, or form action.
```dtsisRemoteRequest: boolean;```
`true` if the request comes from the client via a remote function. The `url` property will be stripped of the internal informationrelated to the data request in this case. Use this property instead if the distinction is important to you.
## RequestHandlerA `(event: RequestEvent) => Response` function exported from a `+server.js` file that corresponds to an HTTP verb (`GET`, `PUT`, `PATCH`, etc) and handles requests with that method.It receives `Params` as the first generic argument, which you can skip by using [generated types](/docs/kit/types#Generated-types) instead.```dtstype RequestHandler< Params extends AppLayoutParams<'/'> = AppLayoutParams<'/'>, RouteId extends AppRouteId | null = AppRouteId | null> = ( event: RequestEvent
) => MaybePromise;``` ## RerouteAvailable since 2.3.0 The [`reroute`](/docs/kit/hooks#Universal-hooks-reroute) hook allows you to modify the URL before it is used to determine which route to render.```dtstype Reroute = (event: { url: URL; fetch: typeof fetch;}) => MaybePromise;```
## ResolveOptions```dtsinterface ResolveOptions {/*…*/}```
```dtstransformPageChunk?: (input: { html: string; done: boolean }) => MaybePromise
;```- `input` the html chunk and the info if this is the last chunk
Applies custom transforms to HTML. If `done` is true, it's the final chunk. Chunks are not guaranteed to be well-formed HTML(they could include an element's opening tag but not its closing tag, for example)but they will always be split at sensible boundaries such as `%sveltekit.head%` or layout/page components.
```dtsfilterSerializedResponseHeaders?: (name: string, value: string) => boolean;```
- `name` header name- `value` header value
Determines which headers should be included in serialized responses when a `load` function loads a resource with `fetch`.By default, none will be included.
```dtspreload?: (input: { type: 'font' | 'css' | 'js' | 'asset'; path: string }) => boolean;```
- `input` the type of the file and its path
Determines what should be added to the `` tag to preload it.By default, `js` and `css` files will be preloaded.
## RouteDefinition```dtsinterface RouteDefinition
{/*…*/}``````dtsapi: { methods: Array
;};```
```dtspage: { methods: Array
>;};```
```dtspattern: RegExp;```
```dtsprerender: PrerenderOption;```
```dtssegments: RouteSegment[];```
## SSRManifest```dtsinterface SSRManifest {/*…*/}```
```dtsappPath: string;```
```dtsassets: Set
;```Static files from `kit.config.files.assets` and the service worker (if any).
```dtsmimeTypes: Record
;```
```dts_: {/*…*/}```
private fields
```dtsclient: NonNullable
;```
```dtsnodes: SSRNodeLoader[];```
```dtsremotes: Record
Promise>;```hashed filename -> import to that file
```dtsroutes: SSRRoute[];```
```dtsprerendered_routes: Set
;```
```dtsmatchers: () => Promise
>;```
```dtsserver_assets: Record
;```A `[file]: size` map of all assets imported by server code.
## ServerInitAvailable since 2.10.0 The [`init`](/docs/kit/hooks#Shared-hooks-init) will be invoked before the server responds to its first request```dtstype ServerInit = () => MaybePromise;```
## ServerInitOptions```dtsinterface ServerInitOptions {/*…*/}```
```dtsenv: Record
;```A map of environment variables.
```dtsread?: (file: string) => MaybePromise
;```A function that turns an asset filename into a `ReadableStream`. Required for the `read` export from `$app/server` to work.
## ServerLoadThe generic form of `PageServerLoad` and `LayoutServerLoad`. You should import those from `./$types` (see [generated types](/docs/kit/types#Generated-types))rather than using `ServerLoad` directly.```dtstype ServerLoad< Params extends AppLayoutParams<'/'> = AppLayoutParams<'/'>, ParentData extends Record
= Record< string, any >, OutputData extends Record | void = Record< string, any > | void, RouteId extends AppRouteId | null = AppRouteId | null> = ( event: ServerLoadEvent) => MaybePromise;``` ## ServerLoadEvent```dtsinterface ServerLoadEvent< Params extends AppLayoutParams<'/'> = AppLayoutParams<'/'>, ParentData extends Record
= Record< string, any >, RouteId extends AppRouteId | null = AppRouteId | null> extends RequestEvent {/*…*/}``````dtsparent: () => Promise
;````await parent()` returns data from parent `+layout.server.js` `load` functions.Be careful not to introduce accidental waterfalls when using `await parent()`. If for example you only want to merge parent data into the returned output, call it _after_ fetching your other data.
```dtsdepends: (...deps: string[]) => void;```
This function declares that the `load` function has a _dependency_ on one or more URLs or custom identifiers, which can subsequently be used with [`invalidate()`](/docs/kit/$app-navigation#invalidate) to cause `load` to rerun.Most of the time you won't need this, as `fetch` calls `depends` on your behalf — it's only necessary if you're using a custom API client that bypasses `fetch`.URLs can be absolute or relative to the page being loaded, and must be [encoded](https://developer.mozilla.org/en-US/docs/Glossary/percent-encoding).Custom identifiers have to be prefixed with one or more lowercase letters followed by a colon to conform to the [URI specification](https://www.rfc-editor.org/rfc/rfc3986_html).The following example shows how to use `depends` to register a dependency on a custom identifier, which is `invalidate`d after a button click, making the `load` function rerun.```js// @errors: 7031/// file: src/routes/+page.jslet count = 0;export async function load({ depends }) { depends('increase:count'); return { count: count++ };}``````html/// file: src/routes/+page.svelte
{data.count}
Increase Count ```
```dtsuntrack:
(fn: () => T) => T;```Use this function to opt out of dependency tracking for everything that is synchronously called within the callback. Example:```js// @errors: 7031/// file: src/routes/+page.jsexport async function load({ untrack, url }) { // Untrack url.pathname so that path changes don't trigger a rerun if (untrack(() => url.pathname === '/')) { return { message: 'Welcome!' }; }}```
```dtstracing: {/*…*/}```
- available since v2.31.0
Access to spans for tracing. If tracing is not enabled, these spans will do nothing.
```dtsenabled: boolean;```
Whether tracing is enabled.
```dtsroot: Span;```
The root span for the request. This span is named `sveltekit.handle.root`.
```dtscurrent: Span;```
The span associated with the current server `load` function.
## SnapshotThe type of `export const snapshot` exported from a page or layout component.```dtsinterface Snapshot
{/*…*/}``````dtscapture: () => T;```
```dtsrestore: (snapshot: T) => void;```
## SubmitFunction```dtstype SubmitFunction< Success extends | Record| undefined = Record, Failure extends | Record| undefined = Record> = (input: { action: URL; formData: FormData; formElement: HTMLFormElement; controller: AbortController; submitter: HTMLElement | null; cancel: () => void;}) => MaybePromise< | void | ((opts: { formData: FormData; formElement: HTMLFormElement; action: URL; result: ActionResult; /** * Call this to get the default behavior of a form submission response. * @param options Set `reset: false` if you don't want the `` values to be reset after a successful submission. * @param invalidateAll Set `invalidateAll: false` if you don't want the action to call `invalidateAll` after submission. */ update: (options?: { reset?: boolean; invalidateAll?: boolean; }) => Promise; }) => MaybePromise)>;```
## TransportAvailable since 2.11.0 The [`transport`](/docs/kit/hooks#Universal-hooks-transport) hook allows you to transport custom types across the server/client boundary.Each transporter has a pair of `encode` and `decode` functions. On the server, `encode` determines whether a value is an instance of the custom type and, if so, returns a non-falsy encoding of the value which can be an object or an array (or `false` otherwise).In the browser, `decode` turns the encoding back into an instance of the custom type.```tsimport type { Transport } from '@sveltejs/kit';declare class MyCustomType { data: any}// hooks.jsexport const transport: Transport = { MyCustomType: { encode: (value) => value instanceof MyCustomType && [value.data], decode: ([data]) => new MyCustomType(data) }};``````dtstype Transport = Record;```
## TransporterA member of the [`transport`](/docs/kit/hooks#Universal-hooks-transport) hook.```dtsinterface Transporter< T = any, U = Exclude< any, false | 0 | '' | null | undefined | typeof NaN >> {/*…*/}```
```dtsencode: (value: T) => false | U;```
```dtsdecode: (data: U) => T;```
## Private typesThe following are referenced by the public types documented above, but cannot be imported directly:## AdapterEntry```dtsinterface AdapterEntry {/*…*/}```
```dtsid: string;```
A string that uniquely identifies an HTTP service (e.g. serverless function) and is used for deduplication.For example, `/foo/a-[b]` and `/foo/[c]` are different routes, but would bothbe represented in a Netlify _redirects file as `/foo/:param`, so they share an ID
```dtsfilter(route: RouteDefinition): boolean;```
A function that compares the candidate route with the current route to determineif it should be grouped with the current route.Use cases:- Fallback pages: `/foo/[c]` is a fallback for `/foo/a-[b]`, and `/[...catchall]` is a fallback for all routes- Grouping routes that share a common `config`: `/foo` should be deployed to the edge, `/bar` and `/baz` should be deployed to a serverless function
```dtscomplete(entry: { generateManifest(opts: { relativePath: string }): string }): MaybePromise
;```A function that is invoked once the entry has been created. This is where youshould write the function to the filesystem and generate redirect manifests.
## Csp```dtsnamespace Csp { type ActionSource = 'strict-dynamic' | 'report-sample'; type BaseSource = | 'self' | 'unsafe-eval' | 'unsafe-hashes' | 'unsafe-inline' | 'wasm-unsafe-eval' | 'none'; type CryptoSource = `${'nonce' | 'sha256' | 'sha384' | 'sha512'}-${string}`; type FrameSource = | HostSource | SchemeSource | 'self' | 'none'; type HostNameScheme = `${string}.${string}` | 'localhost'; type HostSource = `${HostProtocolSchemes}${HostNameScheme}${PortScheme}`; type HostProtocolSchemes = `${string}://` | ''; type HttpDelineator = '/' | '?' | '#' | '\\'; type PortScheme = `:${number}` | '' | ':*'; type SchemeSource = | 'http:' | 'https:' | 'data:' | 'mediastream:' | 'blob:' | 'filesystem:'; type Source = | HostSource | SchemeSource | CryptoSource | BaseSource; type Sources = Source[];}```
## CspDirectives```dtsinterface CspDirectives {/*…*/}```
```dts'child-src'?: Csp.Sources;```
```dts'default-src'?: Array
;```
```dts'frame-src'?: Csp.Sources;```
```dts'worker-src'?: Csp.Sources;```
```dts'connect-src'?: Csp.Sources;```
```dts'font-src'?: Csp.Sources;```
```dts'img-src'?: Csp.Sources;```
```dts'manifest-src'?: Csp.Sources;```
```dts'media-src'?: Csp.Sources;```
```dts'object-src'?: Csp.Sources;```
```dts'prefetch-src'?: Csp.Sources;```
```dts'script-src'?: Array
;```
```dts'script-src-elem'?: Csp.Sources;```
```dts'script-src-attr'?: Csp.Sources;```
```dts'style-src'?: Array
;```
```dts'style-src-elem'?: Csp.Sources;```
```dts'style-src-attr'?: Csp.Sources;```
```dts'base-uri'?: Array
;```
```dtssandbox?: Array<| 'allow-downloads-without-user-activation'| 'allow-forms'| 'allow-modals'| 'allow-orientation-lock'| 'allow-pointer-lock'| 'allow-popups'| 'allow-popups-to-escape-sandbox'| 'allow-presentation'| 'allow-same-origin'| 'allow-scripts'| 'allow-storage-access-by-user-activation'| 'allow-top-navigation'| 'allow-top-navigation-by-user-activation'>;```
```dts'form-action'?: Array
;```
```dts'frame-ancestors'?: Array
;```
```dts'navigate-to'?: Array
;```
```dts'report-uri'?: string[];```
```dts'report-to'?: string[];```
```dts'require-trusted-types-for'?: Array<'script'>;```
```dts'trusted-types'?: Array<'none' | 'allow-duplicates' | '*' | string>;```
```dts'upgrade-insecure-requests'?: boolean;```
```dts'require-sri-for'?: Array<'script' | 'style' | 'script style'>;```
```dts'block-all-mixed-content'?: boolean;```
```dts'plugin-types'?: Array<`${string}/${string}` | 'none'>;```
```dtsreferrer?: Array<| 'no-referrer'| 'no-referrer-when-downgrade'| 'origin'| 'origin-when-cross-origin'| 'same-origin'| 'strict-origin'| 'strict-origin-when-cross-origin'| 'unsafe-url'| 'none'>;```
## HttpMethod```dtstype HttpMethod = | 'GET' | 'HEAD' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'OPTIONS';```
## Logger```dtsinterface Logger {/*…*/}```
```dts(msg: string): void;```
```dtssuccess(msg: string): void;```
```dtserror(msg: string): void;```
```dtswarn(msg: string): void;```
```dtsminor(msg: string): void;```
```dtsinfo(msg: string): void;```
## MaybePromise```dtstype MaybePromise = T | Promise;```
## PrerenderEntryGeneratorMismatchHandler```dtsinterface PrerenderEntryGeneratorMismatchHandler {/*…*/}```
```dts(details: { generatedFromId: string; entry: string; matchedId: string; message: string }): void;```
## PrerenderEntryGeneratorMismatchHandlerValue```dtstype PrerenderEntryGeneratorMismatchHandlerValue = | 'fail' | 'warn' | 'ignore' | PrerenderEntryGeneratorMismatchHandler;```
## PrerenderHttpErrorHandler```dtsinterface PrerenderHttpErrorHandler {/*…*/}```
```dts(details: {status: number;path: string;referrer: string | null;referenceType: 'linked' | 'fetched';message: string;}): void;```
## PrerenderHttpErrorHandlerValue```dtstype PrerenderHttpErrorHandlerValue = | 'fail' | 'warn' | 'ignore' | PrerenderHttpErrorHandler;```
## PrerenderMap```dtstype PrerenderMap = Map;```
## PrerenderMissingIdHandler```dtsinterface PrerenderMissingIdHandler {/*…*/}```
```dts(details: { path: string; id: string; referrers: string[]; message: string }): void;```
## PrerenderMissingIdHandlerValue```dtstype PrerenderMissingIdHandlerValue = | 'fail' | 'warn' | 'ignore' | PrerenderMissingIdHandler;```
## PrerenderOption```dtstype PrerenderOption = boolean | 'auto';```
## PrerenderUnseenRoutesHandler```dtsinterface PrerenderUnseenRoutesHandler {/*…*/}```
```dts(details: { routes: string[]; message: string }): void;```
## PrerenderUnseenRoutesHandlerValue```dtstype PrerenderUnseenRoutesHandlerValue = | 'fail' | 'warn' | 'ignore' | PrerenderUnseenRoutesHandler;```
## Prerendered```dtsinterface Prerendered {/*…*/}```
```dtspages: Map
;```A map of `path` to `{ file }` objects, where a path like `/foo` corresponds to `foo_html` and a path like `/bar/` corresponds to `bar/index_html`.
```dtsassets: Map
;```A map of `path` to `{ type }` objects.
```dtsredirects: Map
;```A map of redirects encountered during prerendering.
```dtspaths: string[];```
An array of prerendered paths (without trailing slashes, regardless of the trailingSlash config)
## RequestOptions```dtsinterface RequestOptions {/*…*/}```
```dtsgetClientAddress(): string;```
```dtsplatform?: App.Platform;```
## RouteSegment```dtsinterface RouteSegment {/*…*/}```
```dtscontent: string;```
```dtsdynamic: boolean;```
## TrailingSlash```dtstype TrailingSlash = 'never' | 'always' | 'ignore';```
# @sveltejs/kit/hooks```js// @noErrorsimport { sequence } from '@sveltejs/kit/hooks';```## sequenceA helper function for sequencing multiple `handle` calls in a middleware-like manner.The behavior for the `handle` options is as follows:- `transformPageChunk` is applied in reverse order and merged- `preload` is applied in forward order, the first option "wins" and no `preload` options after it are called- `filterSerializedResponseHeaders` behaves the same as `preload````js// @errors: 7031/// file: src/hooks.server.jsimport { 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; }, preload: () => { // this one wins as it's the first defined in the chain console.log('first preload'); return true; } }); 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; }, preload: () => { console.log('second preload'); return true; }, filterSerializedResponseHeaders: () => { // this one wins as it's the first defined in the chain console.log('second filterSerializedResponseHeaders'); return true; } }); console.log('second post-processing'); return result;}export const handle = sequence(first, second);```The example above would print:```first pre-processingfirst preloadsecond pre-processingsecond filterSerializedResponseHeaderssecond transformfirst transformsecond post-processingfirst post-processing``````dtsfunction sequence(...handlers: Handle[]): Handle;```
# @sveltejs/kit/node/polyfills```js// @noErrorsimport { installPolyfills } from '@sveltejs/kit/node/polyfills';```## installPolyfillsMake various web APIs available as globals:- `crypto`- `File````dtsfunction installPolyfills(): void;```
# @sveltejs/kit/node```js// @noErrorsimport { createReadableStream, getRequest, setResponse} from '@sveltejs/kit/node';```## createReadableStreamAvailable since 2.4.0 Converts a file on disk to a readable stream```dtsfunction createReadableStream(file: string): ReadableStream;```
## getRequest```dtsfunction getRequest({ request, base, bodySizeLimit}: { request: import('http').IncomingMessage; base: string; bodySizeLimit?: number;}): Promise;```
## setResponse```dtsfunction setResponse( res: import('http').ServerResponse, response: Response): Promise;```
# @sveltejs/kit/vite```js// @noErrorsimport { sveltekit } from '@sveltejs/kit/vite';```## sveltekitReturns the SvelteKit Vite plugins.```dtsfunction sveltekit(): Promise;```
# $app/environment```js// @noErrorsimport { browser, building, dev, version } from '$app/environment';```## browser`true` if the app is running in the browser.```dtsconst browser: boolean;```
## buildingSvelteKit analyses your app during the `build` step by running it. During this process, `building` is `true`. This also applies during prerendering.```dtsconst building: boolean;```
## devWhether the dev server is running. This is not guaranteed to correspond to `NODE_ENV` or `MODE`.```dtsconst dev: boolean;```
## versionThe value of `config.kit.version.name`.```dtsconst version: string;```
# $app/forms```js// @noErrorsimport { applyAction, deserialize, enhance } from '$app/forms';```## applyActionThis 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.```dtsfunction applyAction< Success extends Record | undefined, Failure extends Record | undefined>( result: import('@sveltejs/kit').ActionResult< Success, Failure >): Promise;```
## deserializeUse this function to deserialize the response from a form submission.Usage:```js// @errors: 7031import { deserialize } from '$app/forms';async function handleSubmit(event) { const response = await fetch('/form?/action', { method: 'POST', body: new FormData(event.target) }); const result = deserialize(await response.text()); // ...}``````dtsfunction deserialize< Success extends Record | undefined, Failure extends Record | undefined>( result: string): import('@sveltejs/kit').ActionResult;```
## enhanceThis action enhances a `` element that otherwise would work without JavaScript.The `submit` function is 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 on the same page as the form- updates `page.status`- resets the ` ` element and 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 errorIf you provide a custom function with a callback and want to use the default behavior, invoke `update` in your callback.It accepts an options object- `reset: false` if you don't want the ` ` values to be reset after a successful submission- `invalidateAll: false` if you don't want the action to call `invalidateAll` after submission```dtsfunction enhance< Success extends Record | undefined, Failure extends Record | undefined>( form_element: HTMLFormElement, submit?: import('@sveltejs/kit').SubmitFunction< Success, Failure >): { destroy(): void;};```
# $app/navigation```js// @noErrorsimport { afterNavigate, beforeNavigate, disableScrollHandling, goto, invalidate, invalidateAll, onNavigate, preloadCode, preloadData, pushState, refreshAll, replaceState} from '$app/navigation';```## afterNavigateA lifecycle function that runs the supplied `callback` when the current component mounts, and also whenever we navigate to a URL.`afterNavigate` must be called during a component initialization. It remains active as long as the component is mounted.```dtsfunction afterNavigate( callback: ( navigation: import('@sveltejs/kit').AfterNavigate ) => void): void;```
## beforeNavigateA navigation interceptor that triggers before we navigate to a URL, whether by clicking a link, calling `goto(...)`, or using the browser back/forward controls.Calling `cancel()` will prevent the navigation from completing. If `navigation.type === 'leave'` — meaning the user is navigating away from the app (or closing the tab) — calling `cancel` will trigger the native browser unload confirmation dialog. In this case, the navigation may or may not be cancelled depending on the user's response.When a navigation isn't to a SvelteKit-owned route (and therefore controlled by SvelteKit's client-side router), `navigation.to.route.id` will be `null`.If the navigation will (if not cancelled) cause the document to unload — in other words `'leave'` navigations and `'link'` navigations where `navigation.to.route === null` — `navigation.willUnload` is `true`.`beforeNavigate` must be called during a component initialization. It remains active as long as the component is mounted.```dtsfunction beforeNavigate( callback: ( navigation: import('@sveltejs/kit').BeforeNavigate ) => void): void;```
## disableScrollHandlingIf 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.```dtsfunction disableScrollHandling(): void;```
## gotoAllows you to navigate programmatically to a given route, with options such as keeping the current element focused.Returns a Promise that resolves when SvelteKit navigates (or fails to navigate, in which case the promise rejects) to the specified `url`.For external URLs, use `window.location = url` instead of calling `goto(url)`.```dtsfunction goto( url: string | URL, opts?: { replaceState?: boolean | undefined; noScroll?: boolean | undefined; keepFocus?: boolean | undefined; invalidateAll?: boolean | undefined; invalidate?: | (string | URL | ((url: URL) => boolean))[] | undefined; state?: App.PageState | undefined; }): Promise;```
## invalidateCauses 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.```ts// Example: Match '/path' regardless of the query parametersimport { invalidate } from '$app/navigation';invalidate((url) => url.pathname === '/path');``````dtsfunction invalidate( resource: string | URL | ((url: URL) => boolean)): Promise;```
## invalidateAllCauses all `load` functions belonging to the currently active page to re-run. Returns a `Promise` that resolves when the page is subsequently updated.```dtsfunction invalidateAll(): Promise;```
## onNavigateA lifecycle function that runs the supplied `callback` immediately before we navigate to a new URL except during full-page navigations.If you return a `Promise`, SvelteKit will wait for it to resolve before completing the navigation. This allows you to — for example — use `document.startViewTransition`. Avoid promises that are slow to resolve, since navigation will appear stalled to the user.If a function (or a `Promise` that resolves to a function) is returned from the callback, it will be called once the DOM has updated.`onNavigate` must be called during a component initialization. It remains active as long as the component is mounted.```dtsfunction onNavigate( callback: ( navigation: import('@sveltejs/kit').OnNavigate ) => MaybePromise<(() => void) | void>): void;```
## preloadCodeProgrammatically imports the code for routes that haven't yet been fetched.Typically, you might call this to speed up subsequent navigation.You can specify routes by any matching pathname such as `/about` (to match `src/routes/about/+page.svelte`) or `/blog/*` (to match `src/routes/blog/[slug]/+page.svelte`).Unlike `preloadData`, this won't call `load` functions.Returns a Promise that resolves when the modules have been imported.```dtsfunction preloadCode(pathname: string): Promise;```
## preloadDataProgrammatically preloads 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 `` element with `data-sveltekit-preload-data`.If the next navigation is to `href`, the values returned from load will be used, making navigation instantaneous.Returns a Promise that resolves with the result of running the new route's `load` functions once the preload is complete.```dtsfunction preloadData(href: string): Promise< | { type: 'loaded'; status: number; data: Record; } | { type: 'redirect'; location: string; }>;```
## pushStateProgrammatically create a new history entry with the given `page.state`. To use the current URL, you can pass `''` as the first argument. Used for [shallow routing](/docs/kit/shallow-routing).```dtsfunction pushState( url: string | URL, state: App.PageState): void;```
## refreshAllCauses all currently active remote functions to refresh, and all `load` functions belonging to the currently active page to re-run (unless disabled via the option argument).Returns a `Promise` that resolves when the page is subsequently updated.```dtsfunction refreshAll({ includeLoadFunctions}?: { includeLoadFunctions?: boolean;}): Promise;```
## replaceStateProgrammatically replace the current history entry with the given `page.state`. To use the current URL, you can pass `''` as the first argument. Used for [shallow routing](/docs/kit/shallow-routing).```dtsfunction replaceState( url: string | URL, state: App.PageState): void;```
# $app/paths```js// @noErrorsimport { asset, assets, base, resolve, resolveRoute } from '$app/paths';```## assetAvailable since 2.26 Resolve the URL of an asset in your `static` directory, by prefixing it with [`config.kit.paths.assets`](/docs/kit/configuration#paths) if configured, or otherwise by prefixing it with the base path.During server rendering, the base path is relative and depends on the page currently being rendered.```svelte ``````dtsfunction asset(file: Asset): string;```
## assetsUse [`asset(...)`](/docs/kit/$app-paths#asset) instead An absolute path that matches [`config.kit.paths.assets`](/docs/kit/configuration#paths).```dtslet assets: | '' | `https://${string}` | `http://${string}` | '/_svelte_kit_assets';```
## baseUse [`resolve(...)`](/docs/kit/$app-paths#resolve) instead A string that matches [`config.kit.paths.base`](/docs/kit/configuration#paths).Example usage: ` Link ````dtslet base: '' | `/${string}`;```
## resolveAvailable since 2.26 Resolve a pathname by prefixing it with the base path, if any, or resolve a route ID by populating dynamic segments with parameters.During server rendering, the base path is relative and depends on the page currently being rendered.```js// @errors: 7031import { resolve } from '$app/paths';// using a pathnameconst resolved = resolve(`/blog/hello-world`);// using a route ID plus parametersconst resolved = resolve('/blog/[slug]', { slug: 'hello-world'});``````dtsfunction resolve( ...args: ResolveArgs): ResolvedPathname;```
## resolveRouteUse [`resolve(...)`](/docs/kit/$app-paths#resolve) instead ```dtsfunction resolveRoute( ...args: ResolveArgs): ResolvedPathname;```
# $app/server```js// @noErrorsimport { command, form, getRequestEvent, prerender, query, read} from '$app/server';```## commandAvailable since 2.27 Creates a remote command. When called from the browser, the function will be invoked on the server via a `fetch` call.See [Remote functions](/docs/kit/remote-functions#command) for full documentation.```dtsfunction command( fn: () => Output): RemoteCommand;```
```dtsfunction command ( validate: 'unchecked', fn: (arg: Input) => Output): RemoteCommand ;```
```dtsfunction command( validate: Schema, fn: (arg: StandardSchemaV1.InferOutput) => Output): RemoteCommand< StandardSchemaV1.InferInput, Output>;```
## formAvailable since 2.27 Creates a form object that can be spread onto a ` ` element.See [Remote functions](/docs/kit/remote-functions#form) for full documentation.```dtsfunction form( fn: ( invalid: import('@sveltejs/kit').Invalid) => MaybePromise): RemoteForm;```
```dtsfunction form ( validate: 'unchecked', fn: ( data: Input, invalid: import('@sveltejs/kit').Invalid ) => MaybePromise): RemoteForm ;```
```dtsfunction form< Schema extends StandardSchemaV1< RemoteFormInput, Record>, Output>( validate: Schema, fn: ( data: StandardSchemaV1.InferOutput, invalid: import('@sveltejs/kit').Invalid< StandardSchemaV1.InferInput>) => MaybePromise): RemoteForm, Output>;```
## getRequestEventAvailable since 2.20.0 Returns the current `RequestEvent`. Can be used inside server hooks, server `load` functions, actions, and endpoints (and functions called by them).In environments without [`AsyncLocalStorage`](https://nodejs.org/api/async_context_html#class-asynclocalstorage), this must be called synchronously (i.e. not after an `await`).```dtsfunction getRequestEvent(): RequestEvent;```
## prerenderAvailable since 2.27 Creates a remote prerender function. When called from the browser, the function will be invoked on the server via a `fetch` call.See [Remote functions](/docs/kit/remote-functions#prerender) for full documentation.```dtsfunction prerender( fn: () => MaybePromise, options?: | { inputs?: RemotePrerenderInputsGenerator; dynamic?: boolean; } | undefined): RemotePrerenderFunction;```
```dtsfunction prerender ( validate: 'unchecked', fn: (arg: Input) => MaybePromise, options?: | { inputs?: RemotePrerenderInputsGenerator ; dynamic?: boolean; } | undefined): RemotePrerenderFunction ;```
```dtsfunction prerender( schema: Schema, fn: ( arg: StandardSchemaV1.InferOutput) => MaybePromise, options?: | { inputs?: RemotePrerenderInputsGenerator< StandardSchemaV1.InferInput>; dynamic?: boolean; } | undefined): RemotePrerenderFunction< StandardSchemaV1.InferInput, Output>;```
## queryAvailable since 2.27 Creates a remote query. When called from the browser, the function will be invoked on the server via a `fetch` call.See [Remote functions](/docs/kit/remote-functions#query) for full documentation.```dtsfunction query( fn: () => MaybePromise): RemoteQueryFunction;```
```dtsfunction query ( validate: 'unchecked', fn: (arg: Input) => MaybePromise): RemoteQueryFunction ;```
```dtsfunction query( schema: Schema, fn: ( arg: StandardSchemaV1.InferOutput) => MaybePromise): RemoteQueryFunction< StandardSchemaV1.InferInput, Output>;```
## readAvailable since 2.4.0 Read the contents of an imported asset from the filesystem```js// @errors: 7031import { read } from '$app/server';import somefile from './somefile.txt';const asset = read(somefile);const text = await asset.text();``````dtsfunction read(asset: string): Response;```
## query```dtsnamespace 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 >;}```
# $app/stateSvelteKit makes three read-only state objects available via the `$app/state` module — `page`, `navigating` and `updated`.> This module was added in 2.12. If you're using an earlier version of SvelteKit, use [`$app/stores`]($app-stores) instead.```js// @noErrorsimport { navigating, page, updated } from '$app/state';```## navigatingA 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.```dtsconst navigating: | import('@sveltejs/kit').Navigation | { from: null; to: null; type: null; willUnload: null; delta: null; complete: null; };```
## pageA 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`, `pushState` or `replaceState` (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, and whether or not there was an error```svelteCurrently 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.```dtsconst page: import('@sveltejs/kit').Page;```
## updatedA read-only reactive value that's initially `false`. If [`version.pollInterval`](/docs/kit/configuration#version) is a non-zero value, SvelteKit will poll for new versions of the app and update `current` to `true` when it detects one. `updated.check()` will force an immediate check, regardless of polling.```dtsconst updated: { get current(): boolean; check(): Promise;};```
# $app/storesThis module contains store-based equivalents of the exports from [`$app/state`]($app-state). If you're using SvelteKit 2.12 or later, use that module instead.```js// @noErrorsimport { getStores, navigating, page, updated } from '$app/stores';```## getStores```dtsfunction getStores(): { page: typeof page; navigating: typeof navigating; updated: typeof updated;};```
## navigatingUse `navigating` from `$app/state` instead (requires Svelte 5, [see docs for more info](/docs/kit/migrating-to-sveltekit-2#SvelteKit-2.12:-$app-stores-deprecated)) 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`.On the server, this store can only be subscribed to during component initialization. In the browser, it can be subscribed to at any time.```dtsconst navigating: import('svelte/store').Readable< import('@sveltejs/kit').Navigation | null>;```
## pageUse `page` from `$app/state` instead (requires Svelte 5, [see docs for more info](/docs/kit/migrating-to-sveltekit-2#SvelteKit-2.12:-$app-stores-deprecated)) A readable store whose value contains page data.On the server, this store can only be subscribed to during component initialization. In the browser, it can be subscribed to at any time.```dtsconst page: import('svelte/store').Readable< import('@sveltejs/kit').Page>;```
## updatedUse `updated` from `$app/state` instead (requires Svelte 5, [see docs for more info](/docs/kit/migrating-to-sveltekit-2#SvelteKit-2.12:-$app-stores-deprecated)) A readable store whose initial value is `false`. If [`version.pollInterval`](/docs/kit/configuration#version) 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.On the server, this store can only be subscribed to during component initialization. In the browser, it can be subscribed to at any time.```dtsconst updated: import('svelte/store').Readable & { check(): Promise;};```
# $app/typesThis module contains generated types for the routes in your app.Available since 2.26
```js// @noErrorsimport type { RouteId, RouteParams, LayoutParams } from '$app/types';```## AssetA union of all the filenames of assets contained in your `static` directory, plus a `string` wildcard for asset paths generated from `import` declarations.```dtstype Asset = '/favicon.png' | '/robots.txt' | (string & {});```
## RouteIdA union of all the route IDs in your app. Used for `page.route.id` and `event.route.id`.```dtstype RouteId = '/' | '/my-route' | '/my-other-route/[param]';```
## PathnameA union of all valid pathnames in your app.```dtstype Pathname = '/' | '/my-route' | `/my-other-route/${string}` & {};```
## ResolvedPathnameSimilar to `Pathname`, but possibly prefixed with a [base path](configuration#paths). Used for `page.url.pathname`.```dtstype ResolvedPathname = `${'' | `/${string}`}/` | `${'' | `/${string}`}/my-route` | `${'' | `/${string}`}/my-other-route/${string}` | {};```
## RouteParamsA utility for getting the parameters associated with a given route.```ts// @errors: 2552type BlogParams = RouteParams<'/blog/[slug]'>; // { slug: string }``````dtstype RouteParams = { /* generated */ } | Record;```
## LayoutParamsA utility for getting the parameters associated with a given layout, which is similar to `RouteParams` but also includes optional parameters for any child route.```dtstype RouteParams = { /* generated */ } | Record;```
# $env/dynamic/privateThis module provides access to runtime environment variables, as defined by the platform you're running on. For example if you're using [`adapter-node`](https://github.com/sveltejs/kit/tree/main/packages/adapter-node) (or running [`vite preview`](/docs/kit/cli)), this is equivalent to `process.env`. This module only includes variables that _do not_ begin with [`config.kit.env.publicPrefix`](/docs/kit/configuration#env) _and do_ start with [`config.kit.env.privatePrefix`](/docs/kit/configuration#env) (if configured).This module cannot be imported into client-side code.```tsimport { env } from '$env/dynamic/private';console.log(env.DEPLOYMENT_SPECIFIC_VARIABLE);```# $env/dynamic/publicSimilar to [`$env/dynamic/private`](/docs/kit/$env-dynamic-private), but only includes variables that begin with [`config.kit.env.publicPrefix`](/docs/kit/configuration#env) (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.```tsimport { env } from '$env/dynamic/public';console.log(env.PUBLIC_DEPLOYMENT_SPECIFIC_VARIABLE);```# $env/static/privateEnvironment variables [loaded by Vite](https://vitejs.dev/guide/env-and-mode_html#env-files) from `.env` files and `process.env`. Like [`$env/dynamic/private`](/docs/kit/$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`](/docs/kit/configuration#env) _and do_ start with [`config.kit.env.privatePrefix`](/docs/kit/configuration#env) (if configured)._Unlike_ [`$env/dynamic/private`](/docs/kit/$env-dynamic-private), the values exported from this module are statically injected into your bundle at build time, enabling optimisations like dead code elimination.```tsimport { 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:```shMY_FEATURE_FLAG="enabled" npm run dev```# $env/static/publicSimilar to [`$env/static/private`](/docs/kit/$env-static-private), except that it only includes environment variables that begin with [`config.kit.env.publicPrefix`](/docs/kit/configuration#env) (which defaults to `PUBLIC_`), and can therefore safely be exposed to client-side code.Values are replaced statically at build time.```tsimport { PUBLIC_BASE_URL } from '$env/static/public';```# $libSvelteKit automatically makes files under `src/lib` available using the `$lib` import alias. You can change which directory this alias points to in your [config file](configuration#files).```svelteA reusable component``````svelte ```# $service-worker```js// @noErrorsimport { base, build, files, prerendered, version } from '$service-worker';```This module is only available to [service workers](/docs/kit/service-workers).## baseThe `base` path of the deployment. Typically this is equivalent to `config.kit.paths.base`, but it is calculated from `location.pathname` meaning that it will continue to work correctly if the site is deployed to a subdirectory.Note that there is a `base` but no `assets`, since service workers cannot be used if `config.kit.paths.assets` is specified.```dtsconst base: string;```
## buildAn array of URL strings representing the files generated by Vite, suitable for caching with `cache.addAll(build)`.During development, this is an empty array.```dtsconst build: string[];```
## filesAn 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`](/docs/kit/configuration#serviceWorker)```dtsconst files: string[];```
## prerenderedAn array of pathnames corresponding to prerendered pages and endpoints.During development, this is an empty array.```dtsconst prerendered: string[];```
## versionSee [`config.kit.version`](/docs/kit/configuration#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.```dtsconst version: string;```
# ConfigurationYour project's configuration lives in a `svelte.config.js` file at the root of your project. As well as SvelteKit, this config object is used by other tooling that integrates with Svelte such as editor extensions.```js/// file: svelte.config.js// @filename: ambient.d.tsdeclare module '@sveltejs/adapter-auto' { const plugin: () => import('@sveltejs/kit').Adapter; export default plugin;}// @filename: index.js// ---cut---import adapter from '@sveltejs/adapter-auto';/** @type {import('@sveltejs/kit').Config} */const config = { kit: { adapter: adapter() }};export default config;```## ConfigAn extension of [`vite-plugin-svelte`'s options](https://github.com/sveltejs/vite-plugin-svelte/blob/main/docs/config.md#svelte-options).```dtsinterface Config extends SvelteConfig {/*…*/}```
```dtskit?: KitConfig;```
SvelteKit options.
```dts[key: string]: any;```
Any additional options required by tooling that integrates with Svelte.
## KitConfigThe `kit` property configures SvelteKit, and can have the following properties:## adapter- default `undefined`
Your [adapter](/docs/kit/adapters) is run when executing `vite build`. It determines how the output is converted for different platforms.
## alias- default `{}`
An object containing zero or more aliases used to replace values in `import` statements. These aliases are automatically passed to Vite and TypeScript.```js// @errors: 7031/// file: svelte.config.js/** @type {import('@sveltejs/kit').Config} */const config = { kit: { alias: { // this will match a file 'my-file': 'path/to/my-file.js', // this will match a directory and its contents // (`my-directory/x` resolves to `path/to/my-directory/x`) 'my-directory': 'path/to/my-directory', // an alias ending /* will only match // the contents of a directory, not the directory itself 'my-directory/*': 'path/to/my-directory/*' } }};```
## appDir- default `"_app"`
The directory where SvelteKit keeps its stuff, including static assets (such as JS and CSS) and internally-used routes.If `paths.assets` is specified, there will be two app directories — `${paths.assets}/${appDir}` and `${paths.base}/${appDir}`.
## csp
[Content Security Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy) configuration. CSP helps to protect your users against cross-site scripting (XSS) attacks, by limiting the places resources can be loaded from. For example, a configuration like this...```js// @errors: 7031/// file: svelte.config.js/** @type {import('@sveltejs/kit').Config} */const config = { kit: { csp: { directives: { 'script-src': ['self'] }, // must be specified with either the `report-uri` or `report-to` directives, or both reportOnly: { 'script-src': ['self'], 'report-uri': ['/'] } } }};export default config;```...would prevent scripts loading from external sites. SvelteKit will augment the specified directives with nonces or hashes (depending on `mode`) for any inline styles and scripts it generates.To add a nonce for scripts and links manually included in `src/app_html`, you may use the placeholder `%sveltekit.nonce%` (for example ` ```## paths
```ts// @noErrorsassets?: '' | `http://${string}` | `https://${string}`;```
- default `""`
An absolute path that your app's files are served from. This is useful if your files are served from a storage bucket of some kind.
```ts// @noErrorsbase?: '' | `/${string}`;```
- default `""`
A root-relative path that must start, but not end with `/` (e.g. `/base-path`), unless it is the empty string. This specifies where your app is served from and allows the app to live on a non-root path. Note that you need to prepend all your root-relative links with the base value or they will point to the root of your domain, not your `base` (this is how the browser works). You can use [`base` from `$app/paths`](/docs/kit/$app-paths#base) for that: `
Link `. If you find yourself writing this often, it may make sense to extract this into a reusable component.
```ts// @noErrorsrelative?: boolean;```
- default `true`- available since v1.9.0
Whether to use relative asset paths.If `true`, `base` and `assets` imported from `$app/paths` will be replaced with relative asset paths during server-side rendering, resulting in more portable HTML.If `false`, `%sveltekit.assets%` and references to build artifacts will always be root-relative paths, unless `paths.assets` is an external URL[Single-page app](/docs/kit/single-page-apps) fallback pages will always use absolute paths, regardless of this setting.If your app uses a `
` element, you should set this to `false`, otherwise asset URLs will incorrectly be resolved against the `
` URL rather than the current page.In 1.0, `undefined` was a valid value, which was set by default. In that case, if `paths.assets` was not external, SvelteKit would replace `%sveltekit.assets%` with a relative path and use relative paths to reference build artifacts, but `base` and `assets` imported from `$app/paths` would be as specified in your config.
## prerender
See [Prerendering](/docs/kit/page-options#prerender).```ts// @noErrorsconcurrency?: number;```
- default `1`
How many pages can be prerendered simultaneously. JS is single-threaded, but in cases where prerendering performance is network-bound (for example loading content from a remote CMS) this can speed things up by processing other tasks while waiting on the network response.
```ts// @noErrorscrawl?: boolean;```
- default `true`
Whether SvelteKit should find pages to prerender by following links from `entries`.
```ts// @noErrorsentries?: Array<'*' | `/${string}`>;```
- default `["*"]`
An array of pages to prerender, or start crawling from (if `crawl: true`). The `*` string includes all routes containing no required `[parameters]` with optional parameters included as being empty (since SvelteKit doesn't know what value any parameters should have).
```ts// @noErrorshandleHttpError?: PrerenderHttpErrorHandlerValue;```
- default `"fail"`- available since v1.15.7
How to respond to HTTP errors encountered while prerendering the app.- `'fail'` — fail the build- `'ignore'` - silently ignore the failure and continue- `'warn'` — continue, but print a warning- `(details) => void` — a custom error handler that takes a `details` object with `status`, `path`, `referrer`, `referenceType` and `message` properties. If you `throw` from this function, the build will fail```js// @errors: 7031/// file: svelte.config.js/** @type {import('@sveltejs/kit').Config} */const config = { kit: { prerender: { handleHttpError: ({ path, referrer, message }) => { // ignore deliberate link to shiny 404 page if (path === '/not-found' && referrer === '/blog/how-we-built-our-404-page') { return; } // otherwise fail the build throw new Error(message); } } }};```
```ts// @noErrorshandleMissingId?: PrerenderMissingIdHandlerValue;```
- default `"fail"`- available since v1.15.7
How to respond when hash links from one prerendered page to another don't correspond to an `id` on the destination page.- `'fail'` — fail the build- `'ignore'` - silently ignore the failure and continue- `'warn'` — continue, but print a warning- `(details) => void` — a custom error handler that takes a `details` object with `path`, `id`, `referrers` and `message` properties. If you `throw` from this function, the build will fail
```ts// @noErrorshandleEntryGeneratorMismatch?: PrerenderEntryGeneratorMismatchHandlerValue;```
- default `"fail"`- available since v1.16.0
How to respond when an entry generated by the `entries` export doesn't match the route it was generated from.- `'fail'` — fail the build- `'ignore'` - silently ignore the failure and continue- `'warn'` — continue, but print a warning- `(details) => void` — a custom error handler that takes a `details` object with `generatedFromId`, `entry`, `matchedId` and `message` properties. If you `throw` from this function, the build will fail
```ts// @noErrorshandleUnseenRoutes?: PrerenderUnseenRoutesHandlerValue;```
- default `"fail"`- available since v2.16.0
How to respond when a route is marked as prerenderable but has not been prerendered.- `'fail'` — fail the build- `'ignore'` - silently ignore the failure and continue- `'warn'` — continue, but print a warning- `(details) => void` — a custom error handler that takes a `details` object with a `routes` property which contains all routes that haven't been prerendered. If you `throw` from this function, the build will failThe default behavior is to fail the build. This may be undesirable when you know that some of your routes may never be reached under certaincircumstances such as a CMS not returning data for a specific area, resulting in certain routes never being reached.
```ts// @noErrorsorigin?: string;```
- default `"http://sveltekit-prerender"`
The value of `url.origin` during prerendering; useful if it is included in rendered content.
## router
```ts// @noErrorstype?: 'pathname' | 'hash';```
- default `"pathname"`- available since v2.14.0
What type of client-side router to use.- `'pathname'` is the default and means the current URL pathname determines the route- `'hash'` means the route is determined by `location.hash`. In this case, SSR and prerendering are disabled. This is only recommended if `pathname` is not an option, for example because you don't control the webserver where your app is deployed. It comes with some caveats: you can't use server-side rendering (or indeed any server logic), and you have to make sure that the links in your app all start with #/, or they won't work. Beyond that, everything works exactly like a normal SvelteKit app.
```ts// @noErrorsresolution?: 'client' | 'server';```
- default `"client"`- available since v2.17.0
How to determine which route to load when navigating to a new page.By default, SvelteKit will serve a route manifest to the browser.When navigating, this manifest is used (along with the `reroute` hook, if it exists) to determine which components to load and which `load` functions to run.Because everything happens on the client, this decision can be made immediately. The drawback is that the manifest needs to beloaded and parsed before the first navigation can happen, which may have an impact if your app contains many routes.Alternatively, SvelteKit can determine the route on the server. This means that for every navigation to a path that has not yet been visited, the server will be asked to determine the route.This has several advantages:- The client does not need to load the routing manifest upfront, which can lead to faster initial page loads- The list of routes is hidden from public view- The server has an opportunity to intercept each navigation (for example through a middleware), enabling (for example) A/B testing opaque to SvelteKitThe drawback is that for unvisited paths, resolution will take slightly longer (though this is mitigated by [preloading](/docs/kit/link-options#data-sveltekit-preload-data)).
## serviceWorker
## typescript
```ts// @noErrorsconfig?: (config: Record
) => Record | void;```- default `(config) => config`- available since v1.3.0
A function that allows you to edit the generated `tsconfig.json`. You can mutate the config (recommended) or return a new one.This is useful for extending a shared `tsconfig.json` in a monorepo root, for example.Note that any paths configured here should be relative to the generated config file, which is written to `.svelte-kit/tsconfig.json`.
## version
Client-side navigation can be buggy if you deploy a new version of your app while people are using it. If the code for the new page is already loaded, it may have stale content; if it isn't, the app's route manifest may point to a JavaScript file that no longer exists.SvelteKit helps you solve this problem through version management.If SvelteKit encounters an error while loading the page and detects that a new version has been deployed (using the `name` specified here, which defaults to a timestamp of the build) it will fall back to traditional full-page navigation.Not all navigations will result in an error though, for example if the JavaScript for the next page is already loaded. If you still want to force a full-page navigation in these cases, use techniques such as setting the `pollInterval` and then using `beforeNavigate`:```html/// file: +layout.svelte```If you set `pollInterval` to a non-zero value, SvelteKit will poll for new versions in the background and set the value of [`updated.current`](/docs/kit/$app-state#updated) `true` when it detects one.```ts// @noErrorsname?: string;```
The current app version string. If specified, this must be deterministic (e.g. a commit ref rather than `Math.random()` or `Date.now().toString()`), otherwise defaults to a timestamp of the build.For example, to use the current commit hash, you could do use `git rev-parse HEAD`:```js// @errors: 7031/// file: svelte.config.jsimport * as child_process from 'node:child_process';export default { kit: { version: { name: child_process.execSync('git rev-parse HEAD').toString().trim() } }};```
```ts// @noErrorspollInterval?: number;```
- default `0`
The interval in milliseconds to poll for version changes. If this is `0`, no polling occurs.
# Command Line InterfaceSvelteKit 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 locallyHowever 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 typesThe `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/// link: trueimport 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.tsimport 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.tsimport 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": "./.svelte-kit/tsconfig.json" }`### Default tsconfig.jsonThe generated `.svelte-kit/tsconfig.json` file contains a mixture of options. Some are generated programmatically based on your project configuration, and should generally not be overridden without good reason:```json/// file: .svelte-kit/tsconfig.json{ "compilerOptions": { "paths": { "$lib": ["../src/lib"], "$lib/*": ["../src/lib/*"] }, "rootDirs": ["..", "./types"] }, "include": [ "ambient.d.ts", "non-ambient.d.ts", "./types/**/$types.d.ts", "../vite.config.js", "../vite.config.ts", "../src/**/*.js", "../src/**/*.ts", "../src/**/*.svelte", "../tests/**/*.js", "../tests/**/*.ts", "../tests/**/*.svelte" ], "exclude": [ "../node_modules/**", "../src/service-worker.js", "../src/service-worker/**/*.js", "../src/service-worker.ts", "../src/service-worker/**/*.ts", "../src/service-worker.d.ts", "../src/service-worker/**/*.d.ts" ]}```Others are required for SvelteKit to work properly, and should also be left untouched unless you know what you're doing:```json/// file: .svelte-kit/tsconfig.json{ "compilerOptions": { // this ensures that types are explicitly // imported with `import type`, which is // necessary as Svelte/Vite cannot // otherwise compile components correctly "verbatimModuleSyntax": true, // Vite compiles one TypeScript module // at a time, rather than compiling // the entire module graph "isolatedModules": true, // Tell TS it's used only for type-checking "noEmit": true, // This ensures both `vite build` // and `svelte-package` work correctly "lib": ["esnext", "DOM", "DOM.Iterable"], "moduleResolution": "bundler", "module": "esnext", "target": "esnext" }}```Use the [`typescript.config` setting](configuration#typescript) in `svelte.config.js` to extend or modify the generated `tsconfig.json`.## $libThis is a simple alias to `src/lib`, or whatever directory is specified as [`config.kit.files.lib`](configuration#files). It allows you to access common components and utility modules without `../../../../` nonsense.### $lib/serverA subdirectory of `$lib`. SvelteKit will prevent you from importing any modules in `$lib/server` into client-side code. See [server-only modules](server-only-modules).## app.d.tsThe `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.## ErrorDefines the common shape of expected and unexpected errors. Expected errors are thrown using the `error` function. Unexpected errors are handled by the `handleError` hooks which should return this shape.```dtsinterface Error {/*…*/}```
```dtsmessage: string;```
## LocalsThe 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.```dtsinterface Locals {}```
## PageDataDefines the common shape of the [page.data state](/docs/kit/$app-state#page) and [$page.data store](/docs/kit/$app-stores#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`).```dtsinterface PageData {}```
## PageStateThe shape of the `page.state` object, which can be manipulated using the [`pushState`](/docs/kit/$app-navigation#pushState) and [`replaceState`](/docs/kit/$app-navigation#replaceState) functions from `$app/navigation`.```dtsinterface PageState {}```
## PlatformIf your adapter provides [platform-specific context](/docs/kit/adapters#Platform-specific-context) via `event.platform`, you can specify it here.```dtsinterface Platform {}```
# Start of Svelte CLI documentation# OverviewThe command line interface (CLI), `sv`, is a toolkit for creating and maintaining Svelte applications.## UsageThe 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, `pnpx` if you're using [pnpm](https://pnpm.io/)):```shnpx 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).## AcknowledgementsThank 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** : `pnpx sv create` or `pnpm dlx sv create`- **Bun** : `bunx sv create`- **Deno** : `deno run npm:sv create`- **Yarn** : `yarn dlx sv create`## `npx sv` is not workingSome 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```shnpx 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:```shnpx 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`### `--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!### `--no-add-ons`Run the command without the interactive add-ons prompt### `--install `Installs dependencies with a specified package manager:- `npm`- `pnpm`- `yarn`- `bun`- `deno`### `--no-install`Prevents installing dependencies.# sv add`sv add` updates an existing project with new functionality.## Usage```shnpx sv add``````shnpx 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` — even if some files are dirty, no prompt will be shown- `--install` — installs dependencies with a specified package manager- `--no-install` — prevents installing dependencies## Official add-ons- [`devtools-json`](devtools-json)- [`drizzle`](drizzle)- [`eslint`](eslint)- [`lucia`](lucia)- [`mcp`](mcp)- [`mdsvex`](mdsvex)- [`paraglide`](paraglide)- [`playwright`](playwright)- [`prettier`](prettier)- [`storybook`](storybook)- [`sveltekit-adapter`](sveltekit-adapter)- [`tailwindcss`](tailwind)- [`vitest`](vitest)# sv check`sv check` finds errors and warnings in your project, such as:- unused CSS- accessibility hints- JavaScript/TypeScript compiler errorsRequires Node 16 or later.## InstallationYou will need to have the `svelte-check` package installed in your project:```shnpm i -D svelte-check```## Usage```shnpx 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:```shnpx 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`:```shnpx 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:```shnpx 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 outputSetting the `--output` to `machine` or `machine-verbose` will format output in a way that is easier to readby 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 asingle space character. The first column of every row contains a timestamp in millisecondswhich can be used for monitoring purposes. The second column gives us the "row type", basedon 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 `exportconst 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(Kit) codebases. It delegates to the [`svelte-migrate`](https://www.npmjs.com/package/svelte-migrate) package.Some migrations may annotate your codebase with tasks for completion that you can find by searching for `@migration`.## Usage```shnpx sv migrate```You can also specify a migration directly via the CLI:```shnpx sv migrate [migration]```## Migrations### `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.### `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.# devtools-jsonThe `devtools-json` add-on installs [`vite-plugin-devtools-json`](https://github.com/ChromeDevTools/vite-plugin-devtools-json/), which is a Vite plugin for generating a Chromium DevTools project settings file on-the-fly in the development server. This file is served from `/.well-known/appspecific/com.chrome.devtools.json` and tells Chromium browsers where your project's source code lives so that you can use [the workspaces feature](https://developer.chrome.com/docs/devtools/workspaces) to edit source files in the browser.> Installing the plugin enables the feature for all users connecting to the dev server with a Chromium browser, and allows the browser to read and write all files within the directory. If using Chrome's AI Assistance feature, this may also result in data being sent to Google.## AlternativesIf you'd prefer not to install the plugin, but still want to avoid seeing a message about the missing file, you have a couple of options.Firstly, you can prevent the request from being issued on your machine by disabling the feature in your browser. You can do this in Chrome by visiting `chrome://flags` and disabling the "DevTools Project Settings". You may also be interested in disabling "DevTools Automatic Workspace Folders" since it’s closely related.You can also prevent the web server from issuing a notice regarding the incoming request for all developers of your application by handling the request yourself. For example, you can create a file named `.well-known/appspecific/com.chrome.devtools.json` with the contents `"Go away, Chrome DevTools!"` or you can add logic to respond to the request in your [`handle`](https://svelte.dev/docs/kit/hooks#Server-hooks-handle) hook:```js/// file: src/hooks.server.jsimport { dev } from '$app/environment';export function handle({ event, resolve }) { if (dev && event.url.pathname === '/.well-known/appspecific/com.chrome.devtools.json') { return new Response(undefined, { status: 404 }); } return resolve(event);}```## Usage```shnpx sv add devtools-json```## What you get- `vite-plugin-devtools-json` added to your Vite plugin options# 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```shnpx 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 Lucia auth add-on- an optional Docker configuration to help with running a local database## Options### databaseWhich 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```shnpx sv add drizzle=database:postgresql```### clientThe SQL client to use, depends on `database`:- For `postgresql`: `postgres.js`, `neon`,- For `mysql`: `mysql2`, `planetscale`- For `sqlite`: `better-sqlite3`, `libsql`, `turso````shnpx 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).### dockerWhether to add Docker Compose configuration. Only available for [`database`](#Options-database) `postgresql` or `mysql````shnpx sv add drizzle=database:postgresql+client:postgres.js+docker:yes```# eslint[ESLint](https://eslint.org/) finds and fixes problems in your code.## Usage```shnpx sv add eslint```## What you get- the relevant packages installed including `eslint-plugin-svelte`- an `eslint.config.js` file- updated `.vscode/settings.json`- configured to work with TypeScript and `prettier` if you're using those packages# luciaAn auth setup following [the Lucia auth guide](https://lucia-auth.com/).## Usage```shnpx sv add lucia```## What you get- an auth setup for SvelteKit and Drizzle following the best practices from the Lucia auth guide- optional demo registration and login pages## Options### demoWhether to include demo registration and login pages.```shnpx sv add lucia=demo:yes```# mcp[Svelte MCP](/docs/mcp/overview) can help your LLM write better Svelte code.## Usage```shnpx sv add mcp```## What you get- A good mcp configuration for your project depending on your IDE## Options### ideThe IDE you want to use like `'claude-code'`, `'cursor'`, `'gemini'`, `'opencode'`, `'vscode'`, `'other'`.```shnpx sv add mcp=ide:cursor,vscode```### setupThe setup you want to use.```shnpx sv add mcp=setup:local```# 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```shnpx 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```shnpx 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### languageTagsThe languages you'd like to support specified as IETF BCP 47 language tags.```shnpx sv add paraglide="languageTags:en,es"```### demoWhether to generate an optional demo page showing how to use paraglide.```shnpx sv add paraglide="demo:yes"```# playwright[Playwright](https://playwright.dev) browser testing.## Usage```shnpx 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```shnpx 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```shnpx 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```shnpx sv add sveltekit-adapter```## What you get- the chosen SvelteKit adapter installed and configured in your `svelte.config.js`## Options### adapterWhich 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```shnpx sv add sveltekit-adapter=adapter:node```# tailwindcss[Tailwind CSS](https://tailwindcss.com/) allows you to rapidly build modern websites without ever leaving your HTML.## Usage```shnpx 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 `app.css` and `+layout.svelte` (for SvelteKit) or `App.svelte` (for non-SvelteKit Vite apps)- integration with `prettier` if using that package## Options### pluginsWhich plugin to use:- `typography` — [`@tailwindcss/typography`](https://github.com/tailwindlabs/tailwindcss-typography)- `forms` — [`@tailwindcss/forms`](https://github.com/tailwindlabs/tailwindcss-forms)```shnpx sv add tailwindcss="plugins:typography"```# vitest[Vitest](https://vitest.dev/) is a Vite-native testing framework.## Usage```shnpx 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# Start of Svelte MCP documentation# OverviewThe Svelte MCP ([Model Context Protocol](https://modelcontextprotocol.io/docs/getting-started/intro)) server can help your LLM or agent of choice write better Svelte code. It works by providing documentation relevant to the task at hand, and statically analysing generated code so that it can suggest fixes and best practices.## SetupThe setup varies based on the version of the MCP you prefer — remote or local — and your chosen MCP client (e.g. Claude Code, Codex CLI or GitHub Copilot):- [local setup](local-setup) using `@sveltejs/mcp`- [remote setup](remote-setup) using `https://mcp.svelte.dev/mcp`## UsageTo get the most out of the MCP server we recommend including the following prompt in your [`AGENTS.md`](https://agents.md) (or [`CLAUDE.md`](https://docs.claude.com/en/docs/claude-code/memory#claude-md-imports), if using Claude Code). This will tell the LLM which tools are available and when it's appropriate to use them.```mdYou are able to use the Svelte MCP server, where you have access to comprehensive Svelte 5 and SvelteKit documentation. Here's how to use the available tools effectively:## Available MCP Tools:### 1. list-sectionsUse this FIRST to discover all available documentation sections. Returns a structured list with titles, use_cases, and paths.When asked about Svelte or SvelteKit topics, ALWAYS use this tool at the start of the chat to find relevant sections.### 2. get-documentationRetrieves full documentation content for specific sections. Accepts single or multiple sections.After calling the list-sections tool, you MUST analyze the returned documentation sections (especially the use_cases field) and then use the get-documentation tool to fetch ALL documentation sections that are relevant for the user's task.### 3. svelte-autofixerAnalyzes Svelte code and returns issues and suggestions.You MUST use this tool whenever writing Svelte code before sending it to the user. Keep calling it until no issues or suggestions are returned.### 4. playground-linkGenerates a Svelte Playground link with the provided code.After completing the code, ask the user if they want a playground link. Only call this tool after user confirmation and NEVER if code was written to files in their project.```If your MCP client supports it, we also recommend using the [svelte-task](prompts#svelte-task) prompt to instruct the LLM on the best way to use the MCP server.# Local setupThe local (or stdio) version of the MCP server is available via the [`@sveltejs/mcp`](https://www.npmjs.com/package/@sveltejs/mcp) npm package. You can either install it globally and then reference it in your configuration or run it with `npx`:```bashnpx -y @sveltejs/mcp```Here's how to set it up in some common MCP clients:## Claude CodeTo include the local MCP version in Claude Code, simply run the following command:```bashclaude mcp add -t stdio -s [scope] svelte -- npx -y @sveltejs/mcp```The `[scope]` must be `user`, `project` or `local`.## Claude DesktopIn the Settings > Developer section, click on Edit Config. It will open the folder with a `claude_desktop_config.json` file in it. Edit the file to include the following configuration:```json{ "mcpServers": { "svelte": { "command": "npx", "args": ["-y", "@sveltejs/mcp"] } }}```## Codex CLIAdd the following to your `config.toml` (which defaults to `~/.codex/config.toml`, but refer to [the configuration documentation](https://github.com/openai/codex/blob/main/docs/config.md) for more advanced setups):```toml[mcp_servers.svelte]command = "npx"args = ["-y", "@sveltejs/mcp"]```## Gemini CLITo include the local MCP version in Gemini CLI, simply run the following command:```bashgemini mcp add -t stdio -s [scope] svelte npx -y @sveltejs/mcp```The `[scope]` must be `user`, `project` or `local`.## OpenCodeRun the command:```bashopencode mcp add```and follow the instructions, selecting 'Local' under the 'Select MCP server type' prompt:```bashopencode mcp add┌ Add MCP server│◇ Enter MCP server name│ svelte│◇ Select MCP server type│ Local│◆ Enter command to run│ npx -y @sveltejs/mcp```## VS Code- Open the command palette- Select "MCP: Add Server..."- Select "Command (stdio)"- Insert `npx -y @sveltejs/mcp` in the input and press `Enter`- When prompted for a name, insert `svelte`- Select if you want to add it as a `Global` or `Workspace` MCP server## Cursor- Open the command palette- Select "View: Open MCP Settings"- Click on "Add custom MCP"It will open a file with your MCP servers where you can add the following configuration:```json{ "mcpServers": { "svelte": { "command": "npx", "args": ["-y", "@sveltejs/mcp"] } }}```## Zed- Open the command palette- Search and select "agent:open settings"- In settings panel look for `Model Context Protocol (MCP) Servers`- Click on "Add Server"- Select: "Add Custom Server"It will open a popup with MCP server config where you can add the following configuration:```json{ "svelte": { "command": "npx", "args": ["-y", "@sveltejs/mcp"] }}```## Other clientsIf we didn't include the MCP client you are using, refer to their documentation for `stdio` servers and use `npx` as the command and `-y @sveltejs/mcp` as the arguments.# Remote setupThe remote version of the MCP server is available at `https://mcp.svelte.dev/mcp`.Here's how to set it up in some common MCP clients:## Claude CodeTo include the remote MCP version in Claude Code, simply run the following command:```bashclaude mcp add -t http -s [scope] svelte https://mcp.svelte.dev/mcp```You can choose your preferred `scope` (it must be `user`, `project` or `local`) and `name`.## Claude Desktop- Open Settings > Connectors- Click on Add Custom Connector- When prompted for a name, enter `svelte`- Under the Remote MCP server URL input, use `https://mcp.svelte.dev/mcp`- Click Add## Codex CLIAdd the following to your `config.toml` (which defaults to `~/.codex/config.toml`, but refer to [the configuration documentation](https://github.com/openai/codex/blob/main/docs/config.md) for more advanced setups):```tomlexperimental_use_rmcp_client = true[mcp_servers.svelte]url = "https://mcp.svelte.dev/mcp"```## Gemini CLITo use the remote MCP server with Gemini CLI, simply run the following command:```bashgemini mcp add -t http -s [scope] svelte https://mcp.svelte.dev/mcp```The `[scope]` must be `user`, `project` or `local`.## OpenCodeRun the command:```bashopencode mcp add```and follow the instructions, selecting 'Remote' under the 'Select MCP server type' prompt:```bashopencode mcp add┌ Add MCP server│◇ Enter MCP server name│ svelte│◇ Select MCP server type│ Remote│◇ Enter MCP server URL│ https://mcp.svelte.dev/mcp```## VS Code- Open the command palette- Select "MCP: Add Server..."- Select "HTTP (HTTP or Server-Sent-Events)"- Insert `https://mcp.svelte.dev/mcp` in the input and press `Enter`- Insert your preferred name- Select if you want to add it as a `Global` or `Workspace` MCP server## Cursor- Open the command palette- Select "View: Open MCP Settings"- Click on "Add custom MCP"It will open a file with your MCP servers where you can add the following configuration:```json{ "mcpServers": { "svelte": { "url": "https://mcp.svelte.dev/mcp" } }}```## GitHub Coding Agent- Open your repository in GitHub- Go to Settings- Open Copilot > Coding agent- Edit the MCP configuration```json{ "mcpServers": { "svelte": { "type": "http", "url": "https://mcp.svelte.dev/mcp", "tools": ["*"] } }}```- Click _Save MCP configuration_## Other clientsIf we didn't include the MCP client you are using, refer to their documentation for `remote` servers and use `https://mcp.svelte.dev/mcp` as the URL.# ToolsThe following tools are provided by the MCP server to the model you are using, which can decide to call one or more of them during a session:## list-sectionsProvides a list of all the available documentation sections.## get-documentationAllows the model to get the full (and up-to-date) documentation for the requested sections directly from [svelte.dev/docs](/docs).## svelte-autofixerUses static analysis to provide suggestions for code that your LLM generates. It can be invoked in an agentic loop by your model until all issues and suggestions are resolved.## playground-linkGenerates an ephemeral playground link with the generated code. It's useful when the generated code is not written to a file in your project and you want to quickly test the generated solution. The code is not stored anywhere except the URL itself (which will often, as a consequence, be quite large).# ResourcesThis is the list of available resources provided by the MCP server. Resources are included by the user (not by the LLM) and are useful if you want to include specific knowledge in your session. For example, if you know that the component will need to use transitions you can include the transition documentation directly without asking the LLM to do it for you.## doc-sectionThis dynamic resource allows you to add every section of the Svelte documentation as a resource. The URI looks like this `svelte://slug-of-the-docs.md` and the returned resource will contain the `llms.txt` version of the specific page you selected.# PromptsThis is the list of available prompts provided by the MCP server. Prompts are selected by the user and are sent as a user message. They can be useful to write repetitive instructions for the LLM on how to properly use the MCP server.## svelte-taskThis prompt should be used whenever you are asking the model to work on a Svelte-related task. It will instruct the LLM which documentation sections are available, which tools to invoke, when to invoke them, and how to interpret the results.Copy the prompt ```mdYou are a Svelte expert tasked to build components and utilities for Svelte developers. If you need documentation for anything related to Svelte you can invoke the tool `get_documentation` with one of the following paths:- title: Overview, use_cases: project setup, creating new svelte apps, scaffolding, cli tools, initializing projects, path: cli/overview- title: Frequently asked questions, use_cases: project setup, initializing new svelte projects, troubleshooting cli installation, package manager configuration, path: cli/faq- title: sv create, use_cases: project setup, starting new sveltekit app, initializing project, creating from playground, choosing project template, path: cli/sv-create- title: sv add, use_cases: project setup, adding features to existing projects, integrating tools, testing setup, styling setup, authentication, database setup, deployment adapters, path: cli/sv-add- title: sv check, use_cases: code quality, ci/cd pipelines, error checking, typescript projects, pre-commit hooks, finding unused css, accessibility auditing, production builds, path: cli/sv-check- title: sv migrate, use_cases: migration, upgrading svelte versions, upgrading sveltekit versions, modernizing codebase, svelte 3 to 4, svelte 4 to 5, sveltekit 1 to 2, adopting runes, refactoring deprecated apis, path: cli/sv-migrate- title: devtools-json, use_cases: development setup, chrome devtools integration, browser-based editing, local development workflow, debugging setup, path: cli/devtools-json- title: drizzle, use_cases: database setup, sql queries, orm integration, data modeling, postgresql, mysql, sqlite, server-side data access, database migrations, type-safe queries, path: cli/drizzle- title: eslint, use_cases: code quality, linting, error detection, project setup, code standards, team collaboration, typescript projects, path: cli/eslint- title: lucia, use_cases: authentication, login systems, user management, registration pages, session handling, auth setup, path: cli/lucia- title: mcp, use_cases: use title and path to estimate use case, path: cli/mcp- title: mdsvex, use_cases: blog, content sites, markdown rendering, documentation sites, technical writing, cms integration, article pages, path: cli/mdsvex- title: paraglide, use_cases: internationalization, multi-language sites, i18n, translation, localization, language switching, global apps, multilingual content, path: cli/paraglide- title: playwright, use_cases: browser testing, e2e testing, integration testing, test automation, quality assurance, ci/cd pipelines, testing user flows, path: cli/playwright- title: prettier, use_cases: code formatting, project setup, code style consistency, team collaboration, linting configuration, path: cli/prettier- title: storybook, use_cases: component development, design systems, ui library, isolated component testing, documentation, visual testing, component showcase, path: cli/storybook- title: sveltekit-adapter, use_cases: deployment, production builds, hosting setup, choosing deployment platform, configuring adapters, static site generation, node server, vercel, cloudflare, netlify, path: cli/sveltekit-adapter- title: tailwindcss, use_cases: project setup, styling, css framework, rapid prototyping, utility-first css, design systems, responsive design, adding tailwind to svelte, path: cli/tailwind- title: vitest, use_cases: testing, unit tests, component testing, test setup, quality assurance, ci/cd pipelines, test-driven development, path: cli/vitest- title: Introduction, use_cases: learning sveltekit, project setup, understanding framework basics, choosing between svelte and sveltekit, getting started with full-stack apps, path: kit/introduction- title: Creating a project, use_cases: project setup, starting new sveltekit app, initial development environment, first-time sveltekit users, scaffolding projects, path: kit/creating-a-project- title: Project types, use_cases: deployment, project setup, choosing adapters, ssg, spa, ssr, serverless, mobile apps, desktop apps, pwa, offline apps, browser extensions, separate backend, docker containers, path: kit/project-types- title: Project structure, use_cases: project setup, understanding file structure, organizing code, starting new project, learning sveltekit basics, path: kit/project-structure- title: Web standards, use_cases: always, any sveltekit project, data fetching, forms, api routes, server-side rendering, deployment to various platforms, path: kit/web-standards- title: Routing, use_cases: routing, navigation, multi-page apps, project setup, file structure, api endpoints, data loading, layouts, error pages, always, path: kit/routing- title: Loading data, use_cases: data fetching, api calls, database queries, dynamic routes, page initialization, loading states, authentication checks, ssr data, form data, content rendering, path: kit/load- title: Form actions, use_cases: forms, user input, data submission, authentication, login systems, user registration, progressive enhancement, validation errors, path: kit/form-actions- title: Page options, use_cases: prerendering static sites, ssr configuration, spa setup, client-side rendering control, url trailing slash handling, adapter deployment config, build optimization, path: kit/page-options- title: State management, use_cases: sveltekit, server-side rendering, ssr, state management, authentication, data persistence, load functions, context api, navigation, component lifecycle, path: kit/state-management- title: Remote functions, use_cases: data fetching, server-side logic, database queries, type-safe client-server communication, forms, user input, mutations, authentication, crud operations, optimistic updates, path: kit/remote-functions- title: Building your app, use_cases: production builds, deployment preparation, build process optimization, adapter configuration, preview before deployment, path: kit/building-your-app- title: Adapters, use_cases: deployment, production builds, hosting setup, choosing deployment platform, configuring adapters, path: kit/adapters- title: Zero-config deployments, use_cases: deployment, production builds, hosting setup, choosing deployment platform, ci/cd configuration, path: kit/adapter-auto- title: Node servers, use_cases: deployment, production builds, node.js hosting, custom server setup, environment configuration, reverse proxy setup, docker deployment, systemd services, path: kit/adapter-node- title: Static site generation, use_cases: static site generation, ssg, prerendering, deployment, github pages, spa mode, blogs, documentation sites, marketing sites, path: kit/adapter-static- title: Single-page apps, use_cases: spa mode, single-page apps, client-only rendering, static hosting, mobile app wrappers, no server-side logic, adapter-static setup, fallback pages, path: kit/single-page-apps- title: Cloudflare, use_cases: deployment, cloudflare workers, cloudflare pages, hosting setup, production builds, serverless deployment, edge computing, path: kit/adapter-cloudflare- title: Cloudflare Workers, use_cases: deploying to cloudflare workers, cloudflare workers sites deployment, legacy cloudflare adapter, wrangler configuration, cloudflare platform bindings, path: kit/adapter-cloudflare-workers- title: Netlify, use_cases: deployment, netlify hosting, production builds, serverless functions, edge functions, static site hosting, path: kit/adapter-netlify- title: Vercel, use_cases: deployment, vercel hosting, production builds, serverless functions, edge functions, isr, image optimization, environment variables, path: kit/adapter-vercel- title: Writing adapters, use_cases: custom deployment, building adapters, unsupported platforms, adapter development, custom hosting environments, path: kit/writing-adapters- title: Advanced routing, use_cases: advanced routing, dynamic routes, file viewers, nested paths, custom 404 pages, url validation, route parameters, multi-level navigation, path: kit/advanced-routing- title: Hooks, use_cases: authentication, logging, error tracking, request interception, api proxying, custom routing, internationalization, database initialization, middleware logic, session management, path: kit/hooks- title: Errors, use_cases: error handling, custom error pages, 404 pages, api error responses, production error logging, error tracking, type-safe errors, path: kit/errors- title: Link options, use_cases: routing, navigation, multi-page apps, performance optimization, link preloading, forms with get method, search functionality, focus management, scroll behavior, path: kit/link-options- title: Service workers, use_cases: offline support, pwa, caching strategies, performance optimization, precaching assets, network resilience, progressive web apps, path: kit/service-workers- title: Server-only modules, use_cases: api keys, environment variables, sensitive data protection, backend security, preventing data leaks, server-side code isolation, path: kit/server-only-modules- title: Snapshots, use_cases: forms, user input, preserving form data, multi-step forms, navigation state, preventing data loss, textarea content, input fields, comment systems, surveys, path: kit/snapshots- title: Shallow routing, use_cases: modals, dialogs, image galleries, overlays, history-driven ui, mobile-friendly navigation, photo viewers, lightboxes, drawer menus, path: kit/shallow-routing- title: Observability, use_cases: performance monitoring, debugging, observability, tracing requests, production diagnostics, analyzing slow requests, finding bottlenecks, monitoring server-side operations, path: kit/observability- title: Packaging, use_cases: building component libraries, publishing npm packages, creating reusable svelte components, library development, package distribution, path: kit/packaging- title: Auth, use_cases: authentication, login systems, user management, session handling, jwt tokens, protected routes, user credentials, authorization checks, path: kit/auth- title: Performance, use_cases: performance optimization, slow loading pages, production deployment, debugging performance issues, reducing bundle size, improving load times, path: kit/performance- title: Icons, use_cases: icons, ui components, styling, css frameworks, tailwind, unocss, performance optimization, dependency management, path: kit/icons- title: Images, use_cases: image optimization, responsive images, performance, hero images, product photos, galleries, cms integration, cdn setup, asset management, path: kit/images- title: Accessibility, use_cases: always, any sveltekit project, screen reader support, keyboard navigation, multi-page apps, client-side routing, internationalization, multilingual sites, path: kit/accessibility- title: SEO, use_cases: seo optimization, search engine ranking, content sites, blogs, marketing sites, public-facing apps, sitemaps, amp pages, meta tags, performance optimization, path: kit/seo- title: Frequently asked questions, use_cases: troubleshooting package imports, library compatibility issues, client-side code execution, external api integration, middleware setup, database configuration, view transitions, yarn configuration, path: kit/faq- title: Integrations, use_cases: project setup, css preprocessors, postcss, scss, sass, less, stylus, typescript setup, adding integrations, tailwind, testing, auth, linting, formatting, path: kit/integrations- title: Breakpoint Debugging, use_cases: debugging, breakpoints, development workflow, troubleshooting issues, vscode setup, ide configuration, inspecting code execution, path: kit/debugging- title: Migrating to SvelteKit v2, use_cases: migration, upgrading from sveltekit 1 to 2, breaking changes, version updates, path: kit/migrating-to-sveltekit-2- title: Migrating from Sapper, use_cases: migrating from sapper, upgrading legacy projects, sapper to sveltekit conversion, project modernization, path: kit/migrating- title: Additional resources, use_cases: troubleshooting, getting help, finding examples, learning sveltekit, project templates, common issues, community support, path: kit/additional-resources- title: Glossary, use_cases: rendering strategies, performance optimization, deployment configuration, seo requirements, static sites, spas, server-side rendering, prerendering, edge deployment, pwa development, path: kit/glossary- title: @sveltejs/kit, use_cases: forms, form actions, server-side validation, form submission, error handling, redirects, json responses, http errors, server utilities, path: kit/@sveltejs-kit- title: @sveltejs/kit/hooks, use_cases: middleware, request processing, authentication chains, logging, multiple hooks, request/response transformation, path: kit/@sveltejs-kit-hooks- title: @sveltejs/kit/node/polyfills, use_cases: node.js environments, custom servers, non-standard runtimes, ssr setup, web api compatibility, polyfill requirements, path: kit/@sveltejs-kit-node-polyfills- title: @sveltejs/kit/node, use_cases: node.js adapter, custom server setup, http integration, streaming files, node deployment, server-side rendering with node, path: kit/@sveltejs-kit-node- title: @sveltejs/kit/vite, use_cases: project setup, vite configuration, initial sveltekit setup, build tooling, path: kit/@sveltejs-kit-vite- title: $app/environment, use_cases: always, conditional logic, client-side code, server-side code, build-time logic, prerendering, development vs production, environment detection, path: kit/$app-environment- title: $app/forms, use_cases: forms, user input, data submission, progressive enhancement, custom form handling, form validation, path: kit/$app-forms- title: $app/navigation, use_cases: routing, navigation, multi-page apps, programmatic navigation, data reloading, preloading, shallow routing, navigation lifecycle, scroll handling, view transitions, path: kit/$app-navigation- title: $app/paths, use_cases: static assets, images, fonts, public files, base path configuration, subdirectory deployment, cdn setup, asset urls, links, navigation, path: kit/$app-paths- title: $app/server, use_cases: remote functions, server-side logic, data fetching, form handling, api endpoints, client-server communication, prerendering, file reading, batch queries, path: kit/$app-server- title: $app/state, use_cases: routing, navigation, multi-page apps, loading states, url parameters, form handling, error states, version updates, page metadata, shallow routing, path: kit/$app-state- title: $app/stores, use_cases: legacy projects, sveltekit pre-2.12, migration from stores to runes, maintaining older codebases, accessing page data, navigation state, app version updates, path: kit/$app-stores- title: $app/types, use_cases: routing, navigation, type safety, route parameters, dynamic routes, link generation, pathname validation, multi-page apps, path: kit/$app-types- title: $env/dynamic/private, use_cases: api keys, secrets management, server-side config, environment variables, backend logic, deployment-specific settings, private data handling, path: kit/$env-dynamic-private- title: $env/dynamic/public, use_cases: environment variables, client-side config, runtime configuration, public api keys, deployment-specific settings, multi-environment apps, path: kit/$env-dynamic-public- title: $env/static/private, use_cases: server-side api keys, backend secrets, database credentials, private configuration, build-time optimization, server endpoints, authentication tokens, path: kit/$env-static-private- title: $env/static/public, use_cases: environment variables, public config, client-side data, api endpoints, build-time configuration, public constants, path: kit/$env-static-public- title: $lib, use_cases: project setup, component organization, importing shared components, reusable ui elements, code structure, path: kit/$lib- title: $service-worker, use_cases: offline support, pwa, service workers, caching strategies, progressive web apps, offline-first apps, path: kit/$service-worker- title: Configuration, use_cases: project setup, configuration, adapters, deployment, build settings, environment variables, routing customization, prerendering, csp security, csrf protection, path configuration, typescript setup, path: kit/configuration- title: Command Line Interface, use_cases: project setup, typescript configuration, generated types, ./$types imports, initial project configuration, path: kit/cli- title: Types, use_cases: typescript, type safety, route parameters, api endpoints, load functions, form actions, generated types, jsconfig setup, path: kit/types- title: Overview, use_cases: use title and path to estimate use case, path: mcp/overview- title: Local setup, use_cases: use title and path to estimate use case, path: mcp/local-setup- title: Remote setup, use_cases: use title and path to estimate use case, path: mcp/remote-setup- title: Tools, use_cases: use title and path to estimate use case, path: mcp/tools- title: Resources, use_cases: use title and path to estimate use case, path: mcp/resources- title: Prompts, use_cases: use title and path to estimate use case, path: mcp/prompts- title: Overview, use_cases: always, any svelte project, getting started, learning svelte, introduction, project setup, understanding framework basics, path: svelte/overview- title: Getting started, use_cases: project setup, starting new svelte project, initial installation, choosing between sveltekit and vite, editor configuration, path: svelte/getting-started- title: .svelte files, use_cases: always, any svelte project, component creation, project setup, learning svelte basics, path: svelte/svelte-files- title: .svelte.js and .svelte.ts files, use_cases: shared reactive state, reusable reactive logic, state management across components, global stores, custom reactive utilities, path: svelte/svelte-js-files- title: What are runes?, use_cases: always, any svelte 5 project, understanding core syntax, learning svelte 5, migration from svelte 4, path: svelte/what-are-runes- title: $state, use_cases: always, any svelte project, core reactivity, state management, counters, forms, todo apps, interactive ui, data updates, class-based components, path: svelte/$state- title: $derived, use_cases: always, any svelte project, computed values, reactive calculations, derived data, transforming state, dependent values, path: svelte/$derived- title: $effect, use_cases: canvas drawing, third-party library integration, dom manipulation, side effects, intervals, timers, network requests, analytics tracking, path: svelte/$effect- title: $props, use_cases: always, any svelte project, passing data to components, component communication, reusable components, component props, path: svelte/$props- title: $bindable, use_cases: forms, user input, two-way data binding, custom input components, parent-child communication, reusable form fields, path: svelte/$bindable- title: $inspect, use_cases: debugging, development, tracking state changes, reactive state monitoring, troubleshooting reactivity issues, path: svelte/$inspect- title: $host, use_cases: custom elements, web components, dispatching custom events, component library, framework-agnostic components, path: svelte/$host- title: Basic markup, use_cases: always, any svelte project, basic markup, html templating, component structure, attributes, events, props, text rendering, path: svelte/basic-markup- title: {#if ...}, use_cases: always, conditional rendering, showing/hiding content, dynamic ui, user permissions, loading states, error handling, form validation, path: svelte/if- title: {#each ...}, use_cases: always, lists, arrays, iteration, product listings, todos, tables, grids, dynamic content, shopping carts, user lists, comments, feeds, path: svelte/each- title: {#key ...}, use_cases: animations, transitions, component reinitialization, forcing component remount, value-based ui updates, resetting component state, path: svelte/key- title: {#await ...}, use_cases: async data fetching, api calls, loading states, promises, error handling, lazy loading components, dynamic imports, path: svelte/await- title: {#snippet ...}, use_cases: reusable markup, component composition, passing content to components, table rows, list items, conditional rendering, reducing duplication, path: svelte/snippet- title: {@render ...}, use_cases: reusable ui patterns, component composition, conditional rendering, fallback content, layout components, slot alternatives, template reuse, path: svelte/@render- title: {@html ...}, use_cases: rendering html strings, cms content, rich text editors, markdown to html, blog posts, wysiwyg output, sanitized html injection, dynamic html content, path: svelte/@html- title: {@attach ...}, use_cases: tooltips, popovers, dom manipulation, third-party libraries, canvas drawing, element lifecycle, interactive ui, custom directives, wrapper components, path: svelte/@attach- title: {@const ...}, use_cases: computed values in loops, derived calculations in blocks, local variables in each iterations, complex list rendering, path: svelte/@const- title: {@debug ...}, use_cases: debugging, development, troubleshooting, tracking state changes, monitoring variables, reactive data inspection, path: svelte/@debug- title: bind:, use_cases: forms, user input, two-way data binding, interactive ui, media players, file uploads, checkboxes, radio buttons, select dropdowns, contenteditable, dimension tracking, path: svelte/bind- title: use:, use_cases: custom directives, dom manipulation, third-party library integration, tooltips, click outside, gestures, focus management, element lifecycle hooks, path: svelte/use- title: transition:, use_cases: animations, interactive ui, modals, dropdowns, notifications, conditional content, show/hide elements, smooth state changes, path: svelte/transition- title: in: and out:, use_cases: animation, transitions, interactive ui, conditional rendering, independent enter/exit effects, modals, tooltips, notifications, path: svelte/in-and-out- title: animate:, use_cases: sortable lists, drag and drop, reorderable items, todo lists, kanban boards, playlist editors, priority queues, animated list reordering, path: svelte/animate- title: style:, use_cases: dynamic styling, conditional styles, theming, dark mode, responsive design, interactive ui, component styling, path: svelte/style- title: class, use_cases: always, conditional styling, dynamic classes, tailwind css, component styling, reusable components, responsive design, path: svelte/class- title: await, use_cases: async data fetching, loading states, server-side rendering, awaiting promises in components, async validation, concurrent data loading, path: svelte/await-expressions- title: Scoped styles, use_cases: always, styling components, scoped css, component-specific styles, preventing style conflicts, animations, keyframes, path: svelte/scoped-styles- title: Global styles, use_cases: global styles, third-party libraries, css resets, animations, styling body/html, overriding component styles, shared keyframes, base styles, path: svelte/global-styles- title: Custom properties, use_cases: theming, custom styling, reusable components, design systems, dynamic colors, component libraries, ui customization, path: svelte/custom-properties- title: Nested