ReactEasy
What is Sanitization?
Sanitization is cleaning untrusted input so that dangerous parts are removed or neutralized before you use it. For HTML, it means stripping scripts, event handler attributes (onerror, onclick), javascript: URLs and other risky elements while keeping safe formatting. In React you sanitize with a library such as DOMPurify before passing HTML to dangerouslySetInnerHTML.
When you need it
- Rendering HTML from a CMS, a rich-text editor, emails or user comments.
- Converting markdown to HTML (markdown can contain raw HTML).
- Building URLs from user input.
- Inserting user content into SVGs, iframes (
srcdoc) or styles.
Sanitize vs escape vs validate
- Escaping: turn special characters into harmless text. React does this automatically for JSX text.
- Sanitizing: keep some markup but remove dangerous parts. Needed only when you intentionally render HTML.
- Validating: reject input that does not match the expected format (email, URL protocol, numeric ID). Do it on the server as well.
Good practices
- Use a maintained library (DOMPurify,
sanitize-htmlon Node.js). Never write your own regex-based sanitizer. - Sanitize as close to rendering as possible, and also on the server if content is stored.
- Configure allowlists of tags and attributes for your use case.
- Prefer rendering structured data or markdown with a React renderer (
react-markdownwithout raw HTML) over HTML strings. - With Trusted Types enforced, have DOMPurify return
TrustedHTML(RETURN_TRUSTED_TYPE: true); React 19.3 passes it to the DOM unchanged.
Code example
tsx
1import DOMPurify from "dompurify";23const dirty = `4 <h2>Release notes</h2>5 <p onclick="steal()">Click me</p>6 <img src="x" onerror="alert('xss')">7 <a href="javascript:alert(1)">bad link</a>8 <script>alert('xss')</script>9`;1011const clean = DOMPurify.sanitize(dirty, {12 ALLOWED_TAGS: ["h2", "p", "a", "strong", "em", "ul", "ol", "li", "img"],13 ALLOWED_ATTR: ["href", "src", "alt"],14});15// -> <h2>Release notes</h2><p>Click me</p><img src="x"><a>bad link</a>1617export function ReleaseNotes() {18 return <section dangerouslySetInnerHTML={{ __html: clean }} />;19}2021// Validation example for URLs22export const isSafeUrl = (value: string) => /^(https?:|mailto:)/i.test(value);
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.