0 day streak
javascript / intermediate
Snippet

Preventing Cross-Site Scripting (XSS) in Dynamic HTML Injection with DOMPurify

Injecting raw HTML via dangerouslySetInnerHTML exposes applications to Cross-Site Scripting (XSS) attacks. Using an established sanitization library like DOMPurify strips malicious JavaScript payloads, executable attributes, and unwanted tags before the browser DOM parses the payload.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import DOMPurify from 'dompurify';
function SafeHtmlViewer({ untrustedMarkup }) {
const sanitizedContent = DOMPurify.sanitize(untrustedMarkup, {
USE_PROFILES: { html: true },
FORBID_TAGS: ['script', 'iframe'],
FORBID_ATTR: ['onerror', 'onload', 'onclick']
});
return (
<article
className="user-rendered-content"
dangerouslySetInnerHTML={{ __html: sanitizedContent }}
/>
);
}
react
Breakdown
1
const sanitizedContent = DOMPurify.sanitize(untrustedMarkup, {
Passes the untrusted string through a sanitization parser that strips harmful scripts and nodes.
2
FORBID_TAGS: ['script', 'iframe'],
Configures strict tag blacklisting to disallow execution context embedding.
3
FORBID_ATTR: ['onerror', 'onload', 'onclick']
Blocks inline event handler attributes capable of executing arbitrary JavaScript code.
4
dangerouslySetInnerHTML={{ __html: sanitizedContent }}
Renders the verified clean HTML string into the React element without XSS vulnerability.