javascript / expert
Snippet
Sanitizing Reactive Untrusted HTML Strings with DOMPurify and Custom Trusted Types
Rendering dynamic HTML content via raw directives exposes applications to Cross-Site Scripting (XSS). This expert snippet combines Vue computed properties with DOMPurify and browser Trusted Types. By wrapping the output in a Trusted Types security policy, modern browsers enforce strict policy compliance at the DOM injection point, stripping malicious script payloads dynamically whenever reactive input references change.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import { ref, computed } from 'vue';import DOMPurify from 'dompurify';const rawUserInput = ref('<img src=x onerror=alert(1)> Hello');const sanitizedHtml = computed(() => {if (typeof window !== 'undefined' && window.trustedTypes) {const policy = window.trustedTypes.createPolicy('vueSanitizer', {createHTML: (string) => DOMPurify.sanitize(string, { RETURN_TRUSTED_TYPE: true })});return policy.createHTML(rawUserInput.value);}return DOMPurify.sanitize(rawUserInput.value);});
vue
Breakdown
1
const sanitizedHtml = computed(() => {
Defines a read-only reactive computed signal that recalculates only when untrusted inputs mutate.
2
if (typeof window !== 'undefined' && window.trustedTypes) {
Guards against SSR environments while verifying native browser support for the W3C Trusted Types API.
3
window.trustedTypes.createPolicy('vueSanitizer', {
Creates an immutable policy object that converts raw strings into typed TrustedHTML objects.
4
createHTML: (string) => DOMPurify.sanitize(string, { RETURN_TRUSTED_TYPE: true })
Passes the input through DOMPurify with the RETURN_TRUSTED_TYPE flag enabled for standard conformance.
5
return policy.createHTML(rawUserInput.value);
Executes the policy transformation returning an encapsulated string token suitable for v-html binding.