JAVASCRIPT

Sanitize User Input to Prevent XSS in React

Learn to sanitize user-generated content in React using a library like DOMPurify to prevent Cross-Site Scripting (XSS) vulnerabilities and safely render HTML.

import React from 'react';
import DOMPurify from 'dompurify'; // npm install dompurify

function UserComment({ comment }) {
  // It's generally safer to sanitize on the server before storing,
  // but client-side sanitization adds a layer of defense for display.
  const sanitizedComment = DOMPurify.sanitize(comment.content, {
    USE_PROFILES: { html: true }, // allow standard HTML tags
    FORBID_TAGS: ['script', 'iframe'], // explicitly forbid dangerous tags
    FORBID_ATTR: ['onload', 'onerror', 'onmouseover'], // forbid dangerous attributes
  });

  return (
    <div className="comment">
      <h3>{comment.author}</h3>
      {/* DANGEROUS: Do NOT use dangerouslySetInnerHTML directly with unsanitized input */}
      {/* <p dangerouslySetInnerHTML={{ __html: comment.content }}></p> */}

      {/* SAFE: Use sanitized HTML */}
      <p dangerouslySetInnerHTML={{ __html: sanitizedComment }}></p>

      {/* If you don't need to render HTML, always prefer rendering as plain text */}
      {/* <p>{comment.content}</p> */}
    </div>
  );
}

function App() {
  const userComments = [
    { id: 1, author: 'Alice', content: 'Hello <b>world</b>!' },
    { id: 2, author: 'Bob', content: 'What a beautiful day! <img src="x" onerror="alert(\'XSS!\')">' },
    { id: 3, author: 'Charlie', content: '<script>alert("Malicious script!");</script>Check this out.' },
  ];

  return (
    <div>
      <h1>Comments</h1>
      {userComments.map(comment => (
        <UserComment key={comment.id} comment={comment} />
      ))}
    </div>
  );
}

export default App;
How it works: This React snippet demonstrates client-side sanitization of user-generated HTML to prevent Cross-Site Scripting (XSS) attacks. It uses the `dompurify` library to clean potentially malicious HTML input before rendering it with `dangerouslySetInnerHTML`. While server-side sanitization is the primary defense, client-side sanitization provides an additional layer, ensuring that even if content bypasses server checks, it won't execute harmful scripts in the user's browser.

Need help integrating this into your project?

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

Hire DigitalCodeLabs