Web Security 05 🛡️ Context-Aware Encoding & Sanitization — Safe DOM rendering, framework escapes, and DOMPurify implementation
In the landscape of web security, “Sanitization” and “Encoding” are the primary defensive countermeasures against Cross-Site Scripting (XSS). While input validation attempts to ensure data conforms to a specific format before it enters a system, encoding and sanitization focus on the output—ensuring that when data is eventually rendered in a browser, it is interpreted strictly as data and never as executable code. The complexity of this task arises from the fact that a single web page contains multiple “contexts,” each with its own set of parsing rules. A string that is safely encoded for the body of a <div> may still trigger a high-severity vulnerability if placed inside a <script> block, an onclick handler, or a CSS property.
Context-aware encoding is the process of applying the correct transformation to a string based on its final destination in the Document Object Model (DOM). For example, HTML entity encoding converts the < character into <, which effectively neutralizes it within HTML tags. However, if that same data is placed inside a URL attribute like href, it requires percent-encoding, and if it is placed inside a JavaScript string, it requires Unicode escaping. Sanitization, conversely, is used when an application must allow a subset of “safe” HTML (such as <b> or <i> tags) while stripping out dangerous elements (like <script>, <iframe>, or onerror attributes).
This chapter covers the technical implementation of context-aware encoding across HTML, JavaScript, and URL contexts. It explores the mechanics of framework-level escaping, the dangers of “bypass” functions like dangerouslySetInnerHTML, and the integration of DOMPurify for robust client-side sanitization. The sections that follow define the specific encoding rules for various DOM sinks and provide a blueprint for implementing a multi-layered sanitization strategy.
Key point: Security is context-dependent; data must be encoded or sanitized specifically for the target “sink” (HTML, Attribute, JS, or URL) because a single encoding method is insufficient to protect all areas of a web document.
Why X exists
The multi-parser problem. A modern web browser does not use a single parser for a page. It switches between an HTML parser, a CSS parser, a URL parser, and a JavaScript engine. Because these parsers have different “special characters,” a payload that is inert to the HTML parser (like a string inside a JS variable) can become active if it breaks out of its quotes and is re-interpreted by the engine.
The “Safe HTML” trade-off. Many applications, such as CMS platforms or comment sections, require users to format their text using bold, italics, or links. Completely encoding this data would render the formatting as literal text (e.g., displaying <b> instead of making text bold). Sanitization exists to allow the “good” parts of HTML while programmatically identifying and removing the “bad” parts.
The framework “escape hatch” problem. Modern frontend frameworks (like React, Vue, or Angular) encode data by default to prevent XSS. However, they all provide “escape hatches” for developers who need to render raw HTML. These functions are often the source of critical vulnerabilities because they bypass the framework’s built-in security, shifting the entire burden of sanitization onto the developer.
The attribute injection problem. Placing untrusted data into an HTML attribute is significantly more dangerous than placing it in a tag’s text content. Even if < and > are encoded, an attacker can use a single quote ' or a double quote " to break out of the attribute and define new ones, such as onmouseover, effectively executing JavaScript without any script tags.
The URI/URL protocol problem. Encoding characters like < and > is useless if an attacker can control the protocol of a URL. If a user-provided link is rendered as <a href="javascript:alert(1)">, the browser will execute the code upon a click, regardless of whether the characters in the payload were encoded or not. Sanitization must include protocol whitelisting (e.g., only allowing http: and https:).
a. HTML Entity Encoding: Protecting the Tag Context
The most common context is the “HTML Body” or “HTML Element” context. This is the area between two tags, such as <div>UNTRUSTED_DATA</div>. In this context, the browser is looking for the < character to start a new tag and the & character to start an entity. To secure this context, you must convert the five most dangerous characters into their HTML entities.
/**
* Basic HTML Entity Encoding for Element Context
*/
function encodeHTML(str) {
return str.replace(/[&<>"']/g, function(m) {
return {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": '''
}[m];
});
}
// Result: "<script>" becomes "<script>"
When the browser encounters <script>, it displays the literal characters on the screen but does not trigger the HTML parser to start a new script execution. However, this level of encoding is insufficient for HTML Attributes. If data is placed inside an attribute like <input value="UNTRUSTED_DATA">, an attacker could use a double quote to close the value attribute and start an onfocus attribute. In attribute contexts, it is safest to encode all non-alphanumeric characters or ensure that the attribute is always wrapped in quotes and strictly encoded.
b. JavaScript and URL Contexts: Beyond HTML Entities
When data is placed inside a <script> block, HTML entity encoding like < is effectively useless because the JavaScript engine does not decode HTML entities before executing. If you have const name = "<script>";, the name is just a string containing those entities. However, if the attacker can break out of the string quotes, they can execute code.
// DANGEROUS: Putting HTML-encoded data in a script block
// Input: ' + alert(1) + '
const username = '" + alert(1) + "';
// The JS engine sees this as a string, but the HTML-encoding
// doesn't stop the syntax from being valid JS if it's rendered unquoted.
To secure the JavaScript Context, data should be serialized using JSON.stringify() or by hexadecimal/unicode escaping all non-alphanumeric characters. This ensures the data remains a valid, quoted string that cannot “break out.”
The URL Context (e.g., <a href="/search?q=UNTRUSTED_DATA">) requires percent-encoding (URL encoding). This involves converting characters into their %HH hex representation. Crucially, for attributes that accept URIs (like href, src, or action), the application must also validate the protocol. If the string starts with javascript:, data:, or vbscript:, it must be rejected or stripped, regardless of how well the characters are encoded.
c. HTML Sanitization with DOMPurify
Sanitization is required when you cannot simply encode everything because you need to support formatted HTML. The industry standard for client-side sanitization is DOMPurify. Unlike simple regex-based filters (which are notoriously easy to bypass), DOMPurify uses the browser’s own DOM implementation to create an inert document fragment, crawls the nodes, and removes anything not on a strict whitelist of tags and attributes.
import DOMPurify from 'dompurify';
// Untrusted HTML from a CMS or user
const dirtyHTML = '<img src=x onerror=alert(1)><b>Clean</b>';
// Sanitize the HTML
const cleanHTML = DOMPurify.sanitize(dirtyHTML, {
ALLOWED_TAGS: ['b', 'i', 'em', 'strong', 'a'],
ALLOWED_ATTR: ['href']
});
// Result: '<b>Clean</b>' (The <img> with onerror is completely removed)
DOMPurify is “Context-Aware” in the sense that it understands which attributes are valid for which tags. It also prevents “DOM Clobbering” attacks, where an attacker uses id or name attributes to overwrite global JavaScript variables. When using modern frameworks like React, DOMPurify should be used immediately before passing data to a “dangerously” named function. This creates a multi-layered defense: the framework protects 99% of the app, and DOMPurify protects the 1% where raw HTML is required.
Complete Example Session
// ============================================
// PART 1: THE VULNERABLE INPUT
// ============================================
const userInput = "'+alert('XSS')+'";
// ============================================
// PART 2: HTML CONTEXT (FAIL)
// ============================================
// If we just put it in a div: <div>'+alert('XSS')+'</div>
// This is actually safe in a div, but what if it goes in an attribute?
// ============================================
// PART 3: ATTRIBUTE CONTEXT (FAIL)
// ============================================
// <input onmouseover='console.log("... ${userInput} ...")'>
// Attacker breaks out with the single quote.
// ============================================
// PART 4: SECURE ENCODING FUNCTION
// ============================================
const escapeHTML = (str) => str.replace(/[&<>"']/g, tag => ({
'&': '&', '<': '<', '>': '>', '"': '"', "'": '''
}[tag]));
// ============================================
// PART 5: THE DANGEROUS FRAMEWORK ESCAPE
// ============================================
// In React: <div dangerouslySetInnerHTML={{ __html: userInput }} />
// This is a direct XSS vector.
// ============================================
// PART 6: IMPLEMENTING DOMPURIFY
// ============================================
import DOMPurify from 'dompurify';
const secureHTML = DOMPurify.sanitize(userInput); // Removes scripts/event handlers
// ============================================
// PART 7: URL PROTOCOL VALIDATION
// ============================================
const validateURL = (url) => {
const parsed = new URL(url, window.location.origin);
return ['http:', 'https:', 'mailto:'].includes(parsed.protocol) ? url : 'about:blank';
};
// ============================================
// PART 8: JAVASCRIPT CONTEXT SECURING
// ============================================
// Safe way to pass data to JS context from server/attribute
const safeJSData = JSON.stringify(userInput).replace(/</g, '\\u003c');
// ============================================
// PART 9: MULTI-CONTEXT RENDERING
// ============================================
const renderUserCard = (user) => {
return `
<div>${escapeHTML(user.name)}</div>
<a href="${validateURL(user.website)}">Website</a>
<div class="bio">${DOMPurify.sanitize(user.bio)}</div>
`;
};
// ============================================
// PART 10: RESULT
// ============================================
// The code now handles HTML encoding, URL validation, and HTML sanitization.
The session above demonstrates the application of specific security strategies for three different contexts: simple text (HTML encoding), links (URL validation), and rich text (DOMPurify sanitization).
Quick Reference
Context-Specific Encoding Rules
| Context | Target Sink | Strategy |
|---|---|---|
| HTML Body | <div>...</div> | HTML Entity Encode (<, >, &, ", ') |
| HTML Attribute | <input value="..."> | Aggressive Entity Encode (all non-alphanumeric) |
| JavaScript | const x = "..."; | Unicode Escape (\uXXXX) or JSON.stringify |
| URL/URI | <a href="..."> | Protocol Whitelist + URL Percent Encode |
| CSS | <div style="..."> | CSS Hex Escape (\HH) |
DOMPurify Configuration Options
| Option | Description | Recommended Setting |
|---|---|---|
ALLOWED_TAGS | List of safe HTML tags | ['b', 'i', 'em', 'strong', 'p', 'br'] |
ALLOWED_ATTR | List of safe attributes | ['href', 'title', 'target'] |
FORBID_TAGS | Explicitly block tags | ['script', 'style', 'iframe', 'object'] |
USE_PROFILES | Presets for SVG/MathML | { html: true } |
RETURN_DOM | Returns a node instead of string | false (usually) |
Best Practices
✅ Do This:
// Use textContent for inserting plain text
element.textContent = untrustedString; // ✅
// Always sanitize when using dangerouslySetInnerHTML
const clean = DOMPurify.sanitize(dirty); // ✅
<div dangerouslySetInnerHTML={{ __html: clean }} />; // ✅
// Whitelist protocols for href attributes
if (url.startsWith('https://')) { link.href = url; } // ✅
// Use JSON.stringify for JS context data
const data = JSON.stringify(serverData); // ✅
❌ Don’t Do This:
// Use innerHTML with untrusted data
element.innerHTML = "Hello " + user; // ❌
// Use a simple .replace(/<script>/g, "") filter
// (Attackers use <sCrIpT> or <img onerror=...>) // ❌
// Trust data from "Internal" APIs without sanitizing
// (Internal services can be compromised too) // ❌
// Put HTML entities in a JS script block
const name = "<script>"; // ❌
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Double Sanitization | Sanitizing on both server and client | Only sanitize once at the point of output |
| Attribute Breakout | Forgetting to encode quotes in attributes | Use encodeHTML for all attribute values |
| Template Literal XSS | Using backticks to build HTML strings | Sanitize/Encode components before interpolating |
| DOM Clobbering | Using user-provided IDs in the DOM | Use DOMPurify to strip id and name attributes |
javascript: URI | Encoding < but allowing the protocol | Implement a strict protocol whitelist |
| Framework Escapes | Using v-html or [innerHTML] without cleaning | Treat these as high-risk sinks and use DOMPurify |
Real-World Examples
1. Basic Text Content
// Encodes for safe display in a span
span.textContent = "<b>User</b>"; // Displays: <b>User</b>
2. Sanitized Rich Text
// Allows bold but removes script
const html = DOMPurify.sanitize("<b>Hi</b><script>alert(1)</script>");
3. Secure Link Protocol
// Prevents javascript: protocol injection
const safeUrl = url.startsWith('http') ? url : '#';
4. Serializing JS State
// Safely passing server data to a global JS variable
window.__INITIAL_STATE__ = JSON.parse('{"name": "Alice"}');
5. Encoding for Attribute
// Prevents breaking out of the value attribute
const attr = `value="${escapeHTML(userInput)}"`;
6. Disabling DOM Clobbering
// DOMPurify strips 'id' to prevent clobbering globals
DOMPurify.sanitize('<img id="location">', { SANITIZE_NAMED_PROPS: true });
7. CSS Context Encoding
// Prevents expression() or url() injection in styles
const safeColor = /^[a-zA-Z0-9#]+$/.test(color) ? color : 'black';
8. React dangerouslySetInnerHTML
<div dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(userBio) }} />
9. URI Component Encoding
// Encodes special characters for a query string
const search = encodeURIComponent("O'Reilly & Associates");
10. Stripping Event Handlers
// DOMPurify automatically removes on* attributes
const output = DOMPurify.sanitize('<div onclick="alert(1)">Click</div>');
Visual
The Browser Parsing Contexts
┌─────────────────────────────────────────────────────────────┐
│ HTML PAGE │
│ │
│ <div id="HTML_ATTR_CONTEXT"> │
│ HTML_BODY_CONTEXT │
│ <script> │
│ const x = "JS_STRING_CONTEXT"; │
│ </script> │
│ <a href="URL_CONTEXT">Click</a> │
│ </div> │
│ │
└─────────────────────────────────────────────────────────────┘
Each context requires a different encoding strategy.
DOMPurify Sanitization Pipeline
┌──────────────┐ ┌──────────────┐ ┌──────────────┐
│ UNTRUSTED │ │ INERT │ │ TREE │
│ HTML STRING │─────▶│ DOCUMENT │─────▶│ WALKER │
└──────────────┘ │ FRAGMENT │ └──────┬───────┘
└──────────────┘ │
▼
┌──────────────┐ ┌──────────────┐ ┌──────────────┐
│ FINAL SAFE │ │ RE-SERIALIZE │ │ STRIP │
│ HTML STRING │◀─────│ TO STRING │◀─────│ BLACKLIST │
└──────────────┘ └──────────────┘ └──────────────┘
Encoding vs Sanitization
┌───────────────────┐ ┌───────────────────┐
│ ENCODING │ │ SANITIZATION │
├───────────────────┤ ├───────────────────┤
│ Transforms all │ │ Filters parts of │
│ special chars. │ │ the input. │
│ │ │ │
│ Output is TEXT. │ │ Output is HTML. │
└───────────────────┘ └───────────────────┘
Summary
| Item | Value |
|---|---|
| Goal | Prevent XSS by treating data as data, not code |
| Encoding | Transforming characters into safe equivalents |
| Sanitization | Stripping dangerous elements from HTML |
| Standard Library | DOMPurify (for sanitization) |
| HTML Context | Escape <, >, &, ", ' |
| JS Context | Use JSON.stringify or Unicode escape |
| URL Context | Protocol Whitelist + Percent Encoding |
| Default Rule | Encode/Sanitize at the point of rendering |
Key takeaways:
- Always encode for the correct context. HTML encoding is for tag bodies; attribute encoding is for attributes; URL encoding is for links; JS encoding is for script blocks.
- Frameworks are not magic. While React and Vue encode by default, any use of
dangerouslySetInnerHTMLorv-htmlintroduces an immediate XSS risk. - Sanitize raw HTML with DOMPurify. Never attempt to use regular expressions to clean HTML. Use a library that parses the DOM like a real browser.
- Whitelist, don’t blacklist. Define the small set of tags and protocols you allow, rather than trying to block every possible malicious tag.
- Validate protocols for URLs. A link is not safe just because the characters are encoded; you must ensure it doesn’t use the
javascript:protocol. - Defense in depth. Use a Content Security Policy (CSP) alongside encoding and sanitization to stop scripts even if a vulnerability is missed.
Remember: Context-aware security is the difference between a secure application and a compromised one. By recognizing that the browser interprets data differently depending on where it resides in the DOM, you can apply the exact countermeasure needed to keep your users’ data safe.
Stop using slow, ad-bloated tool sites! 🤮
🔎 Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)
⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free
🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!