React › Security in React (XSS & dangerouslySetInnerHTML)

How would you safely display user generated HTML content, such as a rich text comment, without exposing your app to XSS attacks?

Advanced

Answer

You use a trusted sanitization library, like DOMPurify, to clean the HTML first, removing any dangerous scripts or unsafe attributes, before ever passing the result into dangerouslySetInnerHTML. This lets you safely support formatted content like bold text or links while blocking anything genuinely harmful.
import DOMPurify from 'dompurify';

function Comment({ rawHtml }) {
  const cleanHtml = DOMPurify.sanitize(rawHtml);
  return <div dangerouslySetInnerHTML={{ __html: cleanHtml }} />;
}
Real-world example A forum allows users to write formatted comments using basic HTML tags like bold and italics, safely cleaning every comment through DOMPurify before displaying it, blocking any hidden malicious script a bad actor might try to sneak in.

Common follow-ups: What specific kinds of malicious content does a library like DOMPurify actually remove?;Is sanitizing on the server, in addition to the client, also recommended for extra safety?