JAVASCRIPT

Safely Sanitize HTML Input for XSS Prevention

Learn to prevent Cross-Site Scripting (XSS) attacks by safely sanitizing user-generated HTML content using the DOMPurify library in Node.js.

// Install: npm install dompurify jsdom
const { JSDOM } = require('jsdom');
const createDOMPurify = require('dompurify');

// Initialize JSDOM for a server-side DOM environment
const window = new JSDOM('').window;
const DOMPurify = createDOMPurify(window);

function sanitizeHtmlInput(untrustedHtml) {
  // Sanitize the input HTML string
  const cleanHtml = DOMPurify.sanitize(untrustedHtml, {
    USE_PROFILES: { html: true }, // Ensure HTML tags are allowed
    FORBID_TAGS: ['script', 'iframe'], // Explicitly forbid dangerous tags
    FORBID_ATTR: ['onerror', 'onload'] // Explicitly forbid dangerous attributes
  });
  return cleanHtml;
}

// Example usage:
// const userInput = '<img src="x" onerror="alert(\'XSS!\')">Hello <script>alert("Malicious script")</script> <b>World</b>!';
// const sanitizedOutput = sanitizeHtmlInput(userInput);
// console.log("Original Input:", userInput);
// console.log("Sanitized Output:", sanitizedOutput);
// Expected: <img src="x">Hello <b>World</b>! (script and onerror removed)

// const safeInput = '<p>This is a <em>safe</em> paragraph.</p>';
// const sanitizedSafeOutput = sanitizeHtmlInput(safeInput);
// console.log("Original Safe Input:", safeInput);
// console.log("Sanitized Safe Output:", sanitizedSafeOutput);
// Expected: <p>This is a <em>safe</em> paragraph.</p>
How it works: This JavaScript snippet demonstrates how to prevent Cross-Site Scripting (XSS) vulnerabilities by sanitizing untrusted HTML input using the `DOMPurify` library. It initializes `DOMPurify` with a `JSDOM` environment for server-side use. The `sanitizeHtmlInput` function strips out potentially malicious tags (like `<script>`) and attributes (like `onerror`) while preserving safe HTML, ensuring that user-generated content rendered on a webpage does not execute unintended code.

Need help integrating this into your project?

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

Hire DigitalCodeLabs