This is the abridged developer documentation for Svelte and SvelteKit. # Start of Svelte documentation # Overview Svelte is a framework for building user interfaces on the web. It uses a compiler to turn declarative components written in HTML, CSS and JavaScript... ```svelte ``` ...into lean, tightly optimized JavaScript. You can use it to build anything on the web, from standalone components to ambitious full stack apps (using Svelte's companion application framework, [SvelteKit](../kit)) and everything in between. These pages serve as reference documentation. If you're new to Svelte, we recommend starting with the [interactive tutorial](/tutorial) and coming back here when you have questions. You can also try Svelte online in the playground. # Getting started We recommend using [SvelteKit](../kit), which lets you [build almost anything](../kit/project-types). It's the official application framework from the Svelte team and powered by [Vite](https://vite.dev/). Create a new project with: ```sh npx sv create myapp cd myapp npm install npm run dev ``` Don't worry if you don't know Svelte yet! You can ignore all the nice features SvelteKit brings on top for now and dive into it later. ## Alternatives to SvelteKit You can also use Svelte directly with Vite via [vite-plugin-svelte](https://github.com/sveltejs/vite-plugin-svelte) by running `npm create vite@latest` and selecting the `svelte` option (or, if working with an existing project, adding the plugin to your `vite.config.js` file). With this, `npm run build` will generate HTML, JS, and CSS files inside the `dist` directory. In most cases, you will probably need to [choose a routing library](/packages#routing) as well. >[!NOTE] Vite is often used in standalone mode to build [single page apps (SPAs)](../kit/glossary#SPA), which you can also [build with SvelteKit](../kit/single-page-apps). There are also [plugins for other bundlers](/packages#bundler-plugins), but we recommend Vite. To add Svelte to pages served by a backend that isn't written in JavaScript, such as Rails or Laravel, follow Vite's [backend integration guide](https://vite.dev/guide/backend-integration) and render components into the page with [`mount`](imperative-component-api#mount). ## Editor tooling The Svelte team maintains a [VS Code extension](https://marketplace.visualstudio.com/items?itemName=svelte.svelte-vscode), and there are integrations with various other [editors](https://sveltesociety.dev/collection/editor-support-c85c080efc292a34) and tools as well. You can also check your code from the command line using [`npx sv check`](https://svelte.dev/docs/cli/sv-check). ## Getting help Don't be shy about asking for help in the [Discord chatroom](/chat)! You can also find answers on [Stack Overflow](https://stackoverflow.com/questions/tagged/svelte). # .svelte files Components are the building blocks of Svelte applications. They are written into `.svelte` files, using a superset of HTML. All three sections — script, styles and markup — are optional. ```svelte /// file: MyComponent.svelte ``` ## ` ``` You can `export` bindings from this block, and they will become exports of the compiled module. You cannot `export default`, since the default export is the component itself. > In Svelte 4, this script tag was created using ` ``` Unlike other frameworks you may have encountered, there is no API for interacting with state — `count` is just a number, rather than an object or a function, and you can update it like you would update any other variable. ### Deep state If `$state` is used with an array or a simple object, the result is a deeply reactive _state proxy_. [Proxies](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy) allow Svelte to run code when you read or write properties, including via methods like `array.push(...)`, triggering granular updates. State is proxified recursively until Svelte finds something other than an array or simple object (like a class or an object created with `Object.create`). In a case like this... ```js let todos = $state([ { done: false, text: 'add more todos' } ]); ``` ...modifying an individual todo's property will trigger updates to anything in your UI that depends on that specific property: ```js let todos = [{ done: false, text: 'add more todos' }]; // ---cut--- todos[0].done = !todos[0].done; ``` If you push a new object to the array, it will also be proxified: ```js let todos = [{ done: false, text: 'add more todos' }]; // ---cut--- todos.push({ done: false, text: 'eat lunch' }); ``` Note that if you destructure a reactive value, the references are not reactive — as in normal JavaScript, they are evaluated at the point of destructuring: ```js let todos = [{ done: false, text: 'add more todos' }]; // ---cut--- let { done, text } = todos[0]; // this will not affect the value of `done` todos[0].done = !todos[0].done; ``` ### Classes Class instances are not proxied. Instead, you can use `$state` in class fields (whether public or private), or as the first assignment to a property immediately inside the `constructor`: ```js // @errors: 7006 2554 class Todo { done = $state(false); constructor(text) { this.text = $state(text); } reset() { this.text = ''; this.done = false; } } ``` When calling methods in JavaScript, the value of [`this`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this) matters. This won't work, because `this` inside the `reset` method will be the ` ``` You can either use an inline function... ```svelte ``` ...or use an arrow function in the class definition: ```js // @errors: 7006 2554 class Todo { done = $state(false); constructor(text) { this.text = $state(text); } +++reset = () => {+++ this.text = ''; this.done = false; } } ``` ### Built-in classes Svelte provides reactive implementations of built-in classes like `Set`, `Map`, `Date` and `URL` that can be imported from [`svelte/reactivity`](svelte-reactivity). ## `$state.raw` In cases where you don't want objects and arrays to be deeply reactive you can use `$state.raw`. State declared with `$state.raw` cannot be mutated; it can only be _reassigned_. In other words, rather than assigning to a property of an object, or using an array method like `push`, replace the object or array altogether if you'd like to update it: ```js let person = $state.raw({ name: 'Heraclitus', age: 49 }); // this will have no effect person.age += 1; // this will work, because we're creating a new person person = { name: 'Heraclitus', age: 50 }; ``` This can improve performance with large arrays and objects that you weren't planning to mutate anyway, since it avoids the cost of making them reactive. Note that raw state can _contain_ reactive state (for example, a raw array of reactive objects). As with `$state`, you can declare class fields using `$state.raw`. ## `$state.snapshot` To take a static snapshot of a deeply reactive `$state` proxy, use `$state.snapshot`: ```svelte ``` This is handy when you want to pass some state to an external library or API that doesn't expect a proxy, such as `structuredClone`. If a value has a `toJSON` method, the snapshot will clone the value returned from `toJSON` instead of the original object. ## `$state.eager` When state changes, it may not be reflected in the UI immediately if it is used by an `await` expression, because [updates are synchronized](await-expressions#Synchronized-updates). In some cases, you may want to update the UI as soon as the state changes. For example, you might want to update a navigation bar when the user clicks on a link, so that they get visual feedback while waiting for the new page to load. To do this, use `$state.eager(value)`: ```svelte ``` Use this feature sparingly, and only to provide feedback in response to user action — in general, allowing Svelte to coordinate updates will provide a better user experience. ## Passing state into functions JavaScript is a _pass-by-value_ language — when you call a function, the arguments are the _values_ rather than the _variables_. In other words: ```js /// file: index.js // @filename: index.js // ---cut--- /** * @param {number} a * @param {number} b */ function add(a, b) { return a + b; } let a = 1; let b = 2; let total = add(a, b); console.log(total); // 3 a = 3; b = 4; console.log(total); // still 3! ``` If `add` wanted to have access to the _current_ values of `a` and `b`, and to return the current `total` value, you would need to use functions instead: ```js /// file: index.js // @filename: index.js // ---cut--- /** * @param {() => number} getA * @param {() => number} getB */ function add(+++getA, getB+++) { return +++() => getA() + getB()+++; } let a = 1; let b = 2; let total = add+++(() => a, () => b)+++; console.log(+++total()+++); // 3 a = 3; b = 4; console.log(+++total()+++); // 7 ``` State in Svelte is no different — when you reference something declared with the `$state` rune... ```js let a = +++$state(1)+++; let b = +++$state(2)+++; ``` ...you're accessing its _current value_. Note that 'functions' is broad — it encompasses properties of proxies and [`get`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get)/[`set`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/set) properties... ```js /// file: index.js // @filename: index.js // ---cut--- /** * @param {{ a: number, b: number }} input */ function add(input) { return { get value() { return input.a + input.b; } }; } let input = $state({ a: 1, b: 2 }); let total = add(input); console.log(total.value); // 3 input.a = 3; input.b = 4; console.log(total.value); // 7 ``` ...though if you find yourself writing code like that, consider using [classes](#Classes) instead. ## Passing state across modules You can declare state in `.svelte.js` and `.svelte.ts` files, but you can only _export_ that state if it's not directly reassigned. In other words you can't do this: ```js /// file: state.svelte.js export let count = $state(0); export function increment() { count += 1; } ``` That's because every reference to `count` is transformed by the Svelte compiler — the code above is roughly equivalent to this: ```js /// file: state.svelte.js (compiler output) // @filename: index.ts interface Signal { value: T; } interface Svelte { state(value?: T): Signal; get(source: Signal): T; set(source: Signal, value: T): void; } declare const $: Svelte; // ---cut--- export let count = $.state(0); export function increment() { $.set(count, $.get(count) + 1); } ``` Since the compiler only operates on one file at a time, if another file imports `count` Svelte doesn't know that it needs to wrap each reference in `$.get` and `$.set`: ```js // @filename: state.svelte.js export let count = 0; // @filename: index.js // ---cut--- import { count } from './state.svelte.js'; console.log(typeof count); // 'object', not 'number' ``` This leaves you with two options for sharing state between modules — either don't reassign it... ```js // This is allowed — since we're updating // `counter.count` rather than `counter`, // Svelte doesn't wrap it in `$.state` export const counter = $state({ count: 0 }); export function increment() { counter.count += 1; } ``` ...or don't directly export it: ```js let count = $state(0); export function getCount() { return count; } export function increment() { count += 1; } ``` # $derived Derived state is declared with the `$derived` rune: ```svelte

{count} doubled is {doubled}

``` The expression inside `$derived(...)` should be free of side-effects. Svelte will disallow state changes (e.g. `count++`) inside derived expressions. As with `$state`, you can mark class fields as `$derived`. ## `$derived.by` Sometimes you need to create complex derivations that don't fit inside a short expression. In these cases, you can use `$derived.by` which accepts a function as its argument. ```svelte ``` In essence, `$derived(expression)` is equivalent to `$derived.by(() => expression)`. ## Understanding dependencies Anything read synchronously inside the `$derived` expression (or `$derived.by` function body) is considered a _dependency_ of the derived state. When the state changes, the derived will be marked as _dirty_ and recalculated when it is next read. In addition, if an expression contains an [`await`](await-expressions), Svelte transforms it such that any state _after_ the `await` is also tracked — in other words, in a case like this... ```js let a = Promise.resolve(1); let b = 2; // ---cut--- let total = $derived(await a + b); ``` ...both `a` and `b` are tracked, even though `b` is only read once `a` has resolved, after the initial execution. (This does not apply to `await` in functions that are called by the expression, only the expression itself.) To exempt a piece of state from being treated as a dependency, use [`untrack`](svelte#untrack). ## Overriding derived values Derived expressions are recalculated when their dependencies change, but you can temporarily override their values by reassigning them (unless they are declared with `const`). This can be useful for things like _optimistic UI_, where a value is derived from the 'source of truth' (such as data from your server) but you'd like to show immediate feedback to the user: ```svelte ``` ## Deriveds and reactivity Unlike `$state`, which converts objects and arrays to [deeply reactive proxies]($state#Deep-state), `$derived` values are left as-is. For example, [in a case like this](/REMOVED)... ```js // @errors: 7005 let items = $state([ /*...*/ ]); let index = $state(0); let selected = $derived(items[index]); ``` ...you can change (or `bind:` to) properties of `selected` and it will affect the underlying `items` array. If `items` was _not_ deeply reactive, mutating `selected` would have no effect. ## Destructuring If you use destructuring with a `$derived` declaration, the resulting variables will all be reactive — this... ```js function stuff() { return { a: 1, b: 2, c: 3 } } // ---cut--- let { a, b, c } = $derived(stuff()); ``` ...is roughly equivalent to this: ```js function stuff() { return { a: 1, b: 2, c: 3 } } // ---cut--- let _stuff = $derived(stuff()); let a = $derived(_stuff.a); let b = $derived(_stuff.b); let c = $derived(_stuff.c); ``` ## Update propagation Svelte uses something called _push-pull reactivity_ — when state is updated, everything that depends on the state (whether directly or indirectly) is immediately notified of the change (the 'push'), but derived values are not re-evaluated until they are actually read (the 'pull'). If the new value of a derived is referentially identical to its previous value, downstream updates will be skipped. In other words, Svelte will only update the text inside the button when `large` changes, not when `count` changes, even though `large` depends on `count`: ```svelte ``` # $effect Effects are functions that run when state updates, and can be used for things like calling third-party libraries, drawing on `` elements, or making network requests. They only run in the browser, not during server-side rendering. Generally speaking, you should _not_ update state inside effects, as it will make code more convoluted and will often lead to never-ending update cycles. If you find yourself doing so, see [when not to use `$effect`](#When-not-to-use-$effect) to learn about alternative approaches. You can create an effect with the `$effect` rune ([demo](/REMOVED)): ```svelte ``` When Svelte runs an effect function, it tracks which pieces of state (and derived state) are accessed (unless accessed inside [`untrack`](svelte#untrack)), and re-runs the function when that state later changes. ### Understanding lifecycle Your effects run after the component has been mounted to the DOM, and in a [microtask](https://developer.mozilla.org/en-US/docs/Web/API/HTML_DOM_API/Microtask_guide) after state changes. Re-runs are batched (i.e. changing `color` and `size` in the same moment won't cause two separate runs), and happen after any DOM updates have been applied. You can use `$effect` anywhere, not just at the top level of a component, as long as it is called while a parent effect is running. An effect can return a _teardown function_ which will run immediately before the effect re-runs: ```svelte

{count}

``` Teardown functions also run when the effect is destroyed, which happens when its parent is destroyed (for example, a component is unmounted) or the parent effect re-runs. ### Understanding dependencies `$effect` automatically picks up any reactive values (`$state`, `$derived`, `$props`) that are _synchronously_ read inside its function body (including indirectly, via function calls) and registers them as dependencies. When those dependencies change, the `$effect` schedules a re-run. If `$state` and `$derived` are used directly inside the `$effect` (for example, during creation of a [reactive class](https://svelte.dev/docs/svelte/$state#Classes)), those values will _not_ be treated as dependencies. Values that are read _asynchronously_ — after an `await` or inside a `setTimeout`, for example — will not be tracked. Here, the canvas will be repainted when `color` changes, but not when `size` changes ([demo](/REMOVED)): ```ts // @filename: index.ts declare let canvas: { width: number; height: number; getContext(type: '2d', options?: CanvasRenderingContext2DSettings): CanvasRenderingContext2D; }; declare let color: string; declare let size: number; // ---cut--- $effect(() => { const context = canvas.getContext('2d'); context.clearRect(0, 0, canvas.width, canvas.height); // this will re-run whenever `color` changes... context.fillStyle = color; setTimeout(() => { // ...but not when `size` changes context.fillRect(0, 0, size, size); }, 0); }); ``` An effect only reruns when the object it reads changes, not when a property inside it changes. (If you want to observe changes _inside_ an object at dev time, you can use [`$inspect`]($inspect).) ```svelte

{state.value} doubled is {derived.value}

``` An effect only depends on the values that it read the last time it ran. This has interesting implications for effects that have conditional code. For instance, if `condition` is `true` in the code snippet below, the code inside the `if` block will run and `color` will be evaluated. This means that changes to either `condition` or `color` [will cause the effect to re-run](/REMOVED). Conversely, if `condition` is `false`, `color` will not be evaluated, and the effect will _only_ re-run again when `condition` changes. ```ts // @filename: ambient.d.ts declare module 'canvas-confetti' { interface ConfettiOptions { colors: string[]; } function confetti(opts?: ConfettiOptions): void; export default confetti; } // @filename: index.js // ---cut--- import confetti from 'canvas-confetti'; let condition = $state(true); let color = $state('#ff3e00'); $effect(() => { if (condition) { confetti({ colors: [color] }); } else { confetti(); } }); ``` ## `$effect.pre` In rare cases, you may need to run code _before_ the DOM updates. For this we can use the `$effect.pre` rune: ```svelte
{#each messages as message}

{message}

{/each}
``` `$effect.pre` runs before DOM updates that are scheduled after it, not before every DOM mutation in the flush - DOM of parent components may already be updated. When using [await expressions](await-expressions), block updates like `{#if ...}` and `{#each ...}` in the same component also run before `$effect.pre`. Apart from the timing, `$effect.pre` works exactly like `$effect`. ## `$effect.tracking` The `$effect.tracking` rune is an advanced feature that tells you whether or not the code is running inside a tracking context, such as an effect or inside your template: ```svelte

in template: {$effect.tracking()}

``` It is used to implement abstractions like [`createSubscriber`](/docs/svelte/svelte-reactivity#createSubscriber), which will create listeners to update reactive values but _only_ if those values are being tracked (rather than, for example, read inside an event handler). ## `$effect.pending` When using [`await`](await-expressions) in components, the `$effect.pending()` rune tells you how many promises are pending in the current [boundary](svelte-boundary), not including child boundaries: ```svelte

{a} + {b} = {await add(a, b)}

{#if $effect.pending()}

pending promises: {$effect.pending()}

{/if} ``` ## `$effect.root` The `$effect.root` rune is an advanced feature that creates a non-tracked scope that doesn't auto-cleanup. This is useful for nested effects that you want to manually control. This rune also allows for the creation of effects outside of the component initialisation phase. ```js const destroy = $effect.root(() => { $effect(() => { // setup }); return () => { // cleanup }; }); // later... destroy(); ``` ## When not to use `$effect` In general, `$effect` is best considered something of an escape hatch — useful for things like analytics and direct DOM manipulation — rather than a tool you should use frequently. In particular, avoid using it to synchronise state. Instead of this... ```svelte ``` ...do this: ```svelte ``` If you're using an effect because you want to be able to reassign the derived value (to build an optimistic UI, for example) note that [deriveds can be directly overridden]($derived#Overriding-derived-values) as of Svelte 5.25. You might be tempted to do something convoluted with effects to link one value to another. The following example shows two inputs for "money spent" and "money left" that are connected to each other. If you update one, the other should update accordingly. Instead of using effects for this... ```svelte ``` ...use `oninput` callbacks or — better still — [function bindings](bind#Function-bindings) where possible: ```svelte ``` If you absolutely have to update `$state` within an effect and run into an infinite loop because you read and write to the same `$state`, use [untrack](svelte#untrack). # $props The inputs to a component are referred to as _props_, which is short for _properties_. You pass props to components just like you pass attributes to elements: ```svelte ``` On the other side, inside `MyComponent.svelte`, we can receive props with the `$props` rune... ```svelte

this component is {props.adjective}

``` ...though more commonly, you'll [_destructure_](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) your props: ```svelte

this component is {+++adjective+++}

``` ## Fallback values Destructuring allows us to declare fallback values, which are used if the parent component does not set a given prop (or the value is `undefined`): ```js let { adjective = 'happy' } = $props(); ``` ## Renaming props We can also use the destructuring assignment to rename props, which is necessary if they're invalid identifiers, or a JavaScript keyword like `super`: ```js let { super: trouper = 'lights are gonna find me' } = $props(); ``` ## Rest props Finally, we can use a _rest property_ to get, well, the rest of the props: ```js let { a, b, c, ...others } = $props(); ``` ## Updating props References to a prop inside a component update when the prop itself updates — when `count` changes in `App.svelte`, it will also change inside `Child.svelte`. But the child component is able to temporarily override the prop value, which can be useful for unsaved ephemeral state: ```svelte ``` ```svelte ``` While you can temporarily _reassign_ props, you should not _mutate_ props unless they are [bindable]($bindable). If the prop is a regular object, the mutation will have no effect: ```svelte ``` ```svelte ``` If the prop is a reactive state proxy, however, then mutations _will_ have an effect but you will see an [`ownership_invalid_mutation`](runtime-warnings#Client-warnings-ownership_invalid_mutation) warning, because the component is mutating state that does not 'belong' to it: ```svelte ``` ```svelte ``` The fallback value of a prop not declared with `$bindable` is left untouched — it is not turned into a reactive state proxy — meaning mutations will not cause updates: ```svelte ``` ```svelte ``` In summary: don't mutate props. Either use callback props to communicate changes, or — if parent and child should share the same object — use the [`$bindable`]($bindable) rune. ## Type safety You can add type safety to your components by annotating your props, as you would with any other variable declaration. In TypeScript that might look like this... ```svelte ``` ...while in JSDoc you can do this: ```svelte ``` You can, of course, separate the type declaration from the annotation: ```svelte ``` If your component exposes [snippet](snippet) props like `children`, these should be typed using the `Snippet` interface imported from `'svelte'` — see [Typing snippets](snippet#Typing-snippets) for examples. Adding types is recommended, as it ensures that people using your component can easily discover which props they should provide. ## `$props.id()` This rune, added in version 5.20.0, generates an ID that is unique to the current component instance. When hydrating a server-rendered component, the value will be consistent between server and client. This is useful for linking elements via attributes like `for` and `aria-labelledby`. ```svelte
``` # $bindable Ordinarily, props go one way, from parent to child. This makes it easy to understand how data flows around your app. In Svelte, component props can be _bound_, which means that data can also flow _up_ from child to parent. This isn't something you should do often — overuse can make your data flow unpredictable and your components harder to maintain — but it can simplify your code if used sparingly and carefully. It also means that a state proxy can be _mutated_ in the child. To mark a prop as bindable, we use the `$bindable` rune: ```svelte /// file: FancyInput.svelte ``` Now, a component that uses `` can add the [`bind:`](bind) directive ([demo](/REMOVED)): ```svelte /// file: App.svelte

{message}

``` The parent component doesn't _have_ to use `bind:` — it can just pass a normal prop. Some parents don't want to listen to what their children have to say. In this case, you can specify a fallback value for when no prop is passed at all: ```js /// file: FancyInput.svelte let { value = $bindable('fallback'), ...props } = $props(); ``` When a bindable prop has a fallback value, the parent must pass a value other than `undefined` if it uses `bind:`. This avoids ambiguity about which value should apply, since the parent and child should share the same value for a binding. # $inspect The `$inspect` rune is roughly equivalent to `console.log`, with the exception that it will re-run whenever its argument changes. `$inspect` tracks reactive state deeply, meaning that updating something inside an object or array using fine-grained reactivity will cause it to re-fire: ```svelte ``` On updates, a stack trace will be printed, making it easy to find the origin of a state change (unless you're in the playground, due to technical limitations). ## $inspect(...).with `$inspect(...)` returns an object with a `with` method, which you can invoke with a callback that will then be invoked instead of `console.log`. The first argument to the callback is either `"init"` or `"update"`; subsequent arguments are the values passed to `$inspect`: ```svelte ``` ## $inspect.trace(...) This rune, added in 5.14, causes the surrounding function to be _traced_ in development. Any time the function re-runs as part of an [effect]($effect) or a [derived]($derived), information will be printed to the console about which pieces of reactive state caused the effect to fire. ```svelte ``` `$inspect.trace` takes an optional first argument which will be used as the label. # $host When compiling a component as a [custom element](custom-elements), the `$host` rune provides access to the host element, allowing you to (for example) dispatch custom events ([demo](/REMOVED)): ```svelte /// file: Stepper.svelte ``` ```svelte /// file: App.svelte count -= 1} onincrement={() => count += 1} >

count: {count}

``` # Basic markup Markup inside a Svelte component can be thought of as HTML++. ## Tags A lowercase tag, like `
`, denotes a regular HTML element. A capitalised tag or a tag that uses dot notation, such as `` or ``, indicates a _component_. ```svelte
``` ## Element attributes By default, attributes work exactly like their HTML counterparts. ```svelte
``` As in HTML, values may be unquoted. ```svelte ``` Attribute values can contain JavaScript expressions. ```svelte page {p} ``` Or they can _be_ JavaScript expressions. ```svelte ``` Boolean attributes are included on the element if their value is [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy) and excluded if it's [falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy). All other attributes are included unless their value is [nullish](https://developer.mozilla.org/en-US/docs/Glossary/Nullish) (`null` or `undefined`). ```svelte
This div has no title attribute
``` > > > ```svelte > > ``` When the attribute name and value match (`name={name}`), they can be replaced with `{name}`. ```svelte ``` Form elements (``, `+++ ``` These attributes allow SvelteKit to set the correct input type, set a `name` that is used to construct the `data` passed to the handler, populate the `value` of the form (for example following a failed submission, to save the user having to re-enter everything), and set the [`aria-invalid`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Reference/Attributes/aria-invalid) state. Passing a second argument to `.as(...)` is useful when rendering a form from existing data, such as an edit form or multiple instances created with [`for(...)`](#form-Multiple-instances-of-a-form). As well as setting the value of the element when it is rendered, it controls the value of the element when the form is reset. `radio`, `submit` and `hidden` inputs always need this value, and `checkbox` inputs need it when they represent one option in an array field. For these `radio` and `checkbox` inputs the second argument identifies the option, so whether it is currently checked goes in a third argument, e.g. `.as('radio', option, settings.visibility === option)` or `.as('checkbox', tag, settings.tags.includes(tag))`. `file` inputs cannot be populated this way. Fields can be nested in objects and arrays, and their values can be strings, numbers, booleans or `File` objects. For example, if your schema looked like this... ```js /// file: data.remote.js import * as v from 'valibot'; import { form } from '$app/server'; // ---cut--- const datingProfile = v.object({ name: v.string(), photo: v.file(), info: v.object({ height: v.number(), likesDogs: v.optional(v.boolean(), false) }), attributes: v.array(v.string()) }); export const createProfile = form(datingProfile, (data) => { /* ... */ }); ``` ...your form could look like this: ```svelte

My best attributes

``` Because our form contains a `file` input, we've added an `enctype="multipart/form-data"` attribute. The values for `info.height` and `info.likesDogs` are coerced to a number and a boolean respectively. For a checkbox that must be checked, such as agreeing to terms of service, use `z.literal(true)` in Zod or `v.pipe(v.optional(v.boolean(), false), v.literal(true))` in Valibot. An unchecked checkbox will then fail validation. In the case of `radio` and `checkbox` inputs that all belong to the same field, the `value` must be specified as a second argument to `.as(...)`: ```js /// file: constants.js export const operatingSystems = /** @type {const} */ (['windows', 'mac', 'linux']); export const languages = /** @type {const} */ (['html', 'css', 'js']); ``` ```js /// file: data.remote.js // @filename: constants.js export const operatingSystems = /** @type {const} */ (['windows', 'mac', 'linux']); export const languages = /** @type {const} */ (['html', 'css', 'js']); // @filename: index.js import * as v from 'valibot'; import { form } from '$app/server'; // ---cut--- import { operatingSystems, languages } from './constants'; export const survey = form( v.object({ operatingSystem: v.picklist(operatingSystems), languages: v.optional(v.array(v.picklist(languages)), []), }), (data) => { /* ... */ }, ); ``` ```svelte

Which operating system do you use?

{#each operatingSystems as os} {/each}

Which languages do you write code in?

{#each languages as language} {/each}
``` Alternatively, you could use `select` and `select multiple`: ```svelte

Which operating system do you use?

Which languages do you write code in?

``` ### Programmatic validation In addition to declarative schema validation, you can programmatically mark fields as invalid inside the form handler using the `invalid` helper from `@sveltejs/kit`. This is useful for cases where you can't know if something is valid until you try to perform some action. - It throws just like `redirect` or `error` - It accepts multiple arguments that can be strings (for issues relating to the form as a whole — these will only show up in `fields.allIssues()`) or standard-schema-compliant issues (for those relating to a specific field). Use the `issue` parameter for type-safe creation of such issues: ```js // @errors: 18046 /// file: src/routes/shop/data.remote.js // @filename: ambient.d.ts declare module '#lib/server/database.js' { export function buy(qty: number): Promise } // @filename: index.js // ---cut--- import * as v from 'valibot'; import { invalid } from '@sveltejs/kit'; import { form } from '$app/server'; import * as db from '#lib/server/database.js'; export const buyHotcakes = form( v.object({ qty: v.pipe( v.number(), v.minValue(1, 'you must buy at least one hotcake') ) }), async (data, issue) => { try { await db.buy(data.qty); } catch (e) { if (e.code === 'OUT_OF_STOCK') { invalid( issue.qty(`we don't have enough hotcakes`) ); } } } ); ``` ### Validation If the submitted data doesn't pass the schema, the callback will not run. Instead, each invalid field's `issues()` method will return an array of `{ message: string }` objects, and the `aria-invalid` attribute (returned from `as(...)`) will be set to `true`: ```svelte
``` If the `title` is valid, or has not yet been validated, `createPost.fields.title.issues()` will return `undefined`. You don't need to wait until the form is submitted to validate the data — you can call `validate()` programmatically, for example in an `oninput` callback (which will validate the data on every keystroke) or an `onchange` callback: ```svelte
createPost.validate()}>
``` By default, issues will be ignored if they belong to form controls that haven't yet been interacted with. To validate _all_ inputs, call `validate({ all: true })`. For client-side validation, you can specify a _preflight_ schema which will populate `issues()` and prevent data being sent to the server if the data doesn't validate: ```svelte

Create a new post

``` To get a list of _all_ issues, rather than just those belonging to a single field, you can use the `fields.allIssues()` method: ```svelte {#each createPost.fields.allIssues() as issue}

{issue.message}

{/each} ``` As with individual fields, `createPost.fields.allIssues()` will return `undefined` if the form as a whole is valid (or has not yet been validated). ### Getting/setting inputs Each field has a `value()` method that reflects its current value. As the user interacts with the form, it is automatically updated: ```svelte

{createPost.fields.title.value()}

{@html render(createPost.fields.content.value())}
``` Alternatively, `createPost.fields.value()` would return a `{ title, content }` object. The `value()` of a field does _not_ reflect defaults provided as a second argument to `as` (as in `fields.title.as('text', '...')`) until it is edited or submitted. You can programmatically update a field (or a collection of fields) via the `set(...)` method: ```svelte ``` ### Handling sensitive data In the case of a non-progressively-enhanced form submission (i.e. where JavaScript is unavailable, for whatever reason) `value()` is also populated if the submitted data is invalid, so that the user does not need to fill the entire form out from scratch. You can prevent sensitive data (such as passwords and credit card numbers) from being sent back to the user by using a name with a leading underscore: ```svelte
``` In this example, if the data does not validate, only the first `` will be populated when the page reloads. ### Returns and redirects The example above uses [`redirect(...)`](@sveltejs-kit#redirect), which sends the user to the newly created page. Alternatively, the callback could return data, in which case it would be available as `createPost.result`: ```ts /// file: src/routes/blog/data.remote.js // @filename: ambient.d.ts declare module '#lib/server/database.js' { export function sql(strings: TemplateStringsArray, ...values: any[]): Promise; } declare module '#lib/server/auth.js' { interface User { name: string; } /** * Gets a user's info from their cookies, using `getRequestEvent` */ export function getUser(): Promise; } // @filename: index.js import * as v from 'valibot'; import { error, redirect } from '@sveltejs/kit'; import { query, form } from '$app/server'; import * as db from '#lib/server/database.js'; import * as auth from '#lib/server/auth.js'; export const getPosts = query(async () => { /* ... */ }); export const getPost = query(v.string(), async (slug) => { /* ... */ }); // ---cut--- export const createPost = form( v.object({/* ... */}), async (data) => { // ... return { success: true }; } ); ``` ```svelte

Create a new post

{#if createPost.result?.success}

Successfully published!

{/if} ``` This value is _ephemeral_ — it will vanish if you resubmit, navigate away, or reload the page. If an error occurs during submission, the nearest `+error.svelte` page will be rendered. ### enhance We can customize what happens when the form is submitted with the `enhance` method: ```svelte

Create a new post

{ try { if (await form.submit()) { form.element.reset(); showToast('Successfully published!'); } else { showToast('Invalid data!'); } } catch (error) { showToast('Oh no! Something went wrong'); } })}>
``` The callback receives a copy of the form instance. It has all the same properties and methods except `enhance`, and `form.submit()` performs the submission directly without re-running the enhance callback. Inside the callback, `form.element` is always defined. ### Multiple instances of a form Some forms may be repeated as part of a list. In this case you can create separate instances of a form function via `for(id)` to achieve isolation. When each instance should render different values, pass them as the second argument to `.as(...)`: ```svelte

Todos

{#each await getTodos() as todo (todo.id)} {const modify = modifyTodo.for(todo.id)}
{/each} ``` ### Multiple submit buttons It's possible for a `
` to have multiple submit buttons. For example, you might have a single form that allows you to log in or register depending on which button was clicked. To accomplish this, add a field to your schema for the button value, and use `as('submit', value)` to bind it: ```svelte
``` In your form handler, you can check which button was clicked: ```js /// file: #lib/auth.js import * as v from 'valibot'; import { form } from '$app/server'; export const loginOrRegister = form( v.object({ username: v.string(), _password: v.string(), action: v.picklist(['login', 'register']) }), async ({ username, _password, action }) => { if (action === 'login') { // handle login } else { // handle registration } } ); ``` ## command The `command` function, like `form`, allows you to write data to the server. Unlike `form`, it's not specific to an element and can be called from anywhere. As with `query` and `form`, if the function accepts an argument, it should be [validated](#query-Query-arguments) by passing a [Standard Schema](https://standardschema.dev) as the first argument to `command`. ```ts /// file: likes.remote.js // @filename: ambient.d.ts declare module '#lib/server/database.js' { export function sql(strings: TemplateStringsArray, ...values: any[]): Promise; } // @filename: index.js // ---cut--- import * as v from 'valibot'; import { query, command } from '$app/server'; import * as db from '#lib/server/database.js'; export const getLikes = query(v.string(), async (id) => { const [row] = await db.sql` SELECT likes FROM item WHERE id = ${id} `; return row.likes; }); export const addLike = command(v.string(), async (id) => { await db.sql` UPDATE item SET likes = likes + 1 WHERE id = ${id} `; }); ``` Now simply call `addLike`, from (for example) an event handler: ```svelte

likes: {await getLikes(item.id)}

``` ## Single-flight mutations The purpose of both [`form`](#form) and [`command`](#command) is *mutating data*. In many cases, mutating data invalidates other data. By default, `form` deals with this by automatically invalidating all queries and load functions following a successful submission, to emulate what would happen with a traditional full-page reload. `command`, on the other hand, does nothing. Typically, neither of these options is going to be the ideal solution — invalidating everything is likely wasteful, as it's unlikely a form submission changed *everything* being displayed on your webpage. In the case of `command`, doing nothing likely *under*-invalidates your app, leaving stale data displayed. In both cases, it's common to have to perform two round-trips to the server: One to run the mutation, and another after that completes to re-request the data from any queries you need to refresh. SvelteKit solves both of these problems with *single-flight mutations*: Your `form` submission or `command` invocation can refresh queries and pass their results back to the client in a single request. ### Server-driven refreshes In most circumstances, the server handler knows what client data needs to be updated based on its arguments: ```js import * as v from 'valibot'; import { error, redirect } from '@sveltejs/kit'; import { query, form } from '$app/server'; const slug = ''; const post = { id: '' }; /** @type {any} */ const externalApi = ''; // ---cut--- export const getPosts = query(async () => { /* ... */ }); export const getPost = query(v.string(), async (slug) => { /* ... */ }); export const createPost = form( v.object({/* ... */}), async (data) => { // form logic goes here... // Refresh `getPosts()` on the server, and send // the data back with the result of `createPost` // it's safe to throw away the promise from `refresh`, // as the framework awaits it for us before serving the response +++void getPosts().refresh();+++ // Redirect to the newly created page redirect(303, `/blog/${slug}`); } ); export const updatePost = form( v.object({ id: v.string() }), async (post) => { // form logic goes here... const result = externalApi.update(post); // The API already gives us the updated post, // no need to refresh it, we can set it directly +++getPost(post.id).set(result);+++ } ); ``` Because queries are keyed based on their arguments, `getPost(post.id).set(result)` on the server knows to look up the matching `getPost(id)` on the client to update it. The same goes for `getPosts().refresh()` -- it knows to look up `getPosts()` with no argument on the client. Calling `refresh()`, `set()` or `reconnect()` anywhere in a `form` handler replaces the default invalidation of all queries and load functions for that submission, so only the queries you refreshed will update. ### Reconnecting live queries in mutations Single-flight mutations can also reconnect `query.live` instances. In a `form`/`command` handler, call `.reconnect()` on the live query resource you want to reconnect: ```js import * as v from 'valibot'; import { form, query } from '$app/server'; export const getNotifications = query.live(v.string(), async function* (userId) { while (true) { yield await db.notifications(userId); await wait(1000); } }); export const markAllRead = form(v.object({ userId: v.string() }), async ({ userId }) => { // mutation logic... +++getNotifications(userId).reconnect();+++ }); ``` This schedules a reconnect for the matching active client instances and applies it as part of the mutation response (i.e. in the same flight as the form/command result). You might need this if, for example, the command modifies a cookie that the live query needs to restart in order to capture. ### Client-requested refreshes Unfortunately, life isn't always as simple as the preceding example. The server always knows which query _functions_ to update, but it may not know which specific query _instances_ to update. For example, if `getPosts({ filter: 'author:santa' })` is rendered on the client, calling `getPosts().refresh()` in the server handler won't update it. You'd need to call `getPosts({ filter: 'author:santa' }).refresh()` instead — but how could you know which specific combinations of filters are currently rendered on the client, especially if your query argument is more complicated than an object with just one key? SvelteKit makes this easy by allowing the client to _request_ that the server updates specific data using `submit().updates` (for `form`) or `myCommand().updates` (for `command`): ```ts import type { RemoteQueryUpdate, RemoteQuery } from '$app/server'; interface Post {} declare function submit(): Promise & { updates(...updates: RemoteQueryUpdate[]): Promise; } declare function getPosts(args: { filter: string }): RemoteQuery; declare const newPost: Post; // ---cut--- await submit().updates( // to request all active instances of getPosts getPosts, // to request a specific instance getPosts({ filter: 'author:santa' }), // to request a specific instance with an optimistic override getPosts({ filter: 'author:santa' }).withOverride((posts) => [newPost, ...posts]) ); ``` It's not enough to just request the updates from the client -- you need to accept them from the server as well: ```js import * as v from 'valibot'; import { error, redirect } from '@sveltejs/kit'; const slug = ''; const post = { id: '' }; /** @type {any} */ const externalApi = ''; // ---cut--- import { query, form, requested } from '$app/server'; export const getPosts = query(v.object({ filter: v.string() }), async ({ filter }) => { /* ... */ }); export const createPost = form( v.object({/* ... */}), async (data) => { // form logic goes here... +++for (const { query } of requested(getPosts, 1)) {+++ +++ void query.refresh();+++ +++}+++ // Redirect to the newly created page redirect(303, `/blog/${slug}`); } ); ``` `requested` gives you access to the queries the client requested to refresh. Each entry is an `{ arg, query, ignore }` object: `arg` is the value the query's implementation function received — i.e. the argument *after* the schema has validated and (where applicable) transformed it — and `query` is a `RemoteQuery` already bound to the client's original cache key, so calling `query.refresh()` / `query.set(...)` updates the correct client instance. Call `ignore()` if you intentionally do not want to update a particular instance: ```js import { requested, query } from '$app/server'; export const getPosts = query('unchecked', ({ filter }) => { return ['foo', 'bar']; }); // ---cut--- for (const { arg, query, ignore } of requested(getPosts, 10)) { if (arg.filter === 'author:santa') { void query.refresh(); } else { ignore(); } } ``` Every requested update must be refreshed, set, reconnected (for a live query), or explicitly ignored. Otherwise, the corresponding query will enter an error state on the client. If parsing or validating an argument fails, that query will also error, but the entire command will not fail. `requested`'s second parameter, `limit`, is the maximum number of items it will return. Any refresh requests beyond this limit will fail on the client. Additionally, `requested` allows a simple shorthand when all you want to do is refresh the requested query instances: ```ts import { requested } from '$app/server'; import type { RemoteQueryFunction } from '$app/server'; declare const getPosts: RemoteQueryFunction; // ---cut--- // this is the same as looping over the result and calling `void query.refresh()`. await requested(getPosts, 1).refreshAll(); ``` If you want to intentionally ignore every selected update, use `ignoreAll`: ```js import { requested, query } from '$app/server'; export const getPosts = query('unchecked', ({ filter }) => { return ['foo', 'bar']; }); // ---cut--- await requested(getPosts, 10).ignoreAll(); ``` `ignoreAll` only ignores entries within the specified `limit`. Any excess entries still fail on the client. > > - **Bundle size.** If a command could implicitly refresh *any* query in your app, SvelteKit would have to include every query's code in the command's server bundle, because it can't know ahead of time which ones will be called. > - **Denial-of-service.** Any malicious user can inspect their network tab to discover which queries your app uses, then POST a command with a client-supplied list of thousands of refreshes. The only defence is for the server handler to declare which queries it is willing to refresh — and in what quantity (hence the required `limit`). ## prerender The `prerender` function is similar to `query`, except that it will be invoked at build time to prerender the result. Use this for data that changes at most once per redeployment. ```js /// file: src/routes/blog/data.remote.js // @filename: ambient.d.ts declare module '#lib/server/database.js' { export function sql(strings: TemplateStringsArray, ...values: any[]): Promise; } // @filename: index.js // ---cut--- import { prerender } from '$app/server'; import * as db from '#lib/server/database.js'; export const getPosts = prerender(async () => { const posts = await db.sql` SELECT title, slug FROM post ORDER BY published_at DESC `; return posts; }); ``` You can use `prerender` functions on pages that are otherwise dynamic, allowing for partial prerendering of your data. This results in very fast navigation, since prerendered data can live on a CDN along with your other static assets. In the browser, prerendered data is saved using the [`Cache`](https://developer.mozilla.org/en-US/docs/Web/API/Cache) API. This cache survives page reloads, and will be cleared when the user first visits a new deployment of your app. ### Prerender arguments As with queries, prerender functions can accept an argument, which should be [validated](#query-Query-arguments) with a [Standard Schema](https://standardschema.dev/): ```js /// file: src/routes/blog/data.remote.js // @filename: ambient.d.ts declare module '#lib/server/database.js' { export function sql(strings: TemplateStringsArray, ...values: any[]): Promise; } // @filename: index.js // ---cut--- import * as v from 'valibot'; import { error } from '@sveltejs/kit'; import { prerender } from '$app/server'; import * as db from '#lib/server/database.js'; export const getPosts = prerender(async () => { /* ... */ }); export const getPost = prerender(v.string(), async (slug) => { const [post] = await db.sql` SELECT * FROM post WHERE slug = ${slug} `; if (!post) error(404, 'Not found'); return post; }); ``` Any calls to `getPost(...)` found by SvelteKit's crawler while [prerendering pages](page-options#prerender) will be saved automatically, but you can also specify which values it should be called with using the `inputs` option: ```js /// file: src/routes/blog/data.remote.js import * as v from 'valibot'; import { prerender } from '$app/server'; // ---cut--- export const getPost = prerender( v.string(), async (slug) => { /* ... */ }, { inputs: () => [ 'first-post', 'second-post', 'third-post' ] } ); ``` By default, prerender functions are excluded from your server bundle, which means that you cannot call them with any arguments that were _not_ prerendered. You can set `dynamic: true` to change this behaviour: ```js /// file: src/routes/blog/data.remote.js import * as v from 'valibot'; import { prerender } from '$app/server'; // ---cut--- export const getPost = prerender( v.string(), async (slug) => { /* ... */ }, { +++dynamic: true+++, inputs: () => [ 'first-post', 'second-post', 'third-post' ] } ); ``` ## Handling validation errors As long as _you're_ not passing invalid data to your remote functions, there are only two reasons why the argument passed to a `command`, `query` or `prerender` function would fail validation: - the function signature changed between deployments, and some users are currently on an older version of your app - someone is trying to attack your site by poking your exposed endpoints with bad data In the second case, we don't want to give the attacker any help, so SvelteKit will generate a generic [400 Bad Request](https://http.dog/400) response. Validation failures pass through the server [`handleError`](hooks#handleError) hook with `kind: 'validation'`, an `error` object containing `{ status, message }`, and the validation `issues`. You can use the issues to log the failure or customise the response: ```js /// file: src/hooks.server.js /** @type {import('@sveltejs/kit/hooks').HandleServerError} */ export function handleError({ kind, issues }) { if (kind === 'validation') { console.error(issues); return { message: 'Nice try, hacker!' }; } } ``` Be thoughtful about exposing validation issues, as they may give an attacker useful information. Returning `error` unchanged is safe — unlike `issues`, it only contains the generic status and message. If you know what you're doing and want to opt out of validation, you can pass the string `'unchecked'` in place of a schema: ```ts /// file: data.remote.ts import { query } from '$app/server'; export const getStuff = query('unchecked', async ({ id }: { id: string }) => { // the shape might not actually be what TypeScript thinks // since bad actors might call this function with other arguments }); ``` ## Using `getRequestEvent` Inside `query`, `form` and `command` you can use [`getRequestEvent`]($app-server#getRequestEvent) to get the current [`RequestEvent`](@sveltejs-kit#RequestEvent) object. This makes it easy to build abstractions for interacting with cookies, for example: ```ts /// file: user.remote.js // @filename: ambient.d.ts interface User { name: string; avatar: string; } declare module '#lib/server/database.js' { export function findUser(sessionId: string | undefined): Promise; } // @filename: index.js // ---cut--- import { getRequestEvent, query } from '$app/server'; import { findUser } from '#lib/server/database.js'; export const getProfile = query(async () => { const user = await getUser(); return user && { name: user.name, avatar: user.avatar }; }); // this query could be called from multiple places, but // the function will only run once per request const getUser = query(async () => { const { cookies } = getRequestEvent(); return await findUser(cookies.get('session_id')); }); ``` Note that some properties of `RequestEvent` are different inside remote functions: - you cannot set headers (other than writing cookies, and then only inside `form` and `command` functions) - inside `query` functions (including `query.batch` and `query.live`), accessing `route`, `params` or `url` throws an error. Queries are cached by their arguments and are not re-run when the user navigates, so results depending on these values would go stale without the cache noticing. Pass values from the page as arguments to the query instead. You can still derive trusted context from cookies or headers in the [`handle`](hooks#handle) hook and put it on `locals`, but note that for query requests `handle` sees the URL of the remote endpoint, not of the page - in `form` and `command` functions, `route`, `params` and `url` relate to the page the remote function was called from, _not_ the URL of the endpoint SvelteKit creates for the remote function. Never use them to determine whether or not a user is authorized to access certain data, as these values are part of the request which could be manipulated ## Implications for authentication Since a remote function call can come from any page, the request event URL may be manipulated by the client. Therefore, you _must_ run your authentication checks directly inside your remote functions that need it. This check can be created as a shared helper: ```js /// file: src/lib/server/auth.js // @filename: ambient.d.ts interface User { id: string; name: string; } declare namespace App { interface Locals { user: User | null; } } // @filename: index.js // ---cut--- import { redirect } from '@sveltejs/kit'; import { getRequestEvent } from '$app/server'; export function requireLogin() { const { locals } = getRequestEvent(); if (!locals.user) redirect(303, '/login'); return locals.user; } ``` Now you can use it in whichever remote functions require authentication: ```js /// file: src/lib/projects.remote.js // @filename: ambient.d.ts declare module '#lib/server/auth.js' { export function requireLogin(): { id: string; name: string }; } declare module '#lib/server/database.js' { export function getProjects( userId: string ): Promise>; } // @filename: index.js // ---cut--- import { query } from '$app/server'; import { requireLogin } from '#lib/server/auth.js'; import { getProjects } from '#lib/server/database.js'; export const getMyProjects = query(async () => { const user = requireLogin(); return await getProjects(user.id); }); ``` Now, any component that calls `getMyProjects` will only be rendered if the user is logged in, regardless of which page uses it: ```svelte
    {#each await getMyProjects() as project (project.id)}
  • {project.name}
  • {/each}
``` ## Redirects Inside `query`, `form` and `prerender` functions it is possible to use the [`redirect(...)`](@sveltejs-kit#redirect) function. It is *not* possible inside `command` functions, as you should avoid redirecting here. (If you absolutely have to, you can return a `{ redirect: location }` object and deal with it in the client.) # Environment variables Environment variables are values your app needs that exist separately from the app's source code. They allow you to use sensitive information like API keys and database credentials without storing them in version control. During development, and at build time, variables defined in a `.env` or `.env.local` file will be added to the environment: ```env /// file: .env.local API_KEY=19f401ba-e8b0-48c4-8c77-b0ebb26d97fe ``` After following the setup below, they can be imported via the following modules: - [`$app/env/private`]($app-env-private) - [`$app/env/public`]($app-env-public) > The `$env/*` modules, along with `$app/environment` were deprecated in SvelteKit 3 (and will be removed in SvelteKit 4) in favour of explicit environment variables that were added in SvelteKit 2.62 as an experimental option. ## Setup Add a `src/env.ts` (or `src/env.js`) file that exports a `variables` object: ```ts /// file: src/env.ts import { defineEnvVars } from '@sveltejs/kit/env'; export const variables = defineEnvVars({ // ... }); ``` Each value in the object passed to [`defineEnvVars`](@sveltejs-kit-env#defineEnvVars) is an [`EnvVarConfig`](@sveltejs-kit-env#EnvVarConfig) object that configures the environment variable. ## Private variables By default, all variables are considered private. For example, you don't want to reveal your `API_KEY`: ```ts /// file: src/env.ts import { defineEnvVars } from '@sveltejs/kit/env'; export const variables = defineEnvVars({ +++API_KEY: {}+++ }); ``` Now that `API_KEY` is defined, it can be imported into app code via `$app/env/private`: ```js import { API_KEY } from '$app/env/private'; ``` The `$app/env/private` module cannot be imported into code that runs in the browser, so that you can't accidentally reveal your secrets in a JavaScript bundle. ## Public variables Some variables are perfectly safe — necessary, even — to expose to the browser. For these, we can specify `public: true`: ```ts /// file: src/env.ts import { defineEnvVars } from '@sveltejs/kit/env'; export const variables = defineEnvVars({ GOOGLE_ANALYTICS_ID: { +++public: true+++ } }); ``` `GOOGLE_ANALYTICS_ID` can now be imported from `$app/env/public`, or used in your `app.html` template as `%sveltekit.env.GOOGLE_ANALYTICS_ID%`: ```html %sveltekit.head%
%sveltekit.body%
``` ## Validation You can specify a [Standard Schema](https://standardschema.dev/) validator such as [Zod](https://zod.dev/) or [Valibot](https://valibot.dev/) to check that an environment variable value is correct: ```ts /// file: src/env.ts import { defineEnvVars } from '@sveltejs/kit/env'; +++import * as v from 'valibot';+++ export const variables = defineEnvVars({ GOOGLE_ANALYTICS_ID: { public: true, +++schema: v.pipe(v.string(), v.regex(/G-[A-Z0-9]+/))+++ } }); ``` If you don't want to bring in a schema library, you can pass a function that returns the (possibly transformed) value, or throws an error explaining the problem: ```ts /// file: src/env.ts import { defineEnvVars } from '@sveltejs/kit/env'; export const variables = defineEnvVars({ GOOGLE_ANALYTICS_ID: { public: true, schema: (value) => { if (!value?.startsWith('G-')) throw new Error('expected a Google Analytics ID'); return value; } } }); ``` If a value is invalid, the app will fail to start (or build). To opt out of one or the other, use [`building`]($app-env#building) from `$app/env` along with a validator that accepts an optional value: ```ts /// file: src/env.ts import { defineEnvVars } from '@sveltejs/kit/env'; +++import { building } from '$app/env'+++ import * as v from 'valibot'; export const variables = defineEnvVars({ SECRET: { // optional when building but required when starting the app +++schema: building ? v.optional(v.string()) : v.string()+++ } }); ``` You can use validators to make values optional, or transform them (such as turning a string into a boolean, or parsing JSON) — see your validation library's documentation to learn how. ## Static variables By default, variables are dynamic. If a variable is configured with `static: true`, it will be inlined into your application code, enabling optimisations like dead-code elimination: ```ts /// file: src/env.ts import { defineEnvVars } from '@sveltejs/kit/env'; import * as v from 'valibot'; export const variables = defineEnvVars({ SHOW_DEBUG_OVERLAY: { public: true, +++static: true,+++ // coerce to true/false schema: v.pipe( v.optional(v.string(), ''), v.transform((str) => str !== '') ) } }); ``` Because this variable is `static`, the `` component shown here will be excluded from the JavaScript bundle unless `SHOW_DEBUG_OVERLAY` is truthy: ```svelte {#if SHOW_DEBUG_OVERLAY} {/if} ``` But if the variable is set before building the app... ```bash SHOW_DEBUG_OVERLAY=true npm run build ``` ...then the component will be included and shown. ## Documenting variables You can document the purpose of an environment variable by adding a `description`: ```ts /// file: src/env.ts import { defineEnvVars } from '@sveltejs/kit/env'; export const variables = defineEnvVars({ CACHE_TTL_SECONDS: { description: 'How long to cache responses, in seconds' } }); ``` Hovering over `CACHE_TTL_SECONDS` in your app code will show the description. # Building your app Building a SvelteKit app happens in two stages, which both happen when you run `vite build` (usually via `npm run build`). Firstly, Vite creates an optimized production build of your server code, your browser code, and your service worker (if you have one). [Prerendering](page-options#prerender) is executed at this stage, if appropriate. Secondly, an _adapter_ takes this production build and tunes it for your target environment — more on this on the following pages. ## During the build SvelteKit will load your `+page/layout(.server).js` files (and all files they import) for analysis during the build. Any code that should _not_ be executed at this stage must check that `building` from [`$app/env`]($app-env) is `false`: ```js +++import { building } from '$app/env';+++ import { initialiseDatabase } from '#lib/server/database.js'; +++if (!building) {+++ initialiseDatabase(); +++}+++ export function load() { // ... } ``` ## Preview your app After building, you can view your production build locally with `vite preview` (via `npm run preview`). Note that this will run the app in Node, and so is not a perfect reproduction of your deployed app — adapter-specific adjustments like the [`platform` object](adapters#Platform-specific-context) do not apply to previews. # Adapters Before you can deploy your SvelteKit app, you need to _adapt_ it for your deployment target. Adapters are small plugins that take the built app as input and generate output for deployment. Official adapters exist for a variety of platforms — these are documented on the following pages: - [`@sveltejs/adapter-cloudflare`](adapter-cloudflare) for Cloudflare Workers - [`@sveltejs/adapter-netlify`](adapter-netlify) for Netlify - [`@sveltejs/adapter-node`](adapter-node) for Node servers - [`@sveltejs/adapter-bun`](adapter-bun) for Bun servers - [`@sveltejs/adapter-static`](adapter-static) for static site generation (SSG) - [`@sveltejs/adapter-vercel`](adapter-vercel) for Vercel Additional [community-provided adapters](/packages#sveltekit-adapters) exist for other platforms. ## Using adapters Run [`npx sv add sveltekit-adapter`](/docs/cli/sveltekit-adapter) to install an adapter and add it to your config. Your adapter is specified in `vite.config.js`: ```js /// file: vite.config.js // @filename: ambient.d.ts declare module 'svelte-adapter-foo' { const adapter: (opts?: any) => import('@sveltejs/kit').Adapter; export default adapter; } // @errors: 2554 // @filename: index.js // ---cut--- import { sveltekit } from '@sveltejs/kit/vite'; import { defineConfig } from 'vite'; +++import adapter from 'svelte-adapter-foo';+++ export default defineConfig({ plugins: [ sveltekit({ +++adapter: adapter()+++ }) ] }); ``` ## Platform-specific context Some adapters may have access to additional information about the request. For example, Cloudflare Workers can access an `env` object containing KV namespaces etc. This can be passed to the `RequestEvent` used in [hooks](hooks) and [server routes](routing#server) as the `platform` property — consult each adapter's documentation to learn more. # Single-page apps You can turn a SvelteKit app into a fully client-rendered single-page app (SPA) by specifying a _fallback page_. This page will be served for any URLs that can't be served by other means such as returning a prerendered page. > > You can avoid these drawbacks by [prerendering](#Prerendering-individual-pages) as many pages as possible when using SPA mode (especially your homepage). If you can prerender all pages, you can simply use [static site generation](adapter-static) rather than a SPA. Otherwise, you should strongly consider using an adapter which supports server side rendering. SvelteKit has officially supported adapters for various providers with generous free tiers. ## Usage First, disable SSR for the pages you don't want to prerender. These pages will be served via the fallback page; for example, to serve all pages via the fallback by default, you can update the root layout as shown below. You should [opt back into prerendering individual pages and directories](#Prerendering-individual-pages) where possible. ```js /// file: src/routes/+layout.js export const ssr = false; ``` If you don't have any server-side logic (i.e. `+page.server.js`, `+layout.server.js` or `+server.js` files) you can use [`adapter-static`](adapter-static) to create your SPA. Install `adapter-static` with `npm i -D @sveltejs/adapter-static` and add it to your `vite.config.js` with the `fallback` option: ```js // @errors: 2307 /// file: vite.config.js import adapter from '@sveltejs/adapter-static'; import { sveltekit } from '@sveltejs/kit/vite'; import { defineConfig } from 'vite'; export default defineConfig({ plugins: [ sveltekit({ adapter: adapter({ fallback: '200.html' // may differ from host to host }) }) ] }); ``` The `fallback` page is an HTML page created by SvelteKit from your page template (e.g. `app.html`) that loads your app and navigates to the correct route. For example [Surge](https://surge.sh/help/adding-a-200-page-for-client-side-routing), a static web host, lets you add a `200.html` file that will handle any requests that don't correspond to static assets or prerendered pages. On some hosts it may be something else entirely — consult your platform's documentation. We recommend avoiding `index.html` if possible as it may conflict with prerendering. ## Prerendering individual pages If you want certain pages to be prerendered, you can re-enable `ssr` alongside `prerender` for just those parts of your app: ```js /// file: src/routes/my-prerendered-page/+page.js export const prerender = true; export const ssr = true; ``` You won't need a Node server or server capable of running JavaScript to deploy this page. It will only server render your page while building your project for the purposes of outputting an `.html` page that can be served from any static web host. ## Apache To run an SPA on [Apache](https://httpd.apache.org/), you should add a `static/.htaccess` file to route requests to the fallback page: ``` RewriteEngine On RewriteBase / RewriteRule ^200\.html$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /200.html [L] ``` # Advanced routing ## Rest parameters If the number of route segments is unknown, you can use rest syntax — for example you might implement GitHub's file viewer like so... ```sh /[org]/[repo]/tree/[branch]/[...file] ``` ...in which case a request for `/sveltejs/kit/tree/main/documentation/docs/04-advanced-routing.md` would result in the following parameters being available to the page: ```js // @noErrors { org: 'sveltejs', repo: 'kit', branch: 'main', file: 'documentation/docs/04-advanced-routing.md' } ``` ### 404 pages Rest parameters also allow you to render custom 404s. Given these routes... ```tree src/routes/ ├ marx-brothers/ │ ├ chico/ │ ├ harpo/ │ ├ groucho/ │ └ +error.svelte └ +error.svelte ``` ...the `marx-brothers/+error.svelte` file will _not_ be rendered if you visit `/marx-brothers/karl`, because no route was matched. If you want to render the nested error page, you should create a route that matches any `/marx-brothers/*` request, and return a 404 from it: ```tree src/routes/ ├ marx-brothers/ +++| ├ [...path]/+++ │ ├ chico/ │ ├ harpo/ │ ├ groucho/ │ └ +error.svelte └ +error.svelte ``` ```js /// file: src/routes/marx-brothers/[...path]/+page.js import { error } from '@sveltejs/kit'; /** @type {import('./$types').PageLoad} */ export function load(event) { error(404, 'Not Found'); } ``` ## Optional parameters A route like `[lang]/home` contains a parameter named `lang` which is required. Sometimes it's beneficial to make these parameters optional, so that in this example both `home` and `en/home` point to the same page. You can do that by wrapping the parameter in another bracket pair: `[[lang]]/home` Note that an optional route parameter cannot follow a rest parameter (`[...rest]/[[optional]]`), since parameters are matched 'greedily' and the optional parameter would always be unused. ## Matching A route like `src/routes/fruits/[page]` would match `/fruits/apple`, but it would also match `/fruits/rocketship`. We don't want that. You can ensure that route parameters are well-formed by adding a _matcher_ to your `src/params.js` file (or `src/params.ts`)... ```js /// file: src/params.js import { defineParams } from '@sveltejs/kit/params'; export const params = defineParams({ fruit: (param) => { if (param !== 'apple' && param !== 'orange') return; return param; } }); ``` ...and augmenting your routes: ``` src/routes/fruits/[page+++=fruit+++] ``` If the pathname doesn't match, SvelteKit will try to match other routes (using the sort order specified below), before eventually returning a 404. If it does match, the returned value is passed as the param value. You can also use a [Standard Schema](https://standardschema.dev) — for example with [Valibot](https://valibot.dev): ```js /// file: src/params.js import { defineParams } from '@sveltejs/kit/params'; import * as v from 'valibot'; export const params = defineParams({ number: v.pipe(v.string(), v.toNumber()) }); ``` If validation fails, the route does not match. If it succeeds, the param is typed with the output type of the schema, which must extend `string`, `boolean`, `number` (as in the example above) or `bigint`: ```js /// file: src/routes/items/[id=number]/+page.js /** @type {import('./$types').PageLoad} */ export function load({ params }) { console.log(typeof params.id); // 'number' } ``` Transformations should be _symmetrical_ — if converting to a number, then calling `toString()` on that number should return the original string. This allows the [`resolve`]($app-paths#resolve) function to construct a pathname correctly: ```js import { resolve } from '$app/paths'; resolve('/blog/[id=number]', { id: 1 }); ``` ## Sorting It's possible for multiple routes to match a given path. For example each of these routes would match `/foo-abc`: ```sh src/routes/[...catchall]/+page.svelte src/routes/[[a=x]]/+page.svelte src/routes/[b]/+page.svelte src/routes/foo-[c]/+page.svelte src/routes/foo-abc/+page.svelte ``` SvelteKit needs to know which route is being requested. To do so, it sorts them according to the following rules... - More specific routes are higher priority (e.g. a route with no parameters is more specific than a route with one dynamic parameter, and so on) - Parameters with [matchers](#Matching) (`[name=type]`) are higher priority than those without (`[name]`) - `[[optional]]` and `[...rest]` parameters are ignored unless they are the final part of the route, in which case they are treated with lowest priority. In other words `x/[[y]]/z` is treated equivalently to `x/z` for the purposes of sorting - Ties are resolved alphabetically ...resulting in this ordering, meaning that `/foo-abc` will invoke `src/routes/foo-abc/+page.svelte`, and `/foo-def` will invoke `src/routes/foo-[c]/+page.svelte` rather than less specific routes: ```sh src/routes/foo-abc/+page.svelte src/routes/foo-[c]/+page.svelte src/routes/[[a=x]]/+page.svelte src/routes/[b]/+page.svelte src/routes/[...catchall]/+page.svelte ``` ## Encoding Some characters can't be used on the filesystem — `/` on Linux and Mac, `\ / : * ? " < > |` on Windows. The `#` and `%` characters have special meaning in URLs, and the `[ ] ( )` characters have special meaning to SvelteKit, so these also can't be used directly as part of your route. To use these characters in your routes, you can use hexadecimal escape sequences, which have the format `[x+nn]` where `nn` is a hexadecimal character code: - `\` — `[x+5c]` - `/` — `[x+2f]` - `:` — `[x+3a]` - `*` — `[x+2a]` - `?` — `[x+3f]` - `"` — `[x+22]` - `<` — `[x+3c]` - `>` — `[x+3e]` - `|` — `[x+7c]` - `#` — `[x+23]` - `%` — `[x+25]` - `[` — `[x+5b]` - `]` — `[x+5d]` - `(` — `[x+28]` - `)` — `[x+29]` For example, to create a `/smileys/:-)` route, you would create a `src/routes/smileys/[x+3a]-[x+29]/+page.svelte` file. You can determine the hexadecimal code for a character with JavaScript: ```js ':'.charCodeAt(0).toString(16); // '3a', hence '[x+3a]' ``` You can also use Unicode escape sequences. Generally you won't need to as you can use the unencoded character directly, but if — for some reason — you can't have a filename with an emoji in it, for example, then you can use the escaped characters. In other words, these are equivalent: ``` src/routes/[u+d83e][u+dd2a]/+page.svelte src/routes/🤪/+page.svelte ``` The format for a Unicode escape sequence is `[u+nnnn]` where `nnnn` is a valid value between `0000` and `10ffff`. (Unlike JavaScript string escaping, there's no need to use surrogate pairs to represent code points above `ffff`.) To learn more about Unicode encodings, consult [Programming with Unicode](https://unicodebook.readthedocs.io/unicode_encodings.html). ## Advanced layouts By default, the _layout hierarchy_ mirrors the _route hierarchy_. In some cases, that might not be what you want. ### (group) Perhaps you have some routes that are 'app' routes that should have one layout (e.g. `/dashboard` or `/item`), and others that are 'marketing' routes that should have a different layout (`/about` or `/testimonials`). We can group these routes with a directory whose name is wrapped in parentheses — unlike normal directories, `(app)` and `(marketing)` do not affect the URL pathname of the routes inside them: ```tree src/routes/ +++│ (app)/+++ │ ├ dashboard/ │ ├ item/ │ └ +layout.svelte +++│ (marketing)/+++ │ ├ about/ │ ├ testimonials/ │ └ +layout.svelte ├ admin/ └ +layout.svelte ``` You can also put a `+page` directly inside a `(group)`, for example if `/` should be an `(app)` or a `(marketing)` page. ### Breaking out of layouts The root layout applies to every page of your app — if omitted, it defaults to `{@render children()}`. If you want some pages to have a different layout hierarchy than the rest, then you can put your entire app inside one or more groups _except_ the routes that should not inherit the common layouts. In the example above, the `/admin` route does not inherit either the `(app)` or `(marketing)` layouts. ### +page@ Pages can break out of the current layout hierarchy on a route-by-route basis. Suppose we have an `/item/[id]/embed` route inside the `(app)` group from the previous example: ```tree src/routes/ ├ (app)/ │ ├ item/ │ │ ├ [id]/ │ │ │ ├ embed/ +++│ │ │ │ └ +page.svelte+++ │ │ │ └ +layout.svelte │ │ └ +layout.svelte │ └ +layout.svelte └ +layout.svelte ``` Ordinarily, this would inherit the root layout, the `(app)` layout, the `item` layout and the `[id]` layout. We can reset to one of those layouts by appending `@` followed by the segment name — or, for the root layout, the empty string. In this example, we can choose from the following options: - `+page@[id].svelte` - inherits from `src/routes/(app)/item/[id]/+layout.svelte` - `+page@item.svelte` - inherits from `src/routes/(app)/item/+layout.svelte` - `+page@(app).svelte` - inherits from `src/routes/(app)/+layout.svelte` - `+page@.svelte` - inherits from `src/routes/+layout.svelte` ```tree src/routes/ ├ (app)/ │ ├ item/ │ │ ├ [id]/ │ │ │ ├ embed/ +++│ │ │ │ └ +page@(app).svelte+++ │ │ │ └ +layout.svelte │ │ └ +layout.svelte │ └ +layout.svelte └ +layout.svelte ``` ### +layout@ Like pages, layouts can _themselves_ break out of their parent layout hierarchy, using the same technique. For example, a `+layout@.svelte` component would reset the hierarchy for all its child routes. ``` src/routes/ ├ (app)/ │ ├ item/ │ │ ├ [id]/ │ │ │ ├ embed/ │ │ │ │ └ +page.svelte // uses (app)/item/[id]/+layout.svelte │ │ │ ├ +layout.svelte // inherits from (app)/item/+layout@.svelte │ │ │ └ +page.svelte // uses (app)/item/+layout@.svelte │ │ └ +layout@.svelte // inherits from root layout, skipping (app)/+layout.svelte │ └ +layout.svelte └ +layout.svelte ``` ### When to use layout groups Not all use cases are suited for layout grouping, nor should you feel compelled to use them. It might be that your use case would result in complex `(group)` nesting, or that you don't want to introduce a `(group)` for a single outlier. It's perfectly fine to use other means such as composition (reusable `load` functions or Svelte components) or if-statements to achieve what you want. The following example shows a layout that rewinds to the root layout and reuses components and functions that other layouts can also use: ```svelte {@render children()} ``` ```js /// file: src/routes/nested/route/+layout.js // @filename: ambient.d.ts declare module "#lib/reusable-load-function.js" { export function reusableLoad(event: import('@sveltejs/kit').LoadEvent): Promise>; } // @filename: index.js // ---cut--- import { reusableLoad } from '#lib/reusable-load-function.js'; /** @type {import('./$types').PageLoad} */ export function load(event) { // Add additional logic here, if needed return reusableLoad(event); } ``` ## Further reading - [Tutorial: Advanced Routing](/tutorial/kit/optional-params) # Hooks 'Hooks' are app-wide functions you declare that SvelteKit will call in response to specific events, giving you fine-grained control over the framework's behaviour. There are three hooks files, all optional: - `src/hooks.server.js` — your app's server hooks - `src/hooks.client.js` — your app's client hooks - `src/hooks.js` — your app's hooks that run on both the client and server Code in these modules will run when the application starts up, making them useful for initializing database clients and so on. ## handle This function runs every time the SvelteKit server receives a [request](web-standards#Fetch-APIs-Request) — whether that happens while the app is running, or during [prerendering](page-options#prerender) — and determines the [response](web-standards#Fetch-APIs-Response). It receives an `event` object representing the request and a function called `resolve`, which renders the route and generates a `Response`. This allows you to modify response headers or bodies, or implement a middleware (for rejecting rate-limited requests, for example). ```js /// file: src/hooks.server.js // @filename: ambient.d.ts declare module '#lib/server/rate-limit.js' { export function isRateLimited(key: string): Promise; } // @filename: index.js // ---cut--- import { building } from '$app/env'; import { isRateLimited } from '#lib/server/rate-limit.js'; /** @type {import('@sveltejs/kit/hooks').Handle} */ export async function handle({ event, resolve }) { if (!building && (await isRateLimited(event.getClientAddress()))) { return new Response('Too many requests', { status: 429 }); } const response = await resolve(event); return response; } ``` If the `handle` hook runs as part of a remote function request initiated by the client, `route`, `params` and `url` relate to the page the remote function was called from, _not_ the URL of the endpoint SvelteKit creates for the remote function. Never use them to determine whether or not a user is authorized to access certain data, as these values are part of the request which could be manipulated. Queries are also not re-run when the user navigates (unless the argument to the query changes as a result of navigation), and so you should be mindful of how you use these values. If unimplemented, defaults to `({ event, resolve }) => resolve(event)`. During prerendering, SvelteKit crawls your pages for links and renders each route it finds. Rendering the route invokes the `handle` function (and all other route dependencies, like `load`). If you need to exclude some code from running during this phase, check that the app is not [`building`]($app-env#building) beforehand. You can define multiple `handle` functions and execute them with the [`sequence`](@sveltejs-kit-hooks) helper function. `resolve` also supports a second, optional parameter that gives you more control over how the response will be rendered. That parameter is an object that can have the following fields: - `transformPageChunk(opts: { html: string, done: boolean }): MaybePromise` — 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. - `filterSerializedResponseHeaders(name: string, value: string): boolean` — determines which headers should be included in serialized responses when a `load` function loads a resource with `fetch`. By default, none will be included. - `preload(input: { type: 'js' | 'css' | 'asset', path: string } | { type: 'font', path: string, filename: string }): boolean` — determines which files should be preloaded. Files are preloaded via `` tags added to the `` tag; if [`output.linkHeaderPreload`](@sveltejs-kit-vite#output) is enabled, dynamically rendered pages use the [`Link` response header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Link) instead. The method is called with each file that was found at build time while constructing the code chunks — so if you for example have `import './styles.css` in your `+page.svelte`, `preload` will be called with the resolved path to that CSS file when visiting that page. Note that in dev mode `preload` is _not_ called, since it depends on analysis that happens at build time. Preloading can improve performance by downloading assets sooner, but it can also hurt if too much is downloaded unnecessarily. By default, `js` and `css` files will be preloaded. `asset` files are not preloaded at all currently, but we may add this later after evaluating feedback. For `font` files, `input` also has a `filename` property, the source file's pathname relative to the project root, so that a filter can match on it instead of the hashed path. ```js /// file: src/hooks.server.js /** @type {import('@sveltejs/kit/hooks').Handle} */ export async function handle({ event, resolve }) { const response = await resolve(event, { transformPageChunk: ({ html }) => html.replace('old', 'new'), filterSerializedResponseHeaders: (name) => name.startsWith('x-'), preload: ({ type, path }) => type === 'js' || path.includes('/important/') }); return response; } ``` Note that `resolve(...)` will never throw an error, it will always return a `Promise` with the appropriate status code. If an error is thrown elsewhere during `handle`, it is treated as fatal, and SvelteKit will respond with a JSON representation of the error or a fallback error page — which can be customised via `src/error.html` — depending on the `Accept` header. You can read more about error handling [here](errors). ### locals To add custom data to the request, which is passed to handlers in `+server.js` and server `load` functions, populate the `event.locals` object, as shown below. ```js /// file: src/hooks.server.js // @filename: ambient.d.ts type User = { name: string; } declare namespace App { interface Locals { user: User; } } const getUserInformation: (cookie: string | void) => Promise; // @filename: index.js // ---cut--- /** @type {import('@sveltejs/kit/hooks').Handle} */ export async function handle({ event, resolve }) { event.locals.user = await getUserInformation(event.cookies.get('sessionid')); const response = await resolve(event); // Note that modifying response headers isn't always safe. // Response objects can have immutable headers // (e.g. Response.redirect() returned from an endpoint). // Modifying immutable headers throws a TypeError. // In that case, clone the response or avoid creating a // response object with immutable headers. response.headers.set('x-custom-header', 'potato'); return response; } ``` ## handleFetch This function allows you to modify (or replace) the result of an [`event.fetch`](load#Making-fetch-requests) call that runs on the server (or during prerendering) inside an endpoint, `load`, `action`, `handle`, `handleError` or `reroute`. For example, your `load` function might make a request to a public URL like `https://api.yourapp.com` when the user performs a client-side navigation to the respective page, but during SSR it might make sense to hit the API directly (bypassing whatever proxies and load balancers sit between it and the public internet). ```js /// file: src/hooks.server.js /** @type {import('@sveltejs/kit/hooks').HandleFetch} */ export async function handleFetch({ request, fetch }) { if (request.url.startsWith('https://api.yourapp.com/')) { // clone the original request, but change the URL request = new Request( request.url.replace('https://api.yourapp.com/', 'http://localhost:9999/'), request ); } return fetch(request); } ``` Requests made with `event.fetch` follow the browser's credentials model — for same-origin requests, `cookie` and `authorization` headers are forwarded unless the `credentials` option is set to `"omit"`. For cross-origin requests, `cookie` will be included if the request URL belongs to a subdomain of the app — for example if your app is on `my-domain.com`, and your API is on `api.my-domain.com`, cookies will be included in the request. There is one caveat: if your app and your API are on sibling subdomains — `www.my-domain.com` and `api.my-domain.com` for example — then a cookie belonging to a common parent domain like `my-domain.com` will _not_ be included, because SvelteKit has no way to know which domain the cookie belongs to. In these cases you will need to manually include the cookie using `handleFetch`: ```js /// file: src/hooks.server.js // @errors: 2345 /** @type {import('@sveltejs/kit/hooks').HandleFetch} */ export async function handleFetch({ event, request, fetch }) { if (request.url.startsWith('https://api.my-domain.com/')) { request.headers.set('cookie', event.request.headers.get('cookie')); } return fetch(request); } ``` ## handleError This function is called for every error thrown while loading, rendering, or responding to a request. This allows for two things: - you can log the error - you can generate a custom representation of the error that is safe to show to users, omitting sensitive details like messages and stack traces Alongside the `event`, the hook receives a `kind` discriminant that tells you where the error came from, and the `error` itself: - `'app'` — the error came from your app via [`error(...)`](@sveltejs-kit#error) - `error` is the error body, which matches [`App.Error`](types#Error) - defaults to the error body itself - `'framework'` — the error came from SvelteKit, such as a 404, 405 or 413 - `error` is `{ status, message }`, where `message` is safe text like `Not Found` - defaults to that same `{ status, message }` - `'validation'` (server only) — the error came from validating a remote function argument against its [Standard Schema](https://standardschema.dev/) - `error` is `{ status: 400, message: 'Bad Request' }`, and `issues` contains the validation issues - defaults to the `error` object; the issues are not exposed unless you explicitly return them - to access validation-library-specific issue properties, parameterise `HandleServerError` with the issue type, for example `HandleServerError` - `'unknown'` — we don't know what went wrong; the error was thrown by your code, or code it calls - `error` is the thrown value, which may contain information unsafe to expose - defaults to `{ status: 500, message: 'Internal Error' }` The next section, [Errors](errors), explains the other categories in more detail. Redirects are not errors, and never reach the hook. The hook returns an object matching [`App.Error`](types#Error), in which `status` and `message` are optional — return them only to override the defaults in the list above. To add more information to the `page.error` object in a type-safe way, augment the existing `App.Error` interface with your additional properties. The built-in `status` and `message` properties are already present and do not need to be redeclared. For example, you can add a tracking ID for users to quote when contacting support: ```ts /// file: src/app.d.ts declare global { namespace App { interface Error { errorId: string; } } } export {}; ``` ```js /// file: src/hooks.server.js // @errors: 2322 2353 // @filename: ambient.d.ts declare module '@sentry/sveltekit' { export const init: (opts: any) => void; export const captureException: (error: any, opts: any) => void; } // @filename: index.js // ---cut--- import * as Sentry from '@sentry/sveltekit'; Sentry.init({/*...*/}) /** @type {import('@sveltejs/kit/hooks').HandleServerError} */ export async function handleError({ kind, error, event }) { if (kind === 'app') { // you created this error with `error(...)`, so it already // matches `App.Error` — pass it through unchanged return error; } const errorId = crypto.randomUUID(); if (kind === 'framework') { // a 404 (or similar) — `error.status` and `error.message` are safe to // expose, so we keep them and just add our own property return { ...error, errorId }; } // example integration with https://sentry.io/ Sentry.captureException(error, { extra: { event, errorId } }); // `status` and `message` are optional — we only override `message`, // so the status stays at its default of 500 return { message: 'Whoops!', errorId }; } ``` ```js /// file: src/hooks.client.js // @errors: 2322 2353 // @filename: ambient.d.ts declare module '@sentry/sveltekit' { export const init: (opts: any) => void; export const captureException: (error: any, opts: any) => void; } // @filename: index.js // ---cut--- import * as Sentry from '@sentry/sveltekit'; Sentry.init({/*...*/}) /** @type {import('@sveltejs/kit/hooks').HandleClientError} */ export async function handleError({ kind, error, event }) { if (kind === 'app') { return error; } const errorId = crypto.randomUUID(); if (kind === 'framework') { return { ...error, errorId }; } // example integration with https://sentry.io/ Sentry.captureException(error, { extra: { event, errorId } }); return { message: 'Whoops!', errorId }; } ``` Errors that were already transformed by the server-side hook are not passed to the client-side hook a second time. During development, if an error occurs because of a syntax error in your Svelte code, the passed in error has a `frame` property appended highlighting the location of the error. ## init This function runs once, when the server is created or the app starts in the browser, and is a useful place to do asynchronous work such as initializing a database connection. ```js // @errors: 2307 /// file: src/hooks.server.js import * as db from '#lib/server/database.js'; /** @type {import('@sveltejs/kit/hooks').ServerInit} */ export async function init() { await db.connect(); } ``` > In the browser, asynchronous work in `init` will delay hydration, so be mindful of what you put in there. ## reroute This function runs before `handle` and allows you to change how URLs are translated into routes. The returned pathname (which defaults to `url.pathname`) is used to select the route and its parameters. For example, you might have a `src/routes/[[lang]]/about/+page.svelte` page, which should be accessible as `/en/about` or `/de/ueber-uns` or `/fr/a-propos`. You could implement this with `reroute`: ```js // @errors: 2345 2304 /// file: src/hooks.js /** @type {Record} */ const translated = { '/en/about': '/en/about', '/de/ueber-uns': '/de/about', '/fr/a-propos': '/fr/about', }; /** @type {import('@sveltejs/kit/hooks').Reroute} */ export function reroute({ url }) { if (url.pathname in translated) { return translated[url.pathname]; } } ``` The `lang` parameter will be correctly derived from the returned pathname. Using `reroute` will _not_ change the contents of the browser's address bar, or the value of `event.url`. Since version 2.18, the `reroute` hook can be asynchronous, allowing it to (for example) fetch data from your backend to decide where to reroute to. Use this carefully and make sure it's fast, as it will delay navigation otherwise. If you need to fetch data, use the `fetch` provided as an argument. It has the [same benefits](load#Making-fetch-requests) as the `fetch` provided to `load` functions, with the caveat that `params` and `id` are unavailable to [`handleFetch`](#handleFetch) because the route is not yet known. ```js // @errors: 2345 2304 /// file: src/hooks.js /** @type {import('@sveltejs/kit/hooks').Reroute} */ export async function reroute({ url, fetch }) { // Ask a special endpoint within your app about the destination if (url.pathname === '/api/reroute') return; const api = new URL('/api/reroute', url); api.searchParams.set('pathname', url.pathname); const result = await fetch(api).then(r => r.json()); return result.pathname; } ``` ## transport This is a collection of _transporters_, which allow you to pass custom types — returned from `load` and form actions — across the server/client boundary. Each transporter contains an `encode` function, which encodes values on the server (or returns a falsy value for anything that isn't an instance of the type) and a corresponding `decode` function: ```js // @errors: 2307 /// file: src/hooks.js import { Vector } from '#lib/math.js'; /** @type {import('@sveltejs/kit/hooks').Transport} */ export const transport = { Vector: { encode: (value) => value instanceof Vector && [value.x, value.y], decode: ([x, y]) => new Vector(x, y) } }; ``` ## Further reading - [Tutorial: Hooks](/tutorial/kit/handle) # Errors Errors are an inevitable fact of software development. SvelteKit handles errors differently depending on where they occur, what kind of errors they are, and the nature of the incoming request. ## Error objects Every error passes through the [`handleError`](hooks#handleError) hook — which can log it and customise it — before it is rendered. The hook's `kind` property identifies where the error came from: your app (`'app'`), SvelteKit (`'framework'`), validation of a [remote function](remote-functions) argument (`'validation'`) or an unknown source (`'unknown'`). By default, all are represented as simple `{ status: number, message: string }` objects. You can add additional properties, like a `code` or a tracking `id`, as shown in the examples below. (When using TypeScript this requires you to redefine the `Error` type as described in [Type safety](errors#Type-safety) below). ## App errors An app error is one thrown from your app code using the [`error`](@sveltejs-kit#error) function imported from `@sveltejs/kit`: ```js /// file: src/routes/blog/[slug]/+page.server.js // @filename: ambient.d.ts declare module '#lib/server/database.js' { export function getPost(slug: string): Promise<{ title: string, content: string } | undefined> } // @filename: index.js // ---cut--- import { error } from '@sveltejs/kit'; import * as db from '#lib/server/database.js'; /** @type {import('./$types').PageServerLoad} */ export async function load({ params }) { const post = await db.getPost(params.slug); if (!post) { error(404, 'Not found'); } return { post }; } ``` This throws an exception that SvelteKit catches, causing it to set the response status code to 404 and render an [`+error.svelte`](routing#error) component, where the `error` is an `App.Error` object with the provided `status` and `message`. On its way there, the error passes through the [`handleError`](hooks#handleError) hook with `kind: 'app'`. Since the shape of the error is determined by your app, it is considered safe to expose, and the hook can pass it through unchanged. ```svelte

{error.message}

``` You can add extra properties to the error object if needed: ```js // @filename: ambient.d.ts declare global { namespace App { interface Error { message: string; code: string; } } } export {} // @filename: index.js import { error } from '@sveltejs/kit'; // ---cut--- error(404, 'Not found', { +++code: 'NOT_FOUND'+++ }); ``` ## Framework errors Some errors are generated by SvelteKit itself rather than by your code — a request that doesn't match any route (404), a `POST` request to a page without actions (405), a request body that exceeds the size limit (413), and so on. These also go through `handleError`, with `kind: 'framework'`. The `error` you receive is a `{ status, message }` object whose `message` is a terse but safe description of what went wrong, such as `'Not Found'`, so it can be exposed to users as-is. If you log errors inside `handleError`, remember that framework errors such as 404s are routine — you will generally want to avoid logging them. ## Validation errors Validation errors occur when a [remote function](remote-functions) is called with invalid data. When these are passed to `handleError`, they are accompanied by an array of `issues`. See [Handling validation errors](remote-functions#Handling-validation-errors) for more details. ## Unknown errors An _unknown_ error is any other exception that occurs while handling a request. Since these can contain sensitive information, unknown error messages and stack traces are not exposed to users. By default, unknown errors are printed to the console (or, in production, your server logs), while the error that is exposed to the user has a generic shape: ```json { "status": 500, "message": "Internal Error" } ``` Unknown errors go through the [`handleError`](hooks#handleError) hook with `kind: 'unknown'`, because SvelteKit does not know what went wrong. There you can add your own error handling, for example sending errors to a reporting service, or returning a custom error object which becomes the `error` prop passed to `+error.svelte`. The value you receive is the raw thrown value, and nothing about it is exposed unless you choose to expose it. Anything you return overrides the defaults, so you can — for example — use the type of the thrown error to determine the HTTP status code used in the response: ```js /// file: src/hooks.server.js // Assuming you have this ... class NotFound extends Error {} /** @type {import('@sveltejs/kit/hooks').HandleServerError} */ export function handleError({ kind, error, event }) { if (kind === 'unknown') { // ... you can do this if (error instanceof NotFound) { return { status: 404, message: 'Not found' }; } return { message: 'Something went wrong' }; } // app and framework errors are already safe to expose return error; } ``` ## Error boundaries Errors that occur during `load` or rendering (for example inside a component's ` ``` ...SvelteKit will error: ``` Cannot import #lib/server/secrets.ts into code that runs in the browser, as this could leak sensitive information. src/routes/+page.svelte imports src/routes/utils.js imports #lib/server/secrets.ts If you're only using the import as a type, change it to `import type`. ``` Even though the public-facing code — `src/routes/+page.svelte` — only uses the `add` export and not the secret `atlantisCoordinates` export, the secret code could end up in JavaScript that the browser downloads, and so the import chain is considered unsafe. This feature also works with dynamic imports, even interpolated ones like ``await import(`./${foo}.js`)``. ## Further reading - [Tutorial: Environment variables](/tutorial/kit/env-static-private) # Snapshots Ephemeral DOM state — like scroll positions on sidebars, the content of `` elements and so on — is discarded when you navigate from one page to another. For example, if the user fills out a form but navigates away and then back before submitting, or if the user refreshes the page, the values they filled in will be lost. In cases where it's valuable to preserve that input, you can take a _snapshot_ of DOM state, which can then be restored if the user navigates back. To do this, call `snapshot` from `$app/navigation` during component initialization: ```svelte