0 day streak
javascript / intermediate
Snippet

Sanitizing User-Generated Rich Text with DOMPurify

Injecting dynamic HTML via dangerouslySetInnerHTML exposes React applications to Cross-Site Scripting (XSS) attacks. Using DOMPurify strips malicious executable scripts and unapproved HTML attributes, returning a safe string primitive before rendering.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import React, { useState } from 'react';
import DOMPurify from 'dompurify';
export function SafeHtmlViewer({ rawUserInput }) {
const sanitizedHtml = DOMPurify.sanitize(rawUserInput, {
ALLOWED_TAGS: ['b', 'i', 'em', 'strong', 'a'],
ALLOWED_ATTR: ['href', 'title']
});
return (
<div
className="preview-box"
dangerouslySetInnerHTML={{ __html: sanitizedHtml }}
/>
);
}
react
Breakdown
1
import DOMPurify from 'dompurify';
Imports the sanitization library to parse and clean untrusted HTML strings.
2
const sanitizedHtml = DOMPurify.sanitize(rawUserInput, {
Executes HTML sanitization against a strict configuration whitelist.
3
ALLOWED_TAGS: ['b', 'i', 'em', 'strong', 'a'],
Restricts allowed DOM nodes to safe inline typography and anchor elements.
4
dangerouslySetInnerHTML={{ __html: sanitizedHtml }}
Safely injects the sanitized HTML string into the React element without XSS vulnerability.