javascript / intermediate
Snippet
Sanitizing Untrusted HTML Input to Prevent XSS Attacks
Using v-html in Vue bypasses template escaping and introduces cross-site scripting (XSS) risks. Integrating DOMPurify inside a computed property removes malicious JavaScript and attributes before the HTML string gets bound to the DOM.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import { defineComponent, computed, ref } from 'vue';import DOMPurify from 'dompurify';export default defineComponent({setup() {const untrustedUserInput = ref('<img src="x" onerror="alert(1)"><b>Safe User Comment</b>');const sanitizedHtml = computed(() => {return DOMPurify.sanitize(untrustedUserInput.value, {ALLOWED_TAGS: ['b', 'i', 'em', 'strong', 'p'],ALLOWED_ATTR: []});});return { sanitizedHtml };},template: '<div v-html="sanitizedHtml"></div>'});
vue
Breakdown
1
const untrustedUserInput = ref('<img src="x" onerror="alert(1)"><b>Safe User Comment</b>');
Holds dynamic raw user content containing potentially malicious executable scripts.
2
const sanitizedHtml = computed(() => {
Creates a reactive computed value that cleans the input whenever the source changes.
3
return DOMPurify.sanitize(untrustedUserInput.value, { ALLOWED_TAGS: ['b', 'i', 'em', 'strong', 'p'], ALLOWED_ATTR: [] });
Applies a strict whitelist of safe HTML tags and eliminates dangerous attributes like onerror or onclick.
4
template: '<div v-html="sanitizedHtml"></div>'
Safely renders the sanitized HTML fragment into the component markup.