tezvyn:

Svelte's `{@html}` and `{@debug}`: When to Use Them

AI-drafted, machine-checkedSource: svelte.devadvanced
Svelte's `{@html}` and `{@debug}`: When to Use Them

Svelte's `{@html}` and `{@debug}` offer powerful but risky escapes. `{@html}` renders raw HTML strings, while `{@debug}` acts like a `debugger` statement in your markup. Use them for trusted content and dev-time inspection.

WHY IT EXISTS Svelte provides safe, performant ways to update the DOM. But sometimes you need to break out of that model, either to render pre-formatted HTML from a trusted source or to inspect the state of your component during development without littering your code with console.log().

THE MENTAL MODEL Think of {@html} and {@debug} as Svelte's "break glass in case of emergency" tools. {@html} is like telling Svelte, "Step aside, I'll handle this part of the DOM myself," by injecting a raw HTML string. {@debug} is a debugger statement for your template, pausing execution to let you inspect reactive state changes as they happen.

HOW IT WORKS For {@html}, you pass it a string variable containing HTML. Svelte will parse this string and insert the resulting DOM nodes, bypassing its usual diffing and update mechanisms for that content. Example: {@html myHtmlString}. For {@debug}, you can list variables to inspect: {@debug user, permissions}. When any of these variables change, Svelte triggers the browser's debugger, allowing you to see their current values in the console. If no variables are listed ({@debug}), it triggers whenever any state changes.

WHEN TO USE IT Use {@html} when you have HTML content from a trusted source, like a headless CMS that returns rich text as an HTML string. You must sanitize this content before rendering. Use {@debug} during development to understand why a component is re-rendering or to check the value of a complex derived store.

WHEN NOT TO USE IT The footgun is clear: NEVER use {@html} with raw, un-sanitized input from a user. This is a direct path to Cross-Site Scripting (XSS) vulnerabilities. Always sanitize first. For {@debug}, the rule is simple: NEVER ship it to production. It will pause execution for your users and expose your application's internal state. Most bundlers can be configured to warn you if you try to commit {@debug} statements.

ONE CANONICAL EXAMPLE Imagine a blog post fetched from an API where the body is an HTML string: const post = { body: '<h1>Welcome!</h1>This is my post.' };. In your Svelte component, you'd render it with {@html post.body}. If you were debugging why the post wasn't showing, you could add {@debug post} right before that line to inspect the post object in the browser's dev tools.

Read the original → svelte.dev

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.