JAVASCRIPT

Sanitize User Input to Prevent XSS with DOMPurify

Prevent Cross-Site Scripting (XSS) attacks by safely sanitizing user-generated HTML content before rendering, utilizing the robust DOMPurify library for comprehensive protection.

// Make sure to include DOMPurify in your project (e.g., via npm install dompurify or CDN)
// import DOMPurify from 'dompurify'; // If using modules

// For a browser environment, assuming DOMPurify is globally available
// or loaded via a script tag.
// If running in Node.js for server-side rendering, you might need to
// configure a JSDOM environment first:
// const createDOMPurify = require('dompurify');
// const { JSDOM } = require('jsdom');
// const window = new JSDOM('').window;
// const DOMPurify = createDOMPurify(window);

function sanitizeHtmlContent(htmlString) {
    if (typeof DOMPurify === 'undefined') {
        console.error("DOMPurify is not loaded. Please ensure it's available.");
        return htmlString; // Fallback or throw error
    }
    // Sanitize the HTML string
    const cleanHtml = DOMPurify.sanitize(htmlString, {
        USE_PROFILES: { html: true }, // Ensure basic HTML elements are allowed
        FORBID_ATTR: ['style'], // Example: forbid inline styles
        FORBID_TAGS: ['script', 'iframe'], // Example: explicitly forbid script/iframe
        // ALLOW_DATA_ATTR: false, // Example: disable data-attributes
    });
    return cleanHtml;
}

// Example Usage:
const unsafeInput = '<img src="x" onerror="alert(\'XSS Attack!\')" />' +
                    '<p>Hello <script>alert("another XSS");</script> World</p>' +
                    '<a href="javascript:alert(\'bad link\')">Click me</a>' +
                    '<div style="width:100px;">Safe content</div>';

const safeOutput = sanitizeHtmlContent(unsafeInput);

console.log('Original:
', unsafeInput);
console.log('Sanitized:
', safeOutput);

// To display in a browser (e.g., innerHTML of a div):
// document.getElementById('outputDiv').innerHTML = safeOutput;
How it works: This snippet demonstrates how to prevent Cross-Site Scripting (XSS) vulnerabilities by sanitizing user-provided HTML content using the `DOMPurify` library. XSS attacks occur when malicious scripts are injected into web pages viewed by other users. `DOMPurify.sanitize()` meticulously parses the input, removes all potentially dangerous elements and attributes (like `script` tags or `onerror` attributes), and returns a safe HTML string suitable for display. It's crucial to sanitize any user-generated content before rendering it on a page, especially when `innerHTML` is used.

Need help integrating this into your project?

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

Hire DigitalCodeLabs