JAVASCRIPT

Secure HTML Sanitization for User-Generated Content (DOMPurify)

Implement robust HTML sanitization using DOMPurify in JavaScript to safely render user-generated content and prevent XSS attacks in your web applications.

// Assumes DOMPurify is loaded (e.g., via CDN <script src="https://unpkg.com/dompurify@latest/dist/purify.min.js"></script>)
// or imported as a module (import DOMPurify from 'dompurify';)

function sanitizeUserInputHTML(untrustedHTML) {
    if (typeof untrustedHTML !== 'string') {
        console.warn('Input for sanitization is not a string.');
        return ''; // Or throw an error, depending on desired behavior
    }

    // Configuration options for DOMPurify:
    // - ALLOWED_TAGS: Specify which HTML tags are permitted.
    // - ALLOWED_ATTR: Specify which attributes are permitted on allowed tags.
    // - FORBID_TAGS: Explicitly forbid certain tags.
    // - ADD_TAGS/ADD_ATTR: Custom tags/attributes to allow.
    // - USE_PROFILES: Convenient presets like 'html', 'mathml', 'svg'.
    const config = {
        USE_PROFILES: { html: true }, // Use the HTML profile
        // ALLOWED_TAGS: ['b', 'i', 'a', 'p', 'br', 'ul', 'ol', 'li', 'strong', 'em', 'img', 'div'],
        // ALLOWED_ATTR: ['href', 'src', 'alt', 'title', 'class', 'style'],
        // FORBID_TAGS: ['script', 'iframe', 'object', 'embed', 'form'], // Already blocked by default/profiles
        // Keep the default configuration unless you have specific needs to loosen it.
        // DOMPurify is very strict by default.
    };

    // Sanitize the HTML string
    const cleanHTML = DOMPurify.sanitize(untrustedHTML, config);
    return cleanHTML;
}

// Example Usage:
// const dirtyHTML = `
//     <img src="x" onerror="alert('XSS Attack!')">
//     <a href="javascript:alert('Another XSS!')">Click Me</a>
//     <p>Hello <b>World</b>!</p>
//     <svg/onload=alert(1)>
// `;

// const safeHTML = sanitizeUserInputHTML(dirtyHTML);
// console.log('Original:
', dirtyHTML);
// console.log('Sanitized:
', safeHTML);

// To display in browser (e.g., in a div):
// const outputDiv = document.getElementById('output');
// if (outputDiv) {
//     outputDiv.innerHTML = safeHTML;
// }
How it works: This JavaScript snippet demonstrates how to securely sanitize user-generated HTML content using the DOMPurify library. When users can input HTML, it's crucial to remove potentially malicious scripts and attributes (like `onerror` or `javascript:` URLs) to prevent Cross-Site Scripting (XSS) attacks. DOMPurify creates a sanitized HTML string, allowing only safe tags and attributes as defined by its strict default configuration or custom profiles, making it safe to render in the browser and significantly more robust than basic alphanumeric filtering.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs