← Back to all snippets
JAVASCRIPT

Sanitize User Input to Prevent XSS Attacks

Learn to sanitize user-generated content on the server-side using DOMPurify in Node.js to effectively prevent Cross-Site Scripting (XSS) vulnerabilities.

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

function sanitizeHtmlInput(htmlString) {
  // Basic sanitization options, customize as needed
  const cleanHtml = DOMPurify.sanitize(htmlString, {
    USE_PROFILES: { html: true }, // Allows standard HTML elements
    FORBID_TAGS: ['script', 'style', 'iframe'], // Explicitly forbid common XSS vectors
    FORBID_ATTR: ['onerror', 'onload', 'onmouseover'], // Forbid common event handlers
    ALLOW_DATA_ATTR: false // Disallow data- attributes by default
  });
  return cleanHtml;
}

// Example usage in an Express route
// const express = require('express');
// const app = express();
// app.use(express.json());

// app.post('/submit-comment', (req, res) => {
//   const rawComment = req.body.comment;
//   const sanitizedComment = sanitizeHtmlInput(rawComment);
//   // Save sanitizedComment to database or display it
//   res.send('Comment received and sanitized: ' + sanitizedComment);
// });

// console.log(sanitizeHtmlInput('<img src=x onerror=alert(1)>Test<script>alert(2)<\/script>'));
// console.log(sanitizeHtmlInput('<a href="javascript:alert(3)">Click me<\/a>'));
// console.log(sanitizeHtmlInput('<p><b data-info="some-data">Hello<\/b> world<\/p>'));
How it works: This snippet demonstrates how to sanitize user-provided HTML content on the server using `DOMPurify` to prevent XSS attacks. `DOMPurify` parses the HTML, removes malicious scripts, invalid tags, and dangerous attributes, ensuring only safe content is processed or displayed. It's crucial to always sanitize user input that might contain HTML before storing it in a database or rendering it back to the client.

Need help integrating this into your project?

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

Hire DigitalCodeLabs