Client-Side Sanitisation
Also Known As
DOMPurify
Sanitizer API
Trusted Types
XSS prevention JS
TL;DR
DOMPurify and the Sanitizer API remove dangerous HTML before insertion — complementing PHP's server-side htmlspecialchars for rich-text scenarios.
Explanation
When rich HTML must be rendered (user-formatted posts, markdown output), textContent is too restrictive. DOMPurify.sanitize(html) strips script tags, event handlers, and dangerous attributes while keeping safe formatting. The native Sanitizer API (Chrome 105+) provides built-in sanitisation. Trusted Types (Chrome) enforce that only sanitised values reach innerHTML. Server-side sanitisation (PHP's HTMLPurifier) is the primary defence — client-side sanitisation is defence-in-depth.
Common Misconception
✗ Client-side DOMPurify is sufficient XSS protection — DOMPurify can be bypassed if the attacker controls the execution environment; server-side sanitisation (HTMLPurifier, strip_tags with allowlist) must be the primary defence.
Why It Matters
Rich text editors and markdown renderers must insert HTML — without sanitisation any stored user content becomes a stored XSS attack vector.
Common Mistakes
- Relying on DOMPurify as the only XSS defence (no server-side sanitisation)
- Not configuring DOMPurify allowlist for your specific allowed tags
- Sanitising after insertion — sanitise before innerHTML, not after
Code Examples
✗ Vulnerable
// Raw innerHTML — stored XSS:
el.innerHTML = post.htmlContent; // attacker's script executes
✓ Fixed
// DOMPurify — safe HTML insertion:
import DOMPurify from 'dompurify';
const clean = DOMPurify.sanitize(post.htmlContent, {
ALLOWED_TAGS: ['b','i','em','strong','a','p','ul','li'],
ALLOWED_ATTR: ['href', 'target'],
});
el.innerHTML = clean;
// Native Sanitizer API (modern browsers):
const sanitizer = new Sanitizer();
el.setHTML(post.htmlContent, { sanitizer });
References
Tags
🤝 Adopt this term
£79/year · your link shown here
Added
17 Mar 2026
Edited
22 Mar 2026
Views
31
🤖 AI Guestbook educational data only
|
|
Last 30 days
Agents 1
Amazonbot 7
ChatGPT 7
Perplexity 4
Google 3
Ahrefs 2
SEMrush 2
Majestic 1
Also referenced
How they use it
crawler 24
crawler_json 2
Related categories
⚡
DEV INTEL
Tools & Severity
🔴 Critical
⚙ Fix effort: Low
⚡ Quick Fix
Use DOMPurify.sanitize(html) before any innerHTML assignment of user-generated content — and also sanitise server-side with HTMLPurifier
📦 Applies To
javascript ES2015
web
🔗 Prerequisites
🔍 Detection Hints
innerHTML with variable from API response or user input without DOMPurify; markdown rendered HTML inserted without sanitisation
Auto-detectable:
✓ Yes
eslint
semgrep
⚠ Related Problems
🤖 AI Agent
Confidence: High
False Positives: Medium
✗ Manual fix
Fix: Medium
Context: Function
Tests: Update
CWE-79
CWE-20