diff --git a/apps/svelte.dev/content/docs/kit/10-getting-started/10-introduction.md b/apps/svelte.dev/content/docs/kit/10-getting-started/10-introduction.md index b9d6a62482..52e2eab278 100644 --- a/apps/svelte.dev/content/docs/kit/10-getting-started/10-introduction.md +++ b/apps/svelte.dev/content/docs/kit/10-getting-started/10-introduction.md @@ -12,7 +12,7 @@ title: Introduction SvelteKit is a framework for rapidly developing robust, performant web applications using [Svelte](https://svelte.dev/). If you're coming from React, SvelteKit is similar to Next. If you're coming from Vue, SvelteKit is similar to Nuxt. -To learn more about the kinds of applications you can build with SvelteKit, see the [FAQ](faq#what-can-i-make-with-sveltekit). +To learn more about the kinds of applications you can build with SvelteKit, see the [FAQ](faq#What-can-I-make-with-SvelteKit). ## What is Svelte? diff --git a/apps/svelte.dev/content/docs/kit/10-getting-started/30-project-structure.md b/apps/svelte.dev/content/docs/kit/10-getting-started/30-project-structure.md index c0962bc5ba..5b7ac9a3cc 100644 --- a/apps/svelte.dev/content/docs/kit/10-getting-started/30-project-structure.md +++ b/apps/svelte.dev/content/docs/kit/10-getting-started/30-project-structure.md @@ -40,7 +40,7 @@ The `src` directory contains the meat of your project. Everything except `src/ro - `lib` contains your library code (utilities and components), which can be imported via the [`$lib`]($lib) alias, or packaged up for distribution using [`svelte-package`](packaging) - `server` contains your server-only library code. It can be imported by using the [`$lib/server`](server-only-modules) alias. SvelteKit will prevent you from importing these in client code. -- `params` contains any [param matchers](advanced-routing#matching) your app needs +- `params` contains any [param matchers](advanced-routing#Matching) your app needs - `routes` contains the [routes](routing) of your application. You can also colocate other components that are only used within a single route here - `app.html` is your page template — an HTML document containing the following placeholders: - `%sveltekit.head%` — `` and ` + +

{data.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.server.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!' }; + } +} +``` + +
+
+ +## LoadProperties + +
+ +```dts +type LoadProperties< + input extends Record | void +> = input extends void + ? undefined // needs to be undefined, because void will break intellisense + : input extends Record + ? input + : unknown; +``` + +
+ +## Navigation + +
+ +```dts +interface Navigation {/*…*/} +``` + +
+ +```dts +from: NavigationTarget | null; +``` + +
+ +Where navigation was triggered from + +
+
+ +
+ +```dts +to: NavigationTarget | null; +``` + +
+ +Where navigation is going to/has gone to + +
+
+ +
+ +```dts +type: Exclude; +``` + +
+ +The type of navigation: +- `form`: The user submitted a `
` +- `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 + +
+
+ +
+ +```dts +willUnload: boolean; +``` + +
+ +Whether or not the navigation will result in the page being unloaded (i.e. not a client-side navigation) + +
+
+ +
+ +```dts +delta?: number; +``` + +
+ +In case of a history back/forward navigation, the number of steps to go back/forward + +
+
+ +
+ +```dts +complete: Promise; +``` + +
+ +A promise that resolves once the navigation is complete, and rejects if the navigation +fails or is aborted. In the case of a `willUnload` navigation, the promise will never resolve + +
+
+ +## NavigationEvent + +
+ +```dts +interface NavigationEvent< + Params extends Partial> = Partial< + Record + >, + RouteId extends string | null = string | null +> {/*…*/} +``` + +
+ +```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 +url: URL; +``` + +
+ +The URL of the current page + +
+
+ +## NavigationTarget + +Information about the target of a specific navigation. + +
+ +```dts +interface NavigationTarget {/*…*/} +``` + +
+ +```dts +params: Record | null; +``` + +
+ +Parameters of the target page - e.g. for a route like `/blog/[slug]`, a `{ slug: string }` object. +Is `null` if the target is not part of the SvelteKit app (could not be resolved to a route). + +
+
+ +
+ +```dts +route: { id: string | null }; +``` + +
+ +Info about the target route + +
+
+ +
+ +```dts +url: URL; +``` + +
+ +The URL that is navigated to + +
+
+ +## NavigationType + +- `enter`: The app has hydrated +- `form`: The user submitted a `` 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`](https://kit.svelte.dev/docs/modules#$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://kit.svelte.dev/docs/modules#$app-navigation-pushstate) and [`replaceState`](https://kit.svelte.dev/docs/modules#$app-navigation-replacestate) functions from `$app/navigation`. + +
+
+ +
+ +```dts +form: any; +``` + +
+ +Filled only after a form submission. See [form actions](https://kit.svelte.dev/docs/form-actions) for more info. + +
+
+ +## ParamMatcher + +The shape of a param matcher. See [matching](https://kit.svelte.dev/docs/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`](https://kit.svelte.dev/docs/modules#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://kit.svelte.dev/docs/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://kit.svelte.dev/docs/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 [`handle hook`](https://kit.svelte.dev/docs/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(); +} +``` -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`](https://kit.svelte.dev/docs/modules#$app-paths-base) for that: `Link`. If you find yourself writing this often, it may make sense to extract this into a reusable component. +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://kit.svelte.dev/docs/types#public-types-cookies) API instead.
+
```dts -relative?: boolean; +url: URL; ```
-
- -- default `true` +The requested URL. +
-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](https://kit.svelte.dev/docs/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. +```dts +isDataRequest: boolean; +``` -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. +
-
-
+`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.
@@ -954,335 +1989,574 @@ In 1.0, `undefined` was a valid value, which was set by default. In that case, i
```dts -prerender?: {/*…*/} +isSubRequest: boolean; ```
-See [Prerendering](https://kit.svelte.dev/docs/page-options#prerender). +`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](https://kit.svelte.dev/docs/types#generated-types) instead. + +
```dts -concurrency?: number; +type RequestHandler< + Params extends Partial> = Partial< + Record + >, + RouteId extends string | null = string | null +> = ( + event: RequestEvent +) => MaybePromise; ``` -
+
-
+## Reroute -- default `1` +The [`reroute`](https://kit.svelte.dev/docs/hooks#universal-hooks-reroute) hook allows you to modify the URL before it is used to determine which route to render. -
+
-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. +```dts +type Reroute = (event: { url: URL }) => void | string; +```
-
+ +## ResolveOptions + +
+ +```dts +interface ResolveOptions {/*…*/} +``` +
```dts -crawl?: boolean; +transformPageChunk?(input: { html: string; done: boolean }): MaybePromise; ```
-- default `true` +- `input` the html chunk and the info if this is the last chunk
-Whether SvelteKit should find pages to prerender by following links from `entries`. +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 -entries?: Array<'*' | `/${string}`>; +filterSerializedResponseHeaders?(name: string, value: string): boolean; ```
-- default `["*"]` +- `name` header name +- `value` header value
-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). +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 -handleHttpError?: PrerenderHttpErrorHandlerValue; +preload?(input: { type: 'font' | 'css' | 'js' | 'asset'; path: string }): boolean; ```
-- default `"fail"` +- `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.
+
-How to respond to HTTP errors encountered while prerendering the app. +## RouteDefinition -- `'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); - } - } - } -}; +```dts +interface RouteDefinition {/*…*/} ``` -
-
```dts -handleMissingId?: PrerenderMissingIdHandlerValue; +id: string; ``` -
+
+
-
+
-- default `"fail"` +```dts +api: { + methods: Array; +}; +``` +
-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 +```dts +page: { + methods: Array>; +}; +``` +
-
+
```dts -handleEntryGeneratorMismatch?: PrerenderEntryGeneratorMismatchHandlerValue; +pattern: RegExp; ``` -
+
+
-
+
-- default `"fail"` +```dts +prerender: PrerenderOption; +``` +
-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 +```dts +segments: RouteSegment[]; +``` +
+ +
+ +```dts +methods: Array; +``` + +
+
```dts -origin?: string; +config: Config; ``` -
+
+
-
+## SSRManifest + +
+ +```dts +interface SSRManifest {/*…*/} +``` -- default `"http://sveltekit-prerender"` +
+ +```dts +appDir: string; +``` +
-The value of `url.origin` during prerendering; useful if it is included in rendered content. +
+ +```dts +appPath: string; +``` +
-
+
+ +```dts +assets: Set; +``` + +
+ +
+ +```dts +mimeTypes: Record; +``` + +
```dts -serviceWorker?: {/*…*/} +_: {/*…*/} ```
+private fields +
```dts -register?: boolean; +client: NonNullable; ``` -
- -
+
+
+
-- default `true` +```dts +nodes: SSRNodeLoader[]; +``` +
+
-Whether to automatically register the service worker, if it exists. +```dts +routes: SSRRoute[]; +``` +
+
+ +```dts +matchers(): Promise>; +``` + +
```dts -files?(filepath: string): boolean; +server_assets: Record; ```
-
- -- default `(filename) => !/\.DS_Store/.test(filename)` +A `[file]: size` map of all assets imported by server code
- -Determine which files in your `static` directory will be available in `$service-worker.files`. +
+## Server + +
+ +```dts +class Server {/*…*/} +``` + +
+ +```dts +constructor(manifest: SSRManifest); +``` + +
+ +
+ +```dts +init(options: ServerInitOptions): Promise; +``` + +
```dts -typescript?: {/*…*/} +respond(request: Request, options: RequestOptions): Promise; ``` -
+
+
-
+## ServerInitOptions + +
```dts -config?: (config: Record) => Record | void; +interface ServerInitOptions {/*…*/} ``` -
+
-
+```dts +env: Record; +``` + +
-- default `(config) => config` +A map of environment variables
+
+ +
+ +```dts +read?: (file: string) => ReadableStream; +``` + +
-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. +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](https://kit.svelte.dev/docs/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 -version?: {/*…*/} +parent(): Promise; ```
-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 - -``` +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. -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://kit.svelte.dev/docs/modules#$app-stores-updated) store to `true` when it detects one. +
+
-
+
```dts -name?: string; +depends(...deps: string[]): void; ```
-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. +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://kit.svelte.dev/docs/modules#$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`. -For example, to use the current commit hash, you could do use `git rev-parse HEAD`: +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: 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() - } +/// 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}

+ ```

+
```dts -pollInterval?: number; +untrack(fn: () => T): T; ```
-
+Use this function to opt out of dependency tracking for everything that is synchronously called within the callback. Example: -- default `0` +```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 {/*…*/} +``` -The interval in milliseconds to poll for version changes. If this is `0`, no polling occurs. +
+ +```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) +>; +``` +
-
diff --git a/apps/svelte.dev/content/docs/kit/98-reference/20-$app-paths.md b/apps/svelte.dev/content/docs/kit/98-reference/20-$app-paths.md index ca3b091db8..5f94701bfd 100644 --- a/apps/svelte.dev/content/docs/kit/98-reference/20-$app-paths.md +++ b/apps/svelte.dev/content/docs/kit/98-reference/20-$app-paths.md @@ -13,7 +13,7 @@ import { assets, base, resolveRoute } from '$app/paths'; An absolute path that matches [`config.kit.paths.assets`](https://kit.svelte.dev/docs/configuration#paths). -> If a value for `config.kit.paths.assets` is specified, it will be replaced with `'/_svelte_kit_assets'` during `vite dev` or `vite preview`, since the assets don't yet live at their eventual URL. +> [!NOTE] If a value for `config.kit.paths.assets` is specified, it will be replaced with `'/_svelte_kit_assets'` during `vite dev` or `vite preview`, since the assets don't yet live at their eventual URL.
diff --git a/apps/svelte.dev/content/docs/kit/98-reference/50-configuration.md b/apps/svelte.dev/content/docs/kit/98-reference/50-configuration.md index a5da3e4d3c..5478631d64 100644 --- a/apps/svelte.dev/content/docs/kit/98-reference/50-configuration.md +++ b/apps/svelte.dev/content/docs/kit/98-reference/50-configuration.md @@ -26,6 +26,8 @@ const config = { export default config; ``` +## Config +
```dts @@ -124,6 +126,8 @@ Any additional options required by tooling that integrates with Svelte. +## KitConfig + The `kit` property configures SvelteKit, and can have the following properties: ## adapter @@ -174,9 +178,9 @@ const config = { }; ``` -> The built-in `$lib` alias is controlled by `config.kit.files.lib` as it is used for packaging. +> [!NOTE] The built-in `$lib` alias is controlled by `config.kit.files.lib` as it is used for packaging. -> You will need to run `npm run dev` to have SvelteKit automatically generate the required alias configuration in `jsconfig.json` or `tsconfig.json`. +> [!NOTE] You will need to run `npm run dev` to have SvelteKit automatically generate the required alias configuration in `jsconfig.json` or `tsconfig.json`.
@@ -222,8 +226,10 @@ const config = { directives: { 'script-src': ['self'] }, + // must be specified with either the `report-uri` or `report-to` directives, or both reportOnly: { - 'script-src': ['self'] + 'script-src': ['self'], + 'report-uri': ['/'] } } } @@ -238,11 +244,11 @@ To add a nonce for scripts and links manually included in `src/app.html`, you ma When pages are prerendered, the CSP header is added via a `` tag (note that in this case, `frame-ancestors`, `report-uri` and `sandbox` directives will be ignored). -> When `mode` is `'auto'`, SvelteKit will use nonces for dynamically rendered pages and hashes for prerendered pages. Using nonces with prerendered pages is insecure and therefore forbidden. +> [!NOTE] When `mode` is `'auto'`, SvelteKit will use nonces for dynamically rendered pages and hashes for prerendered pages. Using nonces with prerendered pages is insecure and therefore forbidden. -> Note that most [Svelte transitions](https://svelte.dev/tutorial/transition) work by creating an inline `