Course contentsShow
← Web Development
Lesson 2897 of 2,98252. Frontend SecurityFree lesson

HTML Context Encoding

Properly escaping special characters when inserting untrusted data into HTML content.

HTML Context Encoding

You'll learn how to safely insert untrusted data into HTML content by escaping special characters that could trigger XSS attacks.

When you insert user-provided data directly into HTML, special characters like <, >, &, ", and ' can break out of the intended context and execute malicious code. HTML context encoding transforms these dangerous characters into their harmless HTML entity equivalents.

Why This Matters

Imagine you're displaying a user's name on a page. If the name is Alice, everything works fine. But what if a malicious user enters <script>alert('XSS')</script> as their name? Without encoding, the browser interprets this as actual HTML and executes the script.

The Core Encoding Rules

When inserting untrusted data into HTML content (between tags like <div>user data here</div>), encode these characters:

  • < becomes &lt;
  • > becomes &gt;
  • & becomes &amp;
  • " becomes &quot;
  • ' becomes &#x27;

Example

// DANGEROUS - No encoding
element.innerHTML = userInput; // ❌

// SAFE - With HTML context encoding
function encodeHTML(str) {
  return str
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#x27;');
}

element.textContent = userInput; // ✅ Browser auto-encodes
// OR
element.innerHTML = encodeHTML(userInput); // ✅ Manual encoding

Context Matters

This encoding is specifically for HTML content contexts. Different contexts (attributes, JavaScript, CSS, URLs) require different encoding strategies—HTML entity encoding alone won't protect you everywhere.

Key Takeaway: Always HTML-encode untrusted data before inserting it into HTML content by converting special characters to HTML entities, preventing browsers from interpreting malicious markup as executable code.