Preventing XSS comes down to one principle: never trust user input, and always encode output for the specific context it lands in. Secondary defenses (CSP, HttpOnly) limit damage when the primary defense fails.
Output Encoding (Primary Defense)
Encode based on where the data is going to be inserted, not what it looks like. The same string needs different encoding depending on context.
HTML Body Context
User input inside normal HTML tags:
<p>Hello, INPUT</p>Encode:
<→<>→>&→&"→"'→'
Framework helpers:
- React —
{userInput}auto-escapes - Angular —
{{ userInput }}auto-escapes - Vue —
{{ userInput }}auto-escapes - PHP —
htmlspecialchars($input, ENT_QUOTES, 'UTF-8') - Python (Jinja) — auto-escapes by default
- Go —
html/templateauto-escapes contextually
HTML Attribute Context
Input inside an attribute value:
<input value="INPUT">Encode ", ', <, >, & as entities. Even safer: always quote the attribute and encode the quote character.
JavaScript Context
Input inside a <script> block:
var user = "INPUT";Encode: use \xHH or \uHHHH for all non-alphanumeric characters. Never trust JSON.stringify() to escape for HTML — it’s not HTML-safe.
Best practice: don’t put user input directly in <script> blocks. Store it in a data-* attribute and read it with JS:
<div id="user" data-name="SAFELY_ENCODED"></div>
<script>
var name = document.getElementById('user').dataset.name;
</script>URL / href Context
Input inside a href or src:
<a href="INPUT">Danger: javascript: URIs. Validate that the URL starts with http://, https://, /, or your allowlist — reject anything starting with javascript:, data:, or vbscript:.
CSS Context
Input inside a <style> block or style="..." attribute. Avoid entirely if possible. If unavoidable, reject anything containing expression, url(, @import, /*.
Content Security Policy (CSP)
A browser-enforced allowlist of script sources. Even if XSS bypasses output encoding, CSP can prevent the attacker’s payload from executing.
Minimum useful policy:
Content-Security-Policy: default-src 'self'; script-src 'self'; object-src 'none'; base-uri 'self'Breakdown:
default-src 'self'— only load resources from same originscript-src 'self'— only execute scripts from same origin (no inline, no eval)object-src 'none'— block Flash, Java, etc.base-uri 'self'— block<base>tag injection
Caveats:
- CSP is secondary defense — don’t skip encoding because you have CSP
'unsafe-inline'breaks most of CSP’s XSS protection — avoid'unsafe-eval'same problem- Nonce- or hash-based CSP (
script-src 'nonce-RANDOM') is strict but requires server-side templating support
Cookie Flags
Not XSS prevention per se, but limits the damage of a successful XSS:
Set-Cookie: sessionid=abc; HttpOnly; Secure; SameSite=Strict; Path=/HttpOnly— blocksdocument.cookieaccess from JavaScript. Stops cookie theft via XSS.Secure— cookie only sent over HTTPS. Stops passive network eavesdropping.SameSite=Strict— cookie never sent on cross-origin requests. Stops some CSRF and some cookie-replay patterns.
HttpOnly is the single most impactful XSS mitigation after output encoding.
Input Validation (Defense in Depth)
Not a substitute for output encoding, but useful as an extra layer:
- Reject input that fails a strict allowlist (e.g. usernames =
[a-zA-Z0-9_]) - Reject input containing obviously dangerous substrings (
<script,javascript:,onerror=) — understanding this is bypassable but raises the bar - Enforce reasonable length limits
Don’t rely on blacklist filtering — the bypass space is enormous. Use output encoding + CSP.
Safe DOM APIs
In client-side JavaScript, prefer safe APIs over the dangerous ones:
| Avoid | Use Instead |
|---|---|
innerHTML | textContent |
document.write() | DOM manipulation (createElement, appendChild) |
eval() / Function() | Specific parsing (JSON.parse) |
setTimeout('code', ...) | setTimeout(() => code, ...) |
jQuery .html() | .text() |
Framework-Level Guidance
- React — stay away from
dangerouslySetInnerHTML. When you must use it, sanitize with DOMPurify first. - Angular —
[innerHTML]goes through sanitization by default;bypassSecurityTrustHtmldisables it (don’t). - Vue —
v-htmlskips encoding; prefer{{ }}orv-text. - Server-side templating — ensure context-aware auto-escaping is on (default in Jinja, Go templates, Razor).
Checklist Summary
The whole prevention chain in order of impact:
- Context-aware output encoding on every piece of user input
Content-Security-Policyheader with nounsafe-inline/unsafe-evalHttpOnly,Secure,SameSiteon session cookies- Input validation as defense in depth
- Safe DOM APIs in client-side code
- Regular dependency audits (DOMPurify, sanitizer libraries stay updated)
Any single layer can fail. All five together cover almost every real-world XSS scenario.
