0 day streak
javascript / intermediate
Snippet

Creating a Custom Sanitization Directive with DOMPurify to Prevent XSS

Using standard v-html in Vue directly exposes applications to Cross-Site Scripting (XSS) if data contains unsanitized user markup. A custom directive encapsulates sanitization logic using DOMPurify with strict whitelists of tags and attributes, ensuring that dynamic HTML is automatically cleansed whenever mounted or updated.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import DOMPurify from 'dompurify';
const SANITIZE_CONFIG = {
ALLOWED_TAGS: ['b', 'i', 'em', 'strong', 'a', 'p', 'ul', 'li'],
ALLOWED_ATTR: ['href', 'target', 'rel']
};
export const vSanitizeHtml = {
mounted(el, binding) {
const clean = DOMPurify.sanitize(binding.value ?? '', SANITIZE_CONFIG);
el.innerHTML = clean;
},
updated(el, binding) {
if (binding.value !== binding.oldValue) {
const clean = DOMPurify.sanitize(binding.value ?? '', SANITIZE_CONFIG);
el.innerHTML = clean;
}
}
};
vue
Breakdown
1
const SANITIZE_CONFIG = { ALLOWED_TAGS: [...], ALLOWED_ATTR: [...] };
Defines strict whitelists for allowed HTML elements and attributes to eliminate script vectors.
2
const clean = DOMPurify.sanitize(binding.value ?? '', SANITIZE_CONFIG);
Strips malicious tags, event listeners, and JavaScript URLs from the passed string.
3
if (binding.value !== binding.oldValue) {
Prevents redundant DOM updates and sanitization passes when values have not changed.