This is the developer documentation for Svelte. # 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. > [!NOTE] If you are using TypeScript and import such exports from a `module` block into a `.ts` file, make sure to have your editor setup so that TypeScript knows about them. This is the case for our VS Code extension and the IntelliJ plugin, but in other cases you might need to setup our [TypeScript editor plugin](https://www.npmjs.com/package/typescript-svelte-plugin). > [!LEGACY] > 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] When you update properties of proxies, the original object is _not_ mutated. If you need to use your own proxy handlers in a state proxy, you should wrap the object _after_ wrapping it in `$state`. 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; } } ``` > [!NOTE] The compiler transforms `done` and `text` into `get`/`set` methods on the class prototype referencing private fields. This means the properties are not enumerable. 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); } ``` > [!NOTE] You can see the code Svelte generates by clicking the 'JS Output' tab in the [playground](/playground). 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`. > [!NOTE] Code in Svelte components is only executed once at creation. Without the `$derived` rune, `doubled` would maintain its original value even when `count` changes. ## `$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 ``` > [!NOTE] Prior to Svelte 5.25, deriveds were read-only. ## 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... ```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: ```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. > [!NOTE] If you're having difficulty understanding why your `$effect` is rerunning or is not running see [understanding dependencies](#Understanding-dependencies). Effects are triggered differently than the `$:` blocks you may be used to if coming from Svelte 4. ### 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. > [!NOTE] Svelte uses effects internally to represent logic and expressions in your template — this is how `

hello {name}!

` updates when `name` changes. 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: ```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. 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 ``` > [!NOTE] For things that are more complicated than a simple expression like `count * 2`, you can also use `$derived.by`. 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(); ``` > [!NOTE] Fallback values are not turned into reactive state proxies (see [Updating props](#Updating-props) for more info) ## 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 ``` > [!NOTE] Interfaces for native DOM elements are provided in the `svelte/elements` module (see [Typing wrapper components](typescript#Typing-wrapper-components)) 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. > [!NOTE] Mutation is also possible with normal props, but is strongly discouraged — Svelte will warn you if it detects that a component is mutating state it does not 'own'. 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: ```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 > [!NOTE] `$inspect` only works during development. In a production build it becomes a noop. 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. ## In templates You can also use `$inspect(...)` in a standalone template expression. This is useful for inspecting values that are only available inside a block: ```svelte {#each users as user} {$inspect(user)}

Hello {user.firstname}!

{/each} ``` # $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: ```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
``` > [!NOTE] Quoting a singular expression does not affect how the value is parsed, but in Svelte 6 it will cause the value to be coerced to a string: > > > ```svelte > > ``` When the attribute name and value match (`name={name}`), they can be replaced with `{name}`. ```svelte ``` Form elements (``, ` ``` ### a11y_no_noninteractive_element_interactions ``` Non-interactive element `<%element%>` should not be assigned mouse or keyboard event listeners ``` A non-interactive element does not support event handlers (mouse and key handlers). Non-interactive elements include `
`, ``, `

` (,`

`, etc), `

`, ``, `

  • `, `
      ` and `
        `. Non-interactive [WAI-ARIA roles](https://www.w3.org/TR/wai-aria-1.1/#usage_intro) include `article`, `banner`, `complementary`, `img`, `listitem`, `main`, `region` and `tooltip`. ```sv
      1. {}}>
      2. {}}>
        ``` ### a11y_no_noninteractive_element_to_interactive_role ``` Non-interactive element `<%element%>` cannot have interactive role '%role%' ``` [WAI-ARIA](https://www.w3.org/TR/wai-aria-1.1/#usage_intro) roles should not be used to convert a non-interactive element to an interactive element. Interactive ARIA roles include `button`, `link`, `checkbox`, `menuitem`, `menuitemcheckbox`, `menuitemradio`, `option`, `radio`, `searchbox`, `switch` and `textbox`. ```svelte

        Button

        ``` ### a11y_no_noninteractive_tabindex ``` noninteractive element cannot have nonnegative tabIndex value ``` Tab key navigation should be limited to elements on the page that can be interacted with. ```svelte
        ``` ### a11y_no_redundant_roles ``` Redundant role '%role%' ``` Some HTML elements have default ARIA roles. Giving these elements an ARIA role that is already set by the browser [has no effect](https://www.w3.org/TR/using-aria/#aria-does-nothing) and is redundant. ```svelte ``` ### a11y_no_static_element_interactions ``` `<%element%>` with a %handler% handler must have an ARIA role ``` Elements like `
        ` with interactive handlers like `click` must have an ARIA role. ```svelte
        ''}>
        ``` ### a11y_positive_tabindex ``` Avoid tabindex values above zero ``` Avoid positive `tabindex` property values. This will move elements out of the expected tab order, creating a confusing experience for keyboard users. ```svelte
        ``` ### a11y_role_has_required_aria_props ``` Elements with the ARIA role "%role%" must have the following attributes defined: %props% ``` Elements with ARIA roles must have all required attributes for that role. ```svelte ``` ### a11y_role_supports_aria_props ``` The attribute '%attribute%' is not supported by the role '%role%' ``` Elements with explicit or implicit roles defined contain only `aria-*` properties supported by that role. ```svelte
      3. ``` ### a11y_role_supports_aria_props_implicit ``` The attribute '%attribute%' is not supported by the role '%role%'. This role is implicit on the element `<%name%>` ``` Elements with explicit or implicit roles defined contain only `aria-*` properties supported by that role. ```svelte
      4. ``` ### a11y_unknown_aria_attribute ``` Unknown aria attribute 'aria-%attribute%' ``` ``` Unknown aria attribute 'aria-%attribute%'. Did you mean '%suggestion%'? ``` Enforce that only known ARIA attributes are used. This is based on the [WAI-ARIA States and Properties spec](https://www.w3.org/WAI/PF/aria-1.1/states_and_properties). ```svelte ``` ### a11y_unknown_role ``` Unknown role '%role%' ``` ``` Unknown role '%role%'. Did you mean '%suggestion%'? ``` Elements with ARIA roles must use a valid, non-abstract ARIA role. A reference to role definitions can be found at [WAI-ARIA](https://www.w3.org/TR/wai-aria/#role_definitions) site. ```svelte
        ``` ### attribute_avoid_is ``` The "is" attribute is not supported cross-browser and should be avoided ``` ### attribute_global_event_reference ``` You are referencing `globalThis.%name%`. Did you forget to declare a variable with that name? ``` ### attribute_illegal_colon ``` Attributes should not contain ':' characters to prevent ambiguity with Svelte directives ``` ### attribute_invalid_property_name ``` '%wrong%' is not a valid HTML attribute. Did you mean '%right%'? ``` ### attribute_quoted ``` Quoted attributes on components and custom elements will be stringified in a future version of Svelte. If this isn't what you want, remove the quotes ``` ### bidirectional_control_characters ``` A bidirectional control character was detected in your code. These characters can be used to alter the visual direction of your code and could have unintended consequences ``` Bidirectional control characters can alter the direction in which text appears to be in. For example, via control characters, you can make `defabc` look like `abcdef`. As a result, if you were to unknowingly copy and paste some code that has these control characters, they may alter the behavior of your code in ways you did not intend. See [trojansource.codes](https://trojansource.codes/) for more information. ### bind_invalid_each_rest ``` The rest operator (...) will create a new object and binding '%name%' with the original object will not work ``` ### block_empty ``` Empty block ``` ### component_name_lowercase ``` `<%name%>` will be treated as an HTML element unless it begins with a capital letter ``` ### css_unused_selector ``` Unused CSS selector "%name%" ``` Svelte traverses both the template and the ` ``` ### custom_element_props_identifier ``` Using a rest element or a non-destructured declaration with `$props()` means that Svelte can't infer what properties to expose when creating a custom element. Consider destructuring all the props or explicitly specifying the `customElement.props` option. ``` ### element_implicitly_closed ``` This element is implicitly closed by the following `%tag%`, which can cause an unexpected DOM structure. Add an explicit `%closing%` to avoid surprises. ``` In HTML, some elements are implicitly closed by another element. For example, you cannot nest a `

        ` inside another `

        `: ```html

        hello

        hello

        ``` Similarly, a parent element's closing tag will implicitly close all child elements, even if the `` rather than `<%name% ... />` ``` In HTML, there's [no such thing as a self-closing tag](https://jakearchibald.com/2023/against-self-closing-tags-in-html/). While this _looks_ like a self-contained element with some text next to it... ```html
        some text!
        ``` ...a spec-compliant HTML parser (such as a browser) will in fact parse it like this, with the text _inside_ the icon: ```html
        some text!
        ``` Some templating languages (including Svelte) will 'fix' HTML by turning `` into ``. Others adhere to the spec. Both result in ambiguity and confusion when copy-pasting code between different contexts, so Svelte prompts you to resolve the ambiguity directly by having an explicit closing tag. To automate this, run the dedicated migration: ```sh npx sv migrate self-closing-tags ``` In a future version of Svelte, self-closing tags may be upgraded from a warning to an error. ### event_directive_deprecated ``` Using `on:%name%` to listen to the %name% event is deprecated. Use the event attribute `on%name%` instead ``` See [the migration guide](v5-migration-guide#Event-changes) for more info. ### export_let_unused ``` Component has unused export property '%name%'. If it is for external reference only, please consider using `export const %name%` ``` ### legacy_code ``` `%code%` is no longer valid — please use `%suggestion%` instead ``` ### legacy_component_creation ``` Svelte 5 components are no longer classes. Instantiate them using `mount` or `hydrate` (imported from 'svelte') instead. ``` See the [migration guide](v5-migration-guide#Components-are-no-longer-classes) for more info. ### node_invalid_placement_ssr ``` %message%. When rendering this component on the server, the resulting HTML will be modified by the browser (by moving, removing, or inserting elements), likely resulting in a `hydration_mismatch` warning ``` HTML restricts where certain elements can appear. In case of a violation the browser will 'repair' the HTML in a way that breaks Svelte's assumptions about the structure of your components. Some examples: - `

        hello

        world

        ` will result in `

        hello

        world

        ` (the `
        ` autoclosed the `

        ` because `

        ` cannot contain block-level elements) - `

        option a
        ` will result in `` (the `
        ` is removed) - `
        cell
        ` will result in `
        cell
        ` (a `` is auto-inserted) This code will work when the component is rendered on the client (which is why this is a warning rather than an error), but if you use server rendering it will cause hydration to fail. ### non_reactive_update ``` `%name%` is updated, but is not declared with `$state(...)`. Changing its value will not correctly trigger updates ``` This warning is thrown when the compiler detects the following: - a variable was declared without `$state` or `$state.raw` - the variable is reassigned - the variable is read in a reactive context In this case, changing the value will not correctly trigger updates. Example: ```svelte

        This value updates: {reactive}

        This value does not update: {stale}

        ``` To fix this, wrap your variable declaration with `$state`. ### options_deprecated_accessors ``` The `accessors` option has been deprecated. It will have no effect in runes mode ``` ### options_deprecated_immutable ``` The `immutable` option has been deprecated. It will have no effect in runes mode ``` ### options_missing_custom_element ``` The `customElement` option is used when generating a custom element. Did you forget the `customElement: true` compile option? ``` ### options_removed_enable_sourcemap ``` The `enableSourcemap` option has been removed. Source maps are always generated now, and tooling can choose to ignore them ``` ### options_removed_hydratable ``` The `hydratable` option has been removed. Svelte components are always hydratable now ``` ### options_removed_loop_guard_timeout ``` The `loopGuardTimeout` option has been removed ``` ### options_renamed_ssr_dom ``` `generate: "dom"` and `generate: "ssr"` options have been renamed to "client" and "server" respectively ``` ### perf_avoid_inline_class ``` Avoid 'new class' — instead, declare the class at the top level scope ``` ### perf_avoid_nested_class ``` Avoid declaring classes below the top level scope ``` ### reactive_declaration_invalid_placement ``` Reactive declarations only exist at the top level of the instance script ``` ### reactive_declaration_module_script_dependency ``` Reassignments of module-level declarations will not cause reactive statements to update ``` ### script_context_deprecated ``` `context="module"` is deprecated, use the `module` attribute instead ``` ```svelte ``` ### script_unknown_attribute ``` Unrecognised attribute — should be one of `generics`, `lang` or `module`. If this exists for a preprocessor, ensure that the preprocessor removes it ``` ### slot_element_deprecated ``` Using `` to render parent content is deprecated. Use `{@render ...}` tags instead ``` See [the migration guide](v5-migration-guide#Snippets-instead-of-slots) for more info. ### state_referenced_locally ``` This reference only captures the initial value of `%name%`. Did you mean to reference it inside a %type% instead? ``` This warning is thrown when the compiler detects the following: - A reactive variable is declared - ...and later reassigned... - ...and referenced in the same scope This 'breaks the link' to the original state declaration. For example, the `double` declaration here only runs with the initial value of `count`: ```svelte ``` To keep it in sync, it should be `$derived(count * 2)`. If you pass state to a function, the function loses access to the state once it is reassigned: ```svelte ``` ```svelte

        The count is {count}

        ``` To fix this, reference the variable such that it is lazily evaluated. For the above example, this can be achieved by wrapping `count` in a function: ```svelte ``` ```svelte

        The count is {+++count()+++}

        ``` For more info, see [Passing state into functions]($state#Passing-state-into-functions). ### store_rune_conflict ``` It looks like you're using the `$%name%` rune, but there is a local binding called `%name%`. Referencing a local variable with a `$` prefix will create a store subscription. Please rename `%name%` to avoid the ambiguity ``` ### svelte_component_deprecated ``` `` is deprecated in runes mode — components are dynamic by default ``` In previous versions of Svelte, the component constructor was fixed when the component was rendered. In other words, if you wanted `` to re-render when `X` changed, you would either have to use `` or put the component inside a `{#key X}...{/key}` block. In Svelte 5 this is no longer true — if `X` changes, `` re-renders. In some cases `` syntax can be used as a replacement; a lowercased variable with property access is recognized as a component in Svelte 5. For complex component resolution logic, an intermediary, capitalized variable may be necessary. E.g. in places where `@const` can be used: ```svelte {#each items as item} ------ +++{@const Component = item.condition ? Y : Z}+++ ++++++ {/each} ``` A derived value may be used in other contexts: ```svelte ------ ++++++ ``` ### svelte_element_invalid_this ``` `this` should be an `{expression}`. Using a string attribute value will cause an error in future versions of Svelte ``` ### svelte_self_deprecated ``` `` is deprecated — use self-imports (e.g. `import %name% from './%basename%'`) instead ``` See [the note in the docs](legacy-svelte-self) for more info. ### unknown_code ``` `%code%` is not a recognised code ``` ``` `%code%` is not a recognised code (did you mean `%suggestion%`?) ``` # Runtime errors ## Client errors ### async_derived_orphan ``` Can only create a `$derived(...)` with an `await` expression during component initialization or in a declaration tag ``` In Svelte there are two types of reaction — [`$derived`](/docs/svelte/$derived) and [`$effect`](/docs/svelte/$effect). Deriveds can normally be created anywhere, because they run _lazily_ and can be [garbage collected](https://developer.mozilla.org/en-US/docs/Glossary/Garbage_collection) if nothing references them. Effects, by contrast, keep running eagerly whenever their dependencies change, until they are destroyed. Because of this, effects can only be created inside other effects (or [effect roots](/docs/svelte/$effect#$effect.root), such as the one that is created when you first mount a component) so that Svelte knows when to destroy them. Some sleight of hand occurs when a derived contains an `await` expression: Since waiting until we read `$derived(await getPromise())` to call `getPromise` would be too late, we use an effect to instead call it proactively, notifying Svelte when the value is available. But since we're using an effect, this can only happen during component initialization or in a [declaration tag](/docs/svelte/declaration-tags). ### bind_invalid_checkbox_value ``` Using `bind:value` together with a checkbox input is not allowed. Use `bind:checked` instead ``` ### bind_invalid_export ``` Component %component% has an export named `%key%` that a consumer component is trying to access using `bind:%key%`, which is disallowed. Instead, use `bind:this` (e.g. `<%name% bind:this={component} />`) and then access the property on the bound component instance (e.g. `component.%key%`) ``` ### bind_not_bindable ``` A component is attempting to bind to a non-bindable property `%key%` belonging to %component% (i.e. `<%name% bind:%key%={...}>`). To mark a property as bindable: `let { %key% = $bindable() } = $props()` ``` ### component_api_changed ``` Calling `%method%` on a component instance (of %component%) is no longer valid in Svelte 5 ``` See the [migration guide](/docs/svelte/v5-migration-guide#Components-are-no-longer-classes) for more information. ### component_api_invalid_new ``` Attempted to instantiate %component% with `new %name%`, which is no longer valid in Svelte 5. If this component is not under your control, set the `compatibility.componentApi` compiler option to `4` to keep it working. ``` See the [migration guide](/docs/svelte/v5-migration-guide#Components-are-no-longer-classes) for more information. ### custom_renderer_unsupported_operation ``` `%operation%` is not supported when rendering with a custom renderer ``` Some of Svelte's internals only work with the DOM, and are never expected to run while a custom renderer is active — for example, `{@html ...}` and hydration are not available with custom renderers. Reaching one of these code paths indicates a bug in Svelte rather than in your app or renderer, so please [open an issue](https://github.com/sveltejs/svelte/issues) with a reproduction. ### derived_references_self ``` A derived value cannot reference itself recursively ``` ### each_key_duplicate ``` Keyed each block has duplicate key at indexes %a% and %b% ``` ``` Keyed each block has duplicate key `%value%` at indexes %a% and %b% ``` ### each_key_volatile ``` Keyed each block has key that is not idempotent — the key for item at index %index% was `%a%` but is now `%b%`. Keys must be the same each time for a given item ``` The key expression in a keyed each block must return the same value when called multiple times for the same item. Using expressions like `[item.a, item.b]` creates a new array each time, which will never be equal to itself. Instead, use a primitive value or create a stable key like `item.a + '-' + item.b`. ### effect_in_teardown ``` `%rune%` cannot be used inside an effect cleanup function ``` ### effect_in_unowned_derived ``` Effect cannot be created inside a `$derived` value that was not itself created inside an effect ``` ### effect_orphan ``` `%rune%` can only be used inside an effect (e.g. during component initialisation) ``` Effects can only be created while a parent effect is running. This means that they cannot, for example, be created inside an event handler or after an `await` expression (unless the `await` occurs directly inside a component's ` ``` ### hydration_failed ``` Failed to hydrate the application ``` ### invalid_bundler_config ``` Svelte's DOM operations have not been initialized. This can happen if a bundler incorrectly removes side-effect-only imports. Check the `sideEffects` setting in your package.json ``` Svelte relies on side-effect-only imports to initialize its DOM operations and enable runtime features. If a library bundles Svelte into its distribution and marks those files as side-effect-free (for example, with `"sideEffects": false` or `"sideEffects": ["**/*.css"]`), the consuming app's bundler may remove these imports. If you maintain the library, prefer leaving `svelte` external rather than bundling it. If you are using a library that bundles Svelte, ask its maintainers to correct its packaging configuration. ### invalid_snippet_in_custom_renderer ``` `createRawSnippet` cannot be used with a custom renderer ``` ### lifecycle_legacy_only ``` `%name%(...)` cannot be used in runes mode ``` ### props_invalid_value ``` Cannot do `bind:%key%={undefined}` when `%key%` has a fallback value ``` ### props_rest_readonly ``` Rest element properties of `$props()` such as `%property%` are readonly ``` ### renderer_cannot_cross ``` Cannot render content belonging to %guest% inside %host%. A custom renderer must define `embed` or `host` to be combined with another renderer ``` ### rune_outside_svelte ``` The `%rune%` rune is only available inside `.svelte` and `.svelte.js/ts` files ``` ### snippet_renderer_mismatch ``` A snippet created in a component that was compiled without `experimental.customRenderer` cannot be rendered by a custom renderer ``` ### state_descriptors_fixed ``` Property descriptors defined on `$state` objects must contain `value` and always be `enumerable`, `configurable` and `writable`. ``` ### state_prototype_fixed ``` Cannot set prototype of `$state` object ``` ### state_unsafe_mutation ``` Updating state inside `$derived(...)`, `$inspect(...)` or a template expression is forbidden. If the value should not be reactive, declare it without `$state` ``` This error occurs when state is updated while evaluating a `$derived`. You might encounter it while trying to 'derive' two pieces of state in one go: ```svelte

        {count} is even: {even}

        {count} is odd: {odd}

        ``` This is forbidden because it introduces instability: if `

        {count} is even: {even}

        ` is updated before `odd` is recalculated, `even` will be stale. In most cases the solution is to make everything derived: ```js let count = 0; // ---cut--- let even = $derived(count % 2 === 0); let odd = $derived(!even); ``` If side-effects are unavoidable, use [`$effect`]($effect) instead. ### svelte_boundary_reset_onerror ``` A `` `reset` function cannot be called while an error is still being handled ``` If a [``](https://svelte.dev/docs/svelte/svelte-boundary) has an `onerror` function, it must not call the provided `reset` function synchronously since the boundary is still in a broken state. Typically, `reset()` is called later, once the error has been resolved. If it's possible to resolve the error inside the `onerror` callback, you must at least wait for the boundary to settle before calling `reset()`, for example using [`tick`](https://svelte.dev/docs/svelte/lifecycle-hooks#tick): ```svelte { fixTheError(); +++await tick();+++ reset(); }}> ``` ## Server errors ### async_local_storage_unavailable ``` The node API `AsyncLocalStorage` is not available, but is required to use async server rendering. ``` Some platforms require configuration flags to enable this API. Consult your platform's documentation. ### await_invalid ``` Encountered asynchronous work while rendering synchronously. ``` You (or the framework you're using) called [`render(...)`](svelte-server#render) with a component containing an `await` expression. Either `await` the result of `render` or wrap the `await` (or the component containing it) in a [``](svelte-boundary) with a `pending` snippet. ### dynamic_element_invalid_tag ``` `` is not a valid element name — the element will not be rendered ``` The value passed to the `this` prop of `` must be a valid HTML element, SVG element, MathML element, or custom element name. A value containing invalid characters (such as whitespace or special characters) was provided, which could be a security risk. Ensure only valid tag names are passed. ### html_deprecated ``` The `html` property of server render results has been deprecated. Use `body` instead. ``` ### hydratable_clobbering ``` Attempted to set `hydratable` with key `%key%` twice with different values. %stack% ``` This error occurs when using `hydratable` multiple times with the same key. To avoid this, you can: - Ensure all invocations with the same key result in the same value - Update the keys to make both instances unique ```svelte ``` ### hydratable_serialization_failed ``` Failed to serialize `hydratable` data for key `%key%`. `hydratable` can serialize anything [`uneval` from `devalue`](https://npmjs.com/package/devalue) can, plus Promises. Cause: %stack% ``` ### invalid_csp ``` `csp.nonce` was set while `csp.hash` was `true`. These options cannot be used simultaneously. ``` ### invalid_id_prefix ``` The `idPrefix` option cannot include `--`. ``` ### lifecycle_function_unavailable ``` `%name%(...)` is not available on the server ``` Certain methods such as `mount` cannot be invoked while running in a server context. Avoid calling them eagerly, i.e. not during render. ### server_context_required ``` Could not resolve `render` context. ``` Certain functions such as `hydratable` cannot be invoked outside of a `render(...)` call, such as at the top level of a module. ## Shared errors ### custom_renderer_unavailable_on_server ``` You need to specify a custom condition to use a custom renderer in a non-browser environment such as Node. Add the `svelte-custom-renderer` resolve condition (eg. run Node with `--conditions=svelte-custom-renderer`). If you're using a bundler, add `svelte-custom-renderer` to its list of resolve conditions instead. ``` ### experimental_async_required ``` Cannot use `%name%(...)` unless the `experimental.async` compiler option is `true` ``` ### invalid_default_snippet ``` Cannot use `{@render children(...)}` if the parent component uses `let:` directives. Consider using a named snippet instead ``` This error would be thrown in a setup like this: ```svelte {entry} ``` ```svelte
          {#each items as item}
        • {@render children(item)}
        • {/each}
        ``` Here, `List.svelte` is using `{@render children(item)` which means it expects `Parent.svelte` to use snippets. Instead, `Parent.svelte` uses the deprecated `let:` directive. This combination of APIs is incompatible, hence the error. ### invalid_snippet ``` Could not `{@render}` a non-snippet value ``` ### invalid_snippet_arguments ``` A snippet function was passed invalid arguments. Snippets should only be instantiated via `{@render ...}` ``` ### invalid_snippet_nullish ``` Could not `{@render}` snippet due to the expression being `null` or `undefined`. Consider using optional chaining `{@render snippet?.()}` ``` ### invariant_violation ``` An invariant violation occurred, meaning Svelte's internal assumptions were flawed. This is a bug in Svelte, not your app — please open an issue at https://github.com/sveltejs/svelte, citing the following message: "%message%" ``` ### lifecycle_outside_component ``` `%name%(...)` can only be used during component initialisation ``` Certain lifecycle methods can only be used during component initialisation. To fix this, make sure you're invoking the method inside the _top level of the instance script_ of your component. ```svelte ``` ### missing_context ``` Context was not set in the current component or any of its ancestors ``` The [`createContext()`](svelte#createContext) utility returns a `[get, set, has]` triplet of functions. `get` will throw an error if `set` was not used to set the context in the current component or any of its ancestors. ### set_context_after_init ``` `setContext` must be called when a component first initializes, not in a subsequent effect or after an `await` expression ``` This restriction only applies when using the `experimental.async` option, which will be active by default in Svelte 6. ### snippet_without_render_tag ``` Attempted to render a snippet without a `{@render}` block. This would cause the snippet code to be stringified instead of its content being rendered to the DOM. To fix this, change `{snippet}` to `{@render snippet()}`. ``` A component throwing this error will look something like this (`children` is not being rendered): ```svelte {children} ``` ...or like this (a parent component is passing a snippet where a non-snippet value is expected): ```svelte {#snippet label()} Hi! {/snippet} ``` ```svelte

        {label}

        ``` ### store_invalid_shape ``` `%name%` is not a store with a `subscribe` method ``` ### svelte_element_invalid_this_value ``` The `this` prop on `` must be a string, if defined ``` # Runtime warnings ## Client warnings ### assignment_value_stale ``` Assignment to `%property%` property (%location%) will evaluate to the right-hand side, not the value of `%property%` following the assignment. This may result in unexpected behaviour. ``` Given a case like this... ```svelte

        items: {JSON.stringify(object.items)}

        ``` ...the array being pushed to when the button is first clicked is the `[]` on the right-hand side of the assignment, but the resulting value of `object.array` is an empty state proxy. As a result, the pushed value will be discarded. You can fix this by separating it into two statements: ```js let object = { array: [0] }; // ---cut--- function add() { object.array ??= []; object.array.push(object.array.length); } ``` ### await_reactivity_loss ``` Detected reactivity loss when reading `%name%`. This happens when state is read in an async function after an earlier `await` ``` Svelte's signal-based reactivity works by tracking which bits of state are read when a template or `$derived(...)` expression executes. If an expression contains an `await`, 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 an `await` that is not 'visible' inside the expression. In a case like this... ```js let a = Promise.resolve(1); let b = 2; // ---cut--- async function sum() { return await a + b; } let total = $derived(await sum()); ``` ...`total` will depend on `a` (which is read immediately) but not `b` (which is not). The solution is to pass the values into the function: ```js let a = Promise.resolve(1); let b = 2; // ---cut--- /** * @param {Promise} a * @param {number} b */ async function sum(a, b) { return await a + b; } let total = $derived(await sum(a, b)); ``` ### await_waterfall ``` An async derived, `%name%` (%location%) was not read immediately after it resolved. This often indicates an unnecessary waterfall, which can slow down your app ``` In a case like this... ```js async function one() { return 1 } async function two() { return 2 } // ---cut--- let a = $derived(await one()); let b = $derived(await two()); ``` ...the second `$derived` will not be created until the first one has resolved. Since `await two()` does not depend on the value of `a`, this delay, often described as a 'waterfall', is unnecessary. (Note that if the values of `await one()` and `await two()` subsequently change, they can do so concurrently — the waterfall only occurs when the deriveds are first created.) You can solve this by creating the promises first and _then_ awaiting them: ```js async function one() { return 1 } async function two() { return 2 } // ---cut--- let aPromise = $derived(one()); let bPromise = $derived(two()); let a = $derived(await aPromise); let b = $derived(await bPromise); ``` ### binding_property_non_reactive ``` `%binding%` is binding to a non-reactive property ``` ``` `%binding%` (%location%) is binding to a non-reactive property ``` ### console_log_state ``` Your `console.%method%` contained `$state` proxies. Consider using `$inspect(...)` or `$state.snapshot(...)` instead ``` When logging a [proxy](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy), browser devtools will log the proxy itself rather than the value it represents. In the case of Svelte, the 'target' of a `$state` proxy might not resemble its current value, which can be confusing. The easiest way to log a value as it changes over time is to use the [`$inspect`](/docs/svelte/$inspect) rune. Alternatively, to log things on a one-off basis (for example, inside an event handler) you can use [`$state.snapshot`](/docs/svelte/$state#$state.snapshot) to take a snapshot of the current value. ### derived_inert ``` Reading a derived belonging to a now-destroyed effect may result in stale values ``` A `$derived` value created inside an effect will stop updating when the effect is destroyed. You should create the `$derived` outside the effect, or inside an `$effect.root`. ### event_handler_invalid ``` %handler% should be a function. Did you mean to %suggestion%? ``` ### hydratable_missing_but_expected ``` Expected to find a hydratable with key `%key%` during hydration, but did not. ``` This can happen if you render a hydratable on the client that was not rendered on the server, and means that it was forced to fall back to running its function blockingly during hydration. This is bad for performance, as it blocks hydration until the asynchronous work completes. ```svelte ``` ### hydration_attribute_changed ``` The `%attribute%` attribute on `%html%` changed its value between server and client renders. The client value, `%value%`, will be ignored in favour of the server value ``` Certain attributes like `src` on an `` element will not be repaired during hydration, i.e. the server value will be kept. That's because updating these attributes can cause the image to be refetched (or in the case of an `