javascript / intermediate
Snippet
Preventing Cross-Site Scripting by Sanitizing Rich Text with DOMPurify
Rendering user-controlled HTML directly in React with dangerouslySetInnerHTML exposes applications to Cross-Site Scripting (XSS) attacks. Using DOMPurify with an explicit tag and attribute whitelist removes malicious payloads (such as inline scripts, onerror handlers, or javascript: URIs) before passing the string to the DOM.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import React from 'react';import DOMPurify from 'dompurify';export function SafeHtmlViewer({ rawHtmlContent }) {const sanitizedHtml = DOMPurify.sanitize(rawHtmlContent, {ALLOWED_TAGS: ['b', 'i', 'em', 'strong', 'a', 'p'],ALLOWED_ATTR: ['href', 'target', 'rel']});return (<divclassName="content-preview"dangerouslySetInnerHTML={{ __html: sanitizedHtml }}/>);}
react
Breakdown
1
const sanitizedHtml = DOMPurify.sanitize(rawHtmlContent, {
Calls the sanitizer function to parse and strip forbidden elements from the input string.
2
ALLOWED_TAGS: ['b', 'i', 'em', 'strong', 'a', 'p'],
Defines a strict whitelist of safe markup tags permitted in the sanitized output.
3
dangerouslySetInnerHTML={{ __html: sanitizedHtml }}
Injects the verified, sanitized HTML payload safely into the React-managed DOM node.