` is no longer necessary. ### src/node_modules A common pattern in Sapper apps is to put your internal library in a directory inside `src/node_modules`. This doesn't work with Vite, so we use [`src/lib`]($lib) instead. ## Pages and layouts ### Renamed files Routes now are made up of the folder name exclusively to remove ambiguity, the folder names leading up to a `+page.svelte` correspond to the route. See [the routing docs](routing) for an overview. The following shows a old/new comparison: | Old | New | | ------------------------- | ------------------------- | | routes/about/index.svelte | routes/about/+page.svelte | | routes/about.svelte | routes/about/+page.svelte | Your custom error page component should be renamed from `_error.svelte` to `+error.svelte`. Any `_layout.svelte` files should likewise be renamed `+layout.svelte`. [Any other files are ignored](routing#Other-files). ### Imports The `goto`, `prefetch` and `prefetchRoutes` imports from `@sapper/app` should be replaced with `goto`, `preloadData` and `preloadCode` imports respectively from [`$app/navigation`]($app-navigation). The `stores` import from `@sapper/app` should be replaced — see the [Stores](migrating#Pages-and-layouts-Stores) section below. Any files you previously imported from directories in `src/node_modules` will need to be replaced with [`$lib`]($lib) imports. ### Preload As before, pages and layouts can export a function that allows data to be loaded before rendering takes place. This function has been renamed from `preload` to [`load`](load), it now lives in a `+page.js` (or `+layout.js`) next to its `+page.svelte` (or `+layout.svelte`), and its API has changed. Instead of two arguments — `page` and `session` — there is a single `event` argument. There is no more `this` object, and consequently no `this.fetch`, `this.error` or `this.redirect`. Instead, you can get [`fetch`](load#Making-fetch-requests) from the input methods, and both [`error`](load#Errors) and [`redirect`](load#Redirects) are now thrown. ### Stores In Sapper, you would get references to provided stores like so: ```js // @filename: ambient.d.ts declare module '@sapper/app'; // @filename: index.js //cut import { stores } from '@sapper/app'; const { preloading, page, session } = stores(); ``` The `page` store still exists; `preloading` has been replaced with a `navigating` store that contains `from` and `to` properties. `page` now has `url` and `params` properties, but no `path` or `query`. You access them differently in SvelteKit. `stores` is now `getStores`, but in most cases it is unnecessary since you can import `navigating`, and `page` directly from [`$app/stores`]($app-stores). ### Routing Regex routes are no longer supported. Instead, use [advanced route matching](advanced-routing#Matching). ### Segments Previously, layout components received a `segment` prop indicating the child segment. This has been removed; you should use the more flexible `$page.url.pathname` value to derive the segment you're interested in. ### URLs In Sapper, all relative URLs were resolved against the base URL — usually `/`, unless the `basepath` option was used — rather than against the current page. This caused problems and is no longer the case in SvelteKit. Instead, relative URLs are resolved against the current page (or the destination page, for `fetch` URLs in `load` functions) instead. In most cases, it's easier to use root-relative (i.e. starts with `/`) URLs, since their meaning is not context-dependent. ### <a> attributes - `sapper:prefetch` is now `data-sveltekit-preload-data` - `sapper:noscroll` is now `data-sveltekit-noscroll` ## Endpoints In Sapper, [server routes](routing#server) received the `req` and `res` objects exposed by Node's `http` module (or the augmented versions provided by frameworks like Polka and Express). SvelteKit is designed to be agnostic as to where the app is running — it could be running on a Node server, but could equally be running on a serverless platform or in a Cloudflare Worker. For that reason, you no longer interact directly with `req` and `res`. Your endpoints will need to be updated to match the new signature. To support this environment-agnostic behavior, `fetch` is now available in the global context, so you don't need to import `node-fetch`, `cross-fetch`, or similar server-side fetch implementations in order to use it. ## Integrations See [integrations](./integrations) for detailed information about integrations. ### HTML minifier Sapper includes `html-minifier` by default. SvelteKit does not include this, but you can add it as a prod dependency and then use it through a [hook](hooks#Server-hooks-handle): ```js // @filename: ambient.d.ts ///
declare module 'html-minifier'; // @filename: index.js //cut import { minify } from 'html-minifier'; import { building } from '$app/environment'; const minification_options = { collapseBooleanAttributes: true, collapseWhitespace: true, conservativeCollapse: true, decodeEntities: true, html5: true, ignoreCustomComments: [/^#/], minifyCSS: true, minifyJS: false, removeAttributeQuotes: true, removeComments: false, // some hydration code needs comments, so leave them in removeOptionalTags: true, removeRedundantAttributes: true, removeScriptTypeAttributes: true, removeStyleLinkTypeAttributes: true, sortAttributes: true, sortClassName: true }; /** @type {import('@sveltejs/kit').Handle} */ export async function handle({ event, resolve }) { let page = ''; return resolve(event, { transformPageChunk: ({ html, done }) => { page += html; if (done) { return building ? minify(page, minification_options) : page; } } }); } ``` Note that `prerendering` is `false` when using `vite preview` to test the production build of the site, so to verify the results of minifying, you'll need to inspect the built HTML files directly.
## docs/kit/60-appendix/50-additional-resources.md
--- NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: Additional resources --- ## FAQs Please see the [SvelteKit FAQ](faq) for solutions to common issues and helpful tips and tricks. The [Svelte FAQ](../svelte/faq) and [`vite-plugin-svelte` FAQ](https://github.com/sveltejs/vite-plugin-svelte/blob/main/docs/faq.md) may also be helpful for questions deriving from those libraries. ## Examples We've written and published a few different SvelteKit sites as examples: - [`sveltejs/realworld`](https://github.com/sveltejs/realworld) contains an example blog site - [A HackerNews clone](https://github.com/sveltejs/sites/tree/master/sites/hn.svelte.dev) - [`svelte.dev`](https://github.com/sveltejs/svelte.dev) SvelteKit users have also published plenty of examples on GitHub, under the [#sveltekit](https://github.com/topics/sveltekit) and [#sveltekit-template](https://github.com/topics/sveltekit-template) topics, as well as on [the Svelte Society site](https://sveltesociety.dev/templates?category=sveltekit). Note that these have not been vetted by the maintainers and may not be up to date. ## Support You can ask for help on [Discord](https://svelte.dev/chat) and [StackOverflow](https://stackoverflow.com/questions/tagged/sveltekit). Please first search for information related to your issue in the FAQ, Google or another search engine, issue tracker, and Discord chat history in order to be respectful of others' time. There are many more people asking questions than answering them, so this will help in allowing the community to grow in a scalable fashion.
## docs/kit/60-appendix/60-glossary.md
--- NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: Glossary --- The core of SvelteKit provides a highly configurable rendering engine. This section describes some of the terms used when discussing rendering. A reference for setting these options is provided in the documentation above. ## CSR Client-side rendering (CSR) is the generation of the page contents in the web browser using JavaScript. In SvelteKit, client-side rendering will be used by default, but you can turn off JavaScript with [the `csr = false` page option](page-options#csr). ## Hydration Svelte components store some state and update the DOM when the state is updated. When fetching data during SSR, by default SvelteKit will store this data and transmit it to the client along with the server-rendered HTML. The components can then be initialized on the client with that data without having to call the same API endpoints again. Svelte will then check that the DOM is in the expected state and attach event listeners in a process called hydration. Once the components are fully hydrated, they can react to changes to their properties just like any newly created Svelte component. In SvelteKit, pages will be hydrated by default, but you can turn off JavaScript with [the `csr = false` page option](page-options#csr). ## Prerendering Prerendering means computing the contents of a page at build time and saving the HTML for display. This approach has the same benefits as traditional server-rendered pages, but avoids recomputing the page for each visitor and so scales nearly for free as the number of visitors increases. The tradeoff is that the build process is more expensive and prerendered content can only be updated by building and deploying a new version of the application. Not all pages can be prerendered. The basic rule is this: for content to be prerenderable, any two users hitting it directly must get the same content from the server, and the page must not contain [actions](form-actions). Note that you can still prerender content that is loaded based on the page's parameters as long as all users will be seeing the same prerendered content. Pre-rendered pages are not limited to static content. You can build personalized pages if user-specific data is fetched and rendered client-side. This is subject to the caveat that you will experience the downsides of not doing SSR for that content as discussed above. In SvelteKit, you can control prerendering with [the `prerender` page option](page-options#prerender) and [`prerender` config](configuration#prerender) in `svelte.config.js`. ## Routing By default, when you navigate to a new page (by clicking on a link or using the browser's forward or back buttons), SvelteKit will intercept the attempted navigation and handle it instead of allowing the browser to send a request to the server for the destination page. SvelteKit will then update the displayed contents on the client by rendering the component for the new page, which in turn can make calls to the necessary API endpoints. This process of updating the page on the client in response to attempted navigation is called client-side routing. In SvelteKit, client-side routing will be used by default, but you can skip it with [`data-sveltekit-reload`](link-options#data-sveltekit-reload). ## SPA A single-page app (SPA) is an application in which all requests to the server load a single HTML file which then does client-side rendering of the requested contents based on the requested URL. All navigation is handled on the client-side in a process called client-side routing with per-page contents being updated and common layout elements remaining largely unchanged. SPAs do not provide SSR, which has the shortcoming described above. However, some applications are not greatly impacted by these shortcomings such as a complex business application behind a login where SEO would not be important and it is known that users will be accessing the application from a consistent computing environment. In SvelteKit, you can [build an SPA with `adapter-static`](single-page-apps). ## SSG Static Site Generation (SSG) is a term that refers to a site where every page is prerendered. SvelteKit was not built to do only static site generation like some tools and so may not scale as well to efficiently render a very large number of pages as tools built specifically for that purpose. However, in contrast to most purpose-built SSGs, SvelteKit does nicely allow for mixing and matching different rendering types on different pages. One benefit of fully prerendering a site is that you do not need to maintain or pay for servers to perform SSR. Once generated, the site can be served from CDNs, leading to great "time to first byte" performance. This delivery model is often referred to as JAMstack. In SvelteKit, you can do static site generation by using [`adapter-static`](adapter-static) or by configuring every page to be prerendered using [the `prerender` page option](page-options#prerender) or [`prerender` config](configuration#prerender) in `svelte.config.js`. ## SSR Server-side rendering (SSR) is the generation of the page contents on the server. SSR is generally preferred for SEO. While some search engines can index content that is dynamically generated on the client-side it may take longer even in these cases. It also tends to improve perceived performance and makes your app accessible to users if JavaScript fails or is disabled (which happens [more often than you probably think](https://kryogenix.org/code/browser/everyonehasjs.html)). In SvelteKit, pages are server-side rendered by default. You can disable SSR with [the `ssr` page option](page-options#ssr).
## docs/kit/98-reference/index.md
--- NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: Reference ---
## docs/kit/98-reference/10-@sveltejs-kit.md
--- NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: @sveltejs/kit --- ```js // @noErrors import { Server, VERSION, error, fail, isActionFailure, isHttpError, isRedirect, json, redirect, text } from '@sveltejs/kit'; ``` ## Server
```dts class Server {/*…*/} ```
```dts constructor(manifest: SSRManifest); ```
```dts init(options: ServerInitOptions): Promise
; ```
```dts respond(request: Request, options: RequestOptions): Promise
; ```
## VERSION
```dts const VERSION: string; ```
## error Throws an error with a HTTP status code and an optional message. When called during request handling, this will cause SvelteKit to return an error response without invoking `handleError`. Make sure you're not catching the thrown error, which would prevent SvelteKit from handling it.
```dts function error(status: number, body: App.Error): never; ```
```dts function error( status: number, body?: { message: string; } extends App.Error ? App.Error | string | undefined : never ): never; ```
## fail Create an `ActionFailure` object.
```dts function fail(status: number): ActionFailure; ```
```dts function fail< T extends Record | undefined = undefined >(status: number, data: T): ActionFailure; ```
## isActionFailure Checks whether this is an action failure thrown by `fail`.
```dts function isActionFailure( e: unknown ): e is ActionFailure; ```
## isHttpError Checks whether this is an error thrown by `error`.
```dts function isHttpError( e: unknown, status?: T | undefined ): e is HttpError_1 & { status: T extends undefined ? never : T; }; ```
## isRedirect Checks whether this is a redirect thrown by `redirect`.
```dts function isRedirect(e: unknown): e is Redirect_1; ```
## json Create a JSON `Response` object from the supplied data.
```dts function json( data: any, init?: ResponseInit | undefined ): Response; ```
## redirect Redirect 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.
```dts function redirect( status: | 300 | 301 | 302 | 303 | 304 | 305 | 306 | 307 | 308 | ({} & number), location: string | URL ): never; ```
## text Create a `Response` object from the supplied body.
```dts function text( body: string, init?: ResponseInit | undefined ): Response; ```
## Action Shape 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.
```dts type Action< Params extends Partial
> = Partial< Record >, OutputData extends Record | void = Record< string, any > | void, RouteId extends string | null = string | null > = ( event: RequestEvent ) => MaybePromise; ``` ## ActionFailure
```dts interface ActionFailure< T extends Record
| undefined = undefined > {/*…*/} ``` ```dts status: number; ```
```dts [uniqueSymbol]: true; ```
## ActionResult When calling a form action via fetch, the response will be one of these shapes. ```svelte
` with a GET method - `leave`: The user is leaving the app by closing the tab or using the back/forward buttons to go to a different document - `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 ```dts type NavigationType = | 'enter' | 'form' | 'leave' | 'link' | 'goto' | 'popstate'; ```
## NumericRange ```dts type NumericRange< TStart extends number, TEnd extends number > = Exclude, LessThan>; ```
## OnNavigate The argument passed to [`onNavigate`](/docs/kit/$app-navigation#onNavigate) callbacks. ```dts interface OnNavigate extends Navigation {/*…*/} ```
```dts type: Exclude
; ``` 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 ```dts willUnload: false; ```
Since `onNavigate` callbacks are called immediately before a client-side navigation, they will never be called with a navigation that unloads the page.
## Page The shape of the `$page` store ```dts interface Page< Params extends Record
= Record< string, string >, RouteId extends string | null = string | null > {/*…*/} ``` ```dts url: URL; ```
The URL of the current page
```dts params: Params; ```
The parameters of the current page - e.g. for a route like `/blog/[slug]`, a `{ slug: string }` object
```dts route: {/*…*/} ```
Info about the current route
```dts id: RouteId; ```
The ID of the current route - e.g. for `src/routes/blog/[slug]`, it would be `/blog/[slug]`
```dts status: number; ```
Http status code of the current page
```dts error: App.Error | null; ```
The error object of the current page, if any. Filled from the `handleError` hooks.
```dts data: App.PageData & Record
; ``` The merged result of all data from all `load` functions on the current page. You can type a common denominator through `App.PageData`.
```dts state: App.PageState; ```
The page state, which can be manipulated using the [`pushState`](https://svelte.dev/docs/kit/$app-navigation#pushState) and [`replaceState`](https://svelte.dev/docs/kit/$app-navigation#replaceState) functions from `$app/navigation`.
```dts form: any; ```
Filled only after a form submission. See [form actions](https://svelte.dev/docs/kit/form-actions) for more info.
## ParamMatcher The shape of a param matcher. See [matching](/docs/kit/advanced-routing#Matching) for more info. ```dts type ParamMatcher = (param: string) => boolean; ```
## PrerenderOption ```dts type PrerenderOption = boolean | 'auto'; ```
## Redirect The object returned by the [`redirect`](/docs/kit/@sveltejs-kit#redirect) function ```dts interface Redirect {/*…*/} ```
```dts status: 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.
```dts location: string; ```
The location to redirect to.
## RequestEvent ```dts interface RequestEvent< Params extends Partial
> = Partial< Record >, RouteId extends string | null = string | null > {/*…*/} ``` ```dts cookies: Cookies; ```
Get or set cookies related to the current request
```dts fetch: 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`](https://svelte.dev/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](https://svelte.dev/docs/kit/load#Cookies)
```dts getClientAddress(): string; ```
The client's IP address, set by the adapter.
```dts locals: App.Locals; ```
Contains custom data that was added to the request within the [`server handle hook`](https://svelte.dev/docs/kit/hooks#Server-hooks-handle).
```dts params: Params; ```
The parameters of the current route - e.g. for a route like `/blog/[slug]`, a `{ slug: string }` object
```dts platform: Readonly
| undefined; ``` Additional data made available through the adapter.
```dts request: Request; ```
The original request object
```dts route: {/*…*/} ```
Info about the current route
```dts id: RouteId; ```
The ID of the current route - e.g. for `src/routes/blog/[slug]`, it would be `/blog/[slug]`
```dts setHeaders(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.js export 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`](https://svelte.dev/docs/kit/@sveltejs-kit#Cookies) API instead.
```dts url: URL; ```
The requested URL.
```dts isDataRequest: 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 information related to the data request in this case. Use this property instead if the distinction is important to you.
```dts isSubRequest: 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.
## RequestHandler A `(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. ```dts type RequestHandler< Params extends Partial
> = Partial< Record >, RouteId extends string | null = string | null > = ( event: RequestEvent ) => MaybePromise; ``` ## Reroute Available 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. ```dts type Reroute = (event: { url: URL }) => void | string; ```
## ResolveOptions ```dts interface ResolveOptions {/*…*/} ```
```dts transformPageChunk?(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.
```dts filterSerializedResponseHeaders?(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.
```dts preload?(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 ```dts interface RouteDefinition
{/*…*/} ``` ```dts api: { methods: Array
; }; ```
```dts page: { methods: Array
>; }; ```
```dts pattern: RegExp; ```
```dts prerender: PrerenderOption; ```
```dts segments: RouteSegment[]; ```
```dts methods: Array
; ```
```dts config: Config; ```
## SSRManifest ```dts interface SSRManifest {/*…*/} ```
```dts appDir: string; ```
```dts appPath: string; ```
```dts mimeTypes: Record
; ```
```dts _: {/*…*/} ```
private fields
```dts client: NonNullable
; ```
```dts nodes: SSRNodeLoader[]; ```
```dts routes: SSRRoute[]; ```
```dts matchers(): Promise
>; ```
```dts server_assets: Record
; ``` A `[file]: size` map of all assets imported by server code
## ServerInit Available since 2.10.0 The [`init`](/docs/kit/hooks#Shared-hooks-init) will be invoked before the server responds to its first request ```dts type ServerInit = () => MaybePromise; ```
## ServerInitOptions ```dts interface ServerInitOptions {/*…*/} ```
```dts env: Record
; ``` A map of environment variables
```dts read?: (file: string) => ReadableStream; ```
A function that turns an asset filename into a `ReadableStream`. Required for the `read` export from `$app/server` to work
## ServerLoad The 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. ```dts type ServerLoad< Params extends Partial
> = Partial< Record >, ParentData extends Record = Record< string, any >, OutputData extends Record | void = Record< string, any > | void, RouteId extends string | null = string | null > = ( event: ServerLoadEvent ) => MaybePromise; ``` ## ServerLoadEvent ```dts interface ServerLoadEvent< Params extends Partial
> = Partial< Record >, ParentData extends Record = Record< string, any >, RouteId extends string | null = string | null > extends RequestEvent {/*…*/} ``` ```dts parent(): 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.
```dts depends(...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()`](https://svelte.dev/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.js let count = 0; export async function load({ depends }) { depends('increase:count'); return { count: count++ }; } ``` ```html /// file: src/routes/+page.svelte
{data.count}
Increase Count ```
```dts untrack
(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.js export async function load({ untrack, url }) { // Untrack url.pathname so that path changes don't trigger a rerun if (untrack(() => url.pathname === '/')) { return { message: 'Welcome!' }; } } ```
## Snapshot The type of `export const snapshot` exported from a page or layout component. ```dts interface Snapshot
{/*…*/} ``` ```dts capture: () => T; ```
```dts restore: (snapshot: T) => void; ```
## SubmitFunction ```dts type 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; }) => void) >; ```
## Private types The following are referenced by the public types documented above, but cannot be imported directly: ## AdapterEntry ```dts interface AdapterEntry {/*…*/} ```
```dts id: 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 both be represented in a Netlify _redirects file as `/foo/:param`, so they share an ID
```dts filter(route: RouteDefinition): boolean; ```
A function that compares the candidate route with the current route to determine if 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
```dts complete(entry: { generateManifest(opts: { relativePath: string }): string }): MaybePromise
; ``` A function that is invoked once the entry has been created. This is where you should write the function to the filesystem and generate redirect manifests.
## Csp ```dts namespace 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 ```dts interface 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
; ```
```dts sandbox?: 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'>; ```
```dts referrer?: 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 ```dts type HttpMethod = | 'GET' | 'HEAD' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'OPTIONS'; ```
## Logger ```dts interface Logger {/*…*/} ```
```dts (msg: string): void; ```
```dts success(msg: string): void; ```
```dts error(msg: string): void; ```
```dts warn(msg: string): void; ```
```dts minor(msg: string): void; ```
```dts info(msg: string): void; ```
## MaybePromise ```dts type MaybePromise = T | Promise; ```
## PrerenderEntryGeneratorMismatchHandler ```dts interface PrerenderEntryGeneratorMismatchHandler {/*…*/} ```
```dts (details: { generatedFromId: string; entry: string; matchedId: string; message: string }): void; ```
## PrerenderEntryGeneratorMismatchHandlerValue ```dts type PrerenderEntryGeneratorMismatchHandlerValue = | 'fail' | 'warn' | 'ignore' | PrerenderEntryGeneratorMismatchHandler; ```
## PrerenderHttpErrorHandler ```dts interface PrerenderHttpErrorHandler {/*…*/} ```
```dts (details: { status: number; path: string; referrer: string | null; referenceType: 'linked' | 'fetched'; message: string; }): void; ```
## PrerenderHttpErrorHandlerValue ```dts type PrerenderHttpErrorHandlerValue = | 'fail' | 'warn' | 'ignore' | PrerenderHttpErrorHandler; ```
## PrerenderMap ```dts type PrerenderMap = Map; ```
## PrerenderMissingIdHandler ```dts interface PrerenderMissingIdHandler {/*…*/} ```
```dts (details: { path: string; id: string; referrers: string[]; message: string }): void; ```
## PrerenderMissingIdHandlerValue ```dts type PrerenderMissingIdHandlerValue = | 'fail' | 'warn' | 'ignore' | PrerenderMissingIdHandler; ```
## PrerenderOption ```dts type PrerenderOption = boolean | 'auto'; ```
## Prerendered ```dts interface Prerendered {/*…*/} ```
```dts pages: Map< string, { /** The location of the .html file relative to the output directory */ file: string; } >; ```
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`.
```dts assets: Map< string, { /** The MIME type of the asset */ type: string; } >; ```
A map of `path` to `{ type }` objects.
```dts redirects: Map< string, { status: number; location: string; } >; ```
A map of redirects encountered during prerendering.
```dts paths: string[]; ```
An array of prerendered paths (without trailing slashes, regardless of the trailingSlash config)
## RequestOptions ```dts interface RequestOptions {/*…*/} ```
```dts getClientAddress(): string; ```
```dts platform?: App.Platform; ```
## RouteSegment ```dts interface RouteSegment {/*…*/} ```
```dts content: string; ```
```dts dynamic: boolean; ```
```dts rest: boolean; ```
## TrailingSlash ```dts type TrailingSlash = 'never' | 'always' | 'ignore'; ```
## docs/kit/98-reference/15-@sveltejs-kit-hooks.md
--- NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: @sveltejs/kit/hooks --- ```js // @noErrors import { sequence } from '@sveltejs/kit/hooks'; ``` ## sequence A 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.js import { sequence } from '@sveltejs/kit/hooks'; /** @type {import('@sveltejs/kit').Handle} */ async function first({ event, resolve }) { console.log('first pre-processing'); const result = await resolve(event, { transformPageChunk: ({ html }) => { // transforms are applied in reverse order console.log('first transform'); return html; }, 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-processing first preload second pre-processing second filterSerializedResponseHeaders second transform first transform second post-processing first post-processing ``` ```dts function sequence( ...handlers: import('@sveltejs/kit').Handle[] ): import('@sveltejs/kit').Handle; ```
## docs/kit/98-reference/15-@sveltejs-kit-node-polyfills.md
--- NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: @sveltejs/kit/node/polyfills --- ```js // @noErrors import { installPolyfills } from '@sveltejs/kit/node/polyfills'; ``` ## installPolyfills Make various web APIs available as globals: - `crypto` - `File` ```dts function installPolyfills(): void; ```
## docs/kit/98-reference/15-@sveltejs-kit-node.md
--- NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: @sveltejs/kit/node --- ```js // @noErrors import { createReadableStream, getRequest, setResponse } from '@sveltejs/kit/node'; ``` ## createReadableStream Available since 2.4.0 Converts a file on disk to a readable stream ```dts function createReadableStream(file: string): ReadableStream; ```
## getRequest ```dts function getRequest({ request, base, bodySizeLimit }: { request: import('http').IncomingMessage; base: string; bodySizeLimit?: number; }): Promise; ```
## setResponse ```dts function setResponse( res: import('http').ServerResponse, response: Response ): Promise; ```
## docs/kit/98-reference/15-@sveltejs-kit-vite.md
--- NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: @sveltejs/kit/vite --- ```js // @noErrors import { sveltekit } from '@sveltejs/kit/vite'; ``` ## sveltekit Returns the SvelteKit Vite plugins. ```dts function sveltekit(): Promise; ```
## docs/kit/98-reference/20-$app-environment.md
--- NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: $app/environment --- ```js // @noErrors import { browser, building, dev, version } from '$app/environment'; ``` ## browser `true` if the app is running in the browser. ```dts const browser: boolean; ```
## building SvelteKit analyses your app during the `build` step by running it. During this process, `building` is `true`. This also applies during prerendering. ```dts const building: boolean; ```
## dev Whether the dev server is running. This is not guaranteed to correspond to `NODE_ENV` or `MODE`. ```dts const dev: boolean; ```
## version The value of `config.kit.version.name`. ```dts const version: string; ```
## docs/kit/98-reference/20-$app-forms.md
--- NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: $app/forms --- ```js // @noErrors import { applyAction, deserialize, enhance } from '$app/forms'; ``` ## applyAction This action updates the `form` property of the current page with the given data and updates `$page.status`. In case of an error, it redirects to the nearest error page. ```dts function applyAction< Success extends Record | undefined, Failure extends Record | undefined >( result: import('@sveltejs/kit').ActionResult< Success, Failure > ): Promise; ```
## deserialize Use this function to deserialize the response from a form submission. Usage: ```js // @errors: 7031 import { 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()); // ... } ``` ```dts function deserialize< Success extends Record | undefined, Failure extends Record | undefined >( result: string ): import('@sveltejs/kit').ActionResult; ```
## enhance This 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 error If you provide a custom function with a callback and want to use the default behavior, invoke `update` in your callback. ```dts function enhance< Success extends Record | undefined, Failure extends Record | undefined >( form_element: HTMLFormElement, submit?: import('@sveltejs/kit').SubmitFunction< Success, Failure > ): { destroy(): void; }; ```
## docs/kit/98-reference/20-$app-navigation.md
--- NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: $app/navigation --- ```js // @noErrors import { afterNavigate, beforeNavigate, disableScrollHandling, goto, invalidate, invalidateAll, onNavigate, preloadCode, preloadData, pushState, replaceState } from '$app/navigation'; ``` ## afterNavigate A lifecycle function that runs the supplied `callback` when the current component mounts, and also whenever we navigate to a new URL. `afterNavigate` must be called during a component initialization. It remains active as long as the component is mounted. ```dts function afterNavigate( callback: ( navigation: import('@sveltejs/kit').AfterNavigate ) => void ): void; ```
## beforeNavigate A 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. ```dts function beforeNavigate( callback: ( navigation: import('@sveltejs/kit').BeforeNavigate ) => void ): void; ```
## disableScrollHandling If called when the page is being updated following a navigation (in `onMount` or `afterNavigate` or an action, for example), this disables SvelteKit's built-in scroll handling. This is generally discouraged, since it breaks user expectations. ```dts function disableScrollHandling(): void; ```
## goto 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)`. ```dts function goto( url: string | URL, opts?: | { replaceState?: boolean | undefined; noScroll?: boolean | undefined; keepFocus?: boolean | undefined; invalidateAll?: boolean | undefined; state?: App.PageState | undefined; } | undefined ): Promise; ```
## invalidate Causes any `load` functions belonging to the currently active page to re-run if they depend on the `url` in question, via `fetch` or `depends`. Returns a `Promise` that resolves when the page is subsequently updated. If the argument is given as a `string` or `URL`, it must resolve to the same URL that was passed to `fetch` or `depends` (including query parameters). To create a custom identifier, use a string beginning with `[a-z]+:` (e.g. `custom:state`) — this is a valid URL. The `function` argument can be used define a custom predicate. It receives the full `URL` and causes `load` to rerun if `true` is returned. This can be useful if you want to invalidate based on a pattern instead of a exact match. ```ts // Example: Match '/path' regardless of the query parameters import { invalidate } from '$app/navigation'; invalidate((url) => url.pathname === '/path'); ``` ```dts function invalidate( resource: string | URL | ((url: URL) => boolean) ): Promise; ```
## invalidateAll Causes all `load` functions belonging to the currently active page to re-run. Returns a `Promise` that resolves when the page is subsequently updated. ```dts function invalidateAll(): Promise; ```
## onNavigate A 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. ```dts function onNavigate( callback: ( navigation: import('@sveltejs/kit').OnNavigate ) => MaybePromise<(() => void) | void> ): void; ```
## preloadCode Programmatically 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. ```dts function preloadCode(pathname: string): Promise; ```
## preloadData Programmatically 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. ```dts function preloadData(href: string): Promise< | { type: 'loaded'; status: number; data: Record; } | { type: 'redirect'; location: string; } >; ```
## pushState Programmatically 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). ```dts function pushState( url: string | URL, state: App.PageState ): void; ```
## replaceState Programmatically 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). ```dts function replaceState( url: string | URL, state: App.PageState ): void; ```
## docs/kit/98-reference/20-$app-paths.md
--- NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: $app/paths --- ```js // @noErrors import { assets, base, resolveRoute } from '$app/paths'; ``` ## assets An absolute path that matches [`config.kit.paths.assets`](/docs/kit/configuration#paths). ```dts let assets: | '' | `https://${string}` | `http://${string}` | '/_svelte_kit_assets'; ```
## base A string that matches [`config.kit.paths.base`](/docs/kit/configuration#paths). Example usage: ` Link ` ```dts let base: '' | `/${string}`; ```
## resolveRoute Populate a route ID with params to resolve a pathname. ```js // @errors: 7031 import { resolveRoute } from '$app/paths'; resolveRoute( `/blog/[slug]/[...somethingElse]`, { slug: 'hello-world', somethingElse: 'something/else' } ); // `/blog/hello-world/something/else` ``` ```dts function resolveRoute( id: string, params: Record ): string; ```
## docs/kit/98-reference/20-$app-server.md
--- NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: $app/server --- ```js // @noErrors import { read } from '$app/server'; ``` ## read Available since 2.4.0 Read the contents of an imported asset from the filesystem ```js // @errors: 7031 import { read } from '$app/server'; import somefile from './somefile.txt'; const asset = read(somefile); const text = await asset.text(); ``` ```dts function read(asset: string): Response; ```
## docs/kit/98-reference/20-$app-stores.md
--- NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: $app/stores --- ```js // @noErrors import { getStores, navigating, page, updated } from '$app/stores'; ``` ## getStores ```dts function getStores(): { page: typeof page; navigating: typeof navigating; updated: typeof updated; }; ```
## navigating 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. ```dts const navigating: import('svelte/store').Readable< import('@sveltejs/kit').Navigation | null >; ```
## page 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. ```dts const page: import('svelte/store').Readable< import('@sveltejs/kit').Page >; ```
## updated 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. ```dts const updated: import('svelte/store').Readable & { check(): Promise; }; ```
## docs/kit/98-reference/25-$env-dynamic-private.md
--- NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: $env/dynamic/private --- This module provides access to runtime environment variables, as defined by the platform you're running on. For example if you're using [`adapter-node`](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. Dynamic environment variables cannot be used during prerendering. ```ts import { env } from '$env/dynamic/private'; console.log(env.DEPLOYMENT_SPECIFIC_VARIABLE); ``` > In `dev`, `$env/dynamic` always includes environment variables from `.env`. In `prod`, this behavior will depend on your adapter.
## docs/kit/98-reference/25-$env-dynamic-public.md
--- NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: $env/dynamic/public --- Similar 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. Dynamic environment variables cannot be used during prerendering. ```ts import { env } from '$env/dynamic/public'; console.log(env.PUBLIC_DEPLOYMENT_SPECIFIC_VARIABLE); ```
## docs/kit/98-reference/25-$env-static-private.md
--- NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: $env/static/private --- Environment 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. ```ts import { API_KEY } from '$env/static/private'; ``` Note that all environment variables referenced in your code should be declared (for example in an `.env` file), even if they don't have a value until the app is deployed: ``` MY_FEATURE_FLAG="" ``` You can override `.env` values from the command line like so: ```bash MY_FEATURE_FLAG="enabled" npm run dev ```
## docs/kit/98-reference/25-$env-static-public.md
--- NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: $env/static/public --- Similar 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. ```ts import { PUBLIC_BASE_URL } from '$env/static/public'; ```
## docs/kit/98-reference/26-$lib.md
--- NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: $lib --- SvelteKit 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). ```svelte A reusable component ``` ```svelte ```
## docs/kit/98-reference/27-$service-worker.md
--- NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: $service-worker --- ```js // @noErrors import { base, build, files, prerendered, version } from '$service-worker'; ``` This module is only available to [service workers](/docs/kit/service-workers). ## base The `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. ```dts const base: string; ```
## build An array of URL strings representing the files generated by Vite, suitable for caching with `cache.addAll(build)`. During development, this is an empty array. ```dts const build: string[]; ```
## files An array of URL strings representing the files in your static directory, or whatever directory is specified by `config.kit.files.assets`. You can customize which files are included from `static` directory using [`config.kit.serviceWorker.files`](/docs/kit/configuration) ```dts const files: string[]; ```
## prerendered An array of pathnames corresponding to prerendered pages and endpoints. During development, this is an empty array. ```dts const prerendered: string[]; ```
## version See [`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. ```dts const version: string; ```
## docs/kit/98-reference/50-configuration.md
--- NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: Configuration --- Your 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.ts declare 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; ``` ## Config ```dts interface Config {/*…*/} ```
```dts compilerOptions?: CompileOptions; ```
- default `{}`
Options passed to [`svelte.compile`](https://svelte.dev/docs/svelte/svelte-compiler#CompileOptions).
```dts extensions?: string[]; ```
- default `[".svelte"]`
List of file extensions that should be treated as Svelte files.
```dts kit?: KitConfig; ```
SvelteKit options
```dts preprocess?: any; ```
Preprocessor options, if any. Preprocessing can alternatively also be done through Vite's preprocessor capabilities.
```dts vitePlugin?: PluginOptions; ```
`vite-plugin-svelte` plugin options.
```dts [key: string]: any; ```
Any additional options required by tooling that integrates with Svelte.
## KitConfig The `kit` property configures SvelteKit, and can have the following properties: ## adapter - default `undefined`
Your [adapter](https://svelte.dev/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 ` ``` If you set `pollInterval` to a non-zero value, SvelteKit will poll for new versions in the background and set the value of the [`updated`](https://svelte.dev/docs/kit/$app-stores#updated) store to `true` when it detects one. ```ts // @noErrors name?: 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.js import * as child_process from 'node:child_process'; export default { kit: { version: { name: child_process.execSync('git rev-parse HEAD').toString().trim() } } }; ```
```ts // @noErrors pollInterval?: number; ```
- default `0`
The interval in milliseconds to poll for version changes. If this is `0`, no polling occurs.
## docs/kit/98-reference/52-cli.md
--- NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: Command Line Interface --- SvelteKit projects use [Vite](https://vitejs.dev), meaning you'll mostly use its CLI (albeit via `npm run dev/build/preview` scripts): - `vite dev` — start a development server - `vite build` — build a production version of your app - `vite preview` — run the production version locally However SvelteKit includes its own CLI for initialising your project: ## svelte-kit sync `svelte-kit sync` creates the `tsconfig.json` and all generated types (which you can import as `./$types` inside routing files) for your project. When you create a new project, it is listed as the `prepare` script and will be run automatically as part of the npm lifecycle, so you should not ordinarily have to run this command.
## docs/kit/98-reference/54-types.md
--- NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: Types --- ## Generated types The `RequestHandler` and `Load` types both accept a `Params` argument allowing you to type the `params` object. For example this endpoint expects `foo`, `bar` and `baz` params: ```js /// file: src/routes/[foo]/[bar]/[baz]/+page.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: true import type * as Kit from '@sveltejs/kit'; type RouteParams = { foo: string; bar: string; baz: string; }; export type PageServerLoad = Kit.ServerLoad; 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]/+page.server.js // @filename: $types.d.ts import type * as Kit from '@sveltejs/kit'; type RouteParams = { foo: string; bar: string; baz: string; } export type PageServerLoad = Kit.ServerLoad; // @filename: index.js // @errors: 2355 //cut /** @type {import('./$types').PageServerLoad} */ export async function GET({ params }) { // ... } ``` ```js /// file: src/routes/[foo]/[bar]/[baz]/+page.js // @filename: $types.d.ts import type * as Kit from '@sveltejs/kit'; type RouteParams = { foo: string; bar: string; baz: string; } export type PageLoad = Kit.Load; // @filename: index.js // @errors: 2355 //cut /** @type {import('./$types').PageLoad} */ export async function load({ params, fetch }) { // ... } ``` > > `{ "extends": "./.svelte-kit/tsconfig.json" }` ### Default tsconfig.json The 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": { "baseUrl": "..", "paths": { "$lib": "src/lib", "$lib/*": "src/lib/*" }, "rootDirs": ["..", "./types"] }, "include": ["../src/**/*.js", "../src/**/*.ts", "../src/**/*.svelte"], "exclude": ["../node_modules/**", "./**"] } ``` 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-preprocess cannot // otherwise compile components correctly "importsNotUsedAsValues": "error", // Vite compiles one TypeScript module // at a time, rather than compiling // the entire module graph "isolatedModules": true, // TypeScript cannot 'see' when you // use an imported value in your // markup, so we need this "preserveValueImports": true, // This ensures both `vite build` // and `svelte-package` work correctly "lib": ["esnext", "DOM", "DOM.Iterable"], "moduleResolution": "node", "module": "esnext", "target": "esnext" } } ``` ## $lib This 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/server A 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.ts The `app.d.ts` file is home to the ambient types of your apps, i.e. types that are available without explicitly importing them. Always part of this file is the `App` namespace. This namespace contains several types that influence the shape of certain SvelteKit features you interact with. ## Error Defines 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. ```dts interface Error {/*…*/} ```
```dts message: string; ```
## Locals The interface that defines `event.locals`, which can be accessed in server [hooks](/docs/kit/hooks) (`handle`, and `handleError`), server-only `load` functions, and `+server.js` files. ```dts interface Locals {} ```
## PageData Defines the common shape of the [$page.data 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`). ```dts interface PageData {} ```
## PageState The 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`. ```dts interface PageState {} ```
## Platform If your adapter provides [platform-specific context](/docs/kit/adapters#Platform-specific-context) via `event.platform`, you can specify it here. ```dts interface Platform {} ```
Instructions for LLMs: Always use Svelte 5 runes and Svelte 5 syntax. Runes do not need to be imported, they are globals. $state() runes are always declared using `let`, never with `const`. When passing a function to $derived, you must always use $derived.by(() => ...). Error boundaries can only catch errors during component rendering and at the top level of an $effect inside the error boundary. Error boundaries do not catch errors in onclick or other event handlers.