javascript / intermediate
Snippet
Safe HTML Rendering in React via DOMPurify Sanitization
Directly injecting raw user-generated markup via `dangerouslySetInnerHTML` exposes React applications to Cross-Site Scripting (XSS) attacks. By sanitizing untrusted strings through DOMPurify with an explicit whitelist of allowed tags and attributes, you neutralize malicious script execution before passing markup to the DOM.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import DOMPurify from 'dompurify';const SANITIZE_CONFIG = {ALLOWED_TAGS: ['b', 'i', 'em', 'strong', 'a', 'p', 'code'],ALLOWED_ATTR: ['href', 'target', 'rel']};export function SafeRichText({ rawHtml, className }) {const cleanHtml = DOMPurify.sanitize(rawHtml, SANITIZE_CONFIG);return (<divclassName={className}dangerouslySetInnerHTML={{ __html: cleanHtml }}/>);}
react
Breakdown
1
ALLOWED_TAGS: ['b', 'i', 'em', 'strong', 'a', 'p', 'code'],
Defines an allowlist restricting accepted HTML nodes to safe formatting tags, stripping `<script>` and `<iframe>`.
2
const cleanHtml = DOMPurify.sanitize(rawHtml, SANITIZE_CONFIG);
Parses and strips executable scripts, unlisted tags, and event handlers like `onload` or `onerror`.
3
dangerouslySetInnerHTML={{ __html: cleanHtml }}
Instructs React to render the sanitized HTML string directly into the container element.