javascript / expert
Snippet
Secure Dynamic HTML with Sanitization
Using the '{@html}' tag in Svelte bypasses the template compiler's safety mechanisms. For expert applications handling user-generated content, integrating a library like DOMPurify is critical to prevent Cross-Site Scripting (XSS). Note that sanitization logic must be handled carefully in SSR environments to match client-side output.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<script>import DOMPurify from 'dompurify';import { browser } from '$app/environment';export let unsafeUserContent = '<img src=x onerror=alert(1)>';$: sanitizedHtml = browser? DOMPurify.sanitize(unsafeUserContent): unsafeUserContent; // Server-side fallback logic needed</script><div class="prose">{@html sanitizedHtml}</div>
svelte
Breakdown
1
$: sanitizedHtml = ...
A reactive statement that re-sanitizes the content whenever the input changes.
2
{@html sanitizedHtml}
Renders the string as raw HTML. Security is now managed by DOMPurify, not Svelte.