javascript / intermediate
Snippet
Preventing XSS Vulnerabilities in Dynamic Svelte HTML Binding
Using Svelte's `{@html}` directive directly with untrusted user input introduces Cross-Site Scripting (XSS) security risks. Sanitizing incoming raw HTML strings dynamically via a library like DOMPurify inside a reactive statement ensures malicious script execution is prevented before rendering.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
<script>import DOMPurify from 'dompurify';export let rawUserInput = '<img src=x onerror=alert(1)> Hello!';$: sanitizedContent = typeof rawUserInput === 'string'? DOMPurify.sanitize(rawUserInput): '';</script><div class="user-content">{@html sanitizedContent}</div>
svelte
Breakdown
1
import DOMPurify from 'dompurify';
Imports an HTML sanitization library designed to strip dangerous JavaScript payloads from raw HTML strings.
2
export let rawUserInput = '<img src=x onerror=alert(1)> Hello!';
Declares a component prop representing untrusted user input that may contain malicious code snippets.
3
$: sanitizedContent = typeof rawUserInput === 'string' ? DOMPurify.sanitize(rawUserInput) : '';
Executes a reactive declaration that cleans the input string whenever rawUserInput changes, enforcing type safety.
4
{@html sanitizedContent}
Safely injects the sanitized HTML string into the DOM without risk of executing unauthorized script tags.