XSS & Output Escaping
Cross-site scripting (XSS) is injection into a web page. If an application inserts untrusted text into HTML without escaping it, a visitor's browser may treat that text as markup or script and run it with the site's privileges: it can read the page, act as the logged-in user, and send data elsewhere. XSS is the browser-side cousin of SQL injection, and the fix follows the same idea: keep data from being interpreted as code.
Three kinds of XSS
| Type | Where the untrusted data comes from | Example |
|---|---|---|
| Reflected | The current request (URL, form field) is echoed back | A search page that prints "Results for: …" |
| Stored | Saved data is shown to other users later | A comment or profile name |
| DOM-based | Client-side JavaScript copies data into the page | element.innerHTML = location.hash |
Stored XSS is usually the most serious, because every visitor who views the content is affected.
Escaping for HTML
The core defence is output encoding: before inserting text into HTML, convert the characters that have special meaning (<, >, &, ", ') into entities. The browser then displays them as text instead of parsing them as markup. Python has html.escape:
import html
comments = [
"Great product, fast delivery!",
"Use <b>bold</b> for emphasis & fun",
'He said "5 stars" and it\'s true',
"<img src=x onerror=alert(1)>",
]
for text in comments:
print(f"<p>{html.escape(text)}</p>")<p>Great product, fast delivery!</p>
<p>Use <b>bold</b> for emphasis & fun</p>
<p>He said "5 stars" and it's true</p>
<p><img src=x onerror=alert(1)></p>
The last comment is a typical test string: if it were inserted raw, the broken image's onerror handler would run JavaScript. Escaped, it is just visible text. (Security testers use harmless payloads like alert(1) only to prove a page is vulnerable on systems they are authorised to test.)
Context matters
Escaping must match where the data goes. HTML-body escaping is not enough everywhere:
| Context | Example | Correct handling |
|---|---|---|
| HTML text | <p>USER</p> |
HTML-escape |
| Quoted attribute | <input value="USER"> |
HTML-escape including quotes (always quote attributes) |
URL in href/src |
<a href="USER"> |
Allow only http:/https: schemes, then escape |
Inside <script> |
var name = USER; |
Serialise as JSON and escape <; better: put data in a data- attribute |
| CSS | style="color: USER" |
Avoid; allow-list values |
A URL attribute is a classic trap: html.escape leaves javascript:alert(1) unchanged because it contains no special characters, yet clicking such a link runs code. URLs need a scheme allow-list:
import html
from urllib.parse import urlsplit
def safe_link(url, label):
scheme = urlsplit(url.strip()).scheme.lower()
if scheme not in ("http", "https", ""):
url = "#" # refuse javascript:, data:, vbscript: ...
return f'<a href="{html.escape(url, quote=True)}">{html.escape(label)}</a>'
print(safe_link("https://example.com/docs?a=1&b=2", "Docs"))
print(safe_link("/profile/42", "My profile"))
print(safe_link("javascript:alert(1)", "Click me"))
print(safe_link(' JavaScript:alert(1)', "Sneaky"))
print(safe_link('https://x.test/" onmouseover="alert(1)', "Quote trick"))<a href="https://example.com/docs?a=1&b=2">Docs</a>
<a href="/profile/42">My profile</a>
<a href="#">Click me</a>
<a href="#">Sneaky</a>
<a href="https://x.test/" onmouseover="alert(1)">Quote trick</a>
The quote trick tries to break out of the href attribute; escaping turns the quote into " so it stays inside the value.
Auto-escaping templates
Escaping by hand in every place is error-prone. Modern template engines (Jinja2, Django templates, React JSX, Vue, Angular) escape by default, and you must opt out explicitly (|safe, dangerouslySetInnerHTML, v-html). Here is the idea in miniature:
import html
import string
class Markup(str):
"""Marks a string as already-safe HTML (like Jinja2's Markup)."""
class AutoEscapeTemplate(string.Template):
def render(self, **values):
escaped = {k: v if isinstance(v, Markup) else html.escape(str(v))
for k, v in values.items()}
return self.substitute(escaped)
page = AutoEscapeTemplate("<h1>Hello, $name</h1><div>$bio</div><footer>$footer</footer>")
print(page.render(
name="<script>steal()</script>",
bio="I like <cats> & dogs",
footer=Markup("<small>© TAD Shop</small>"), # trusted, written by us
))<h1>Hello, <script>steal()</script></h1><div>I like <cats> & dogs</div><footer><small>© TAD Shop</small></footer>
Everything is escaped unless the developer deliberately marks it as safe. When you need user-supplied rich text (a blog editor), don't hand-write filters: use a maintained HTML sanitiser (e.g. DOMPurify in the browser, nh3/bleach in Python) with an allow-list of tags and attributes.
DOM XSS and safe JavaScript APIs
In client-side code, the dangerous sinks are the ones that parse HTML: innerHTML, outerHTML, insertAdjacentHTML, document.write, and eval-like functions. Use their text-only equivalents:
// Dangerous: parses the string as HTML
results.innerHTML = "Results for " + query;
// Safe: always treated as text
results.textContent = "Results for " + query;Content Security Policy
A Content Security Policy (CSP) header is a second layer: it tells the browser which scripts may run at all. A strict policy blocks inline scripts and event-handler attributes, so even if an injection slips through, the injected code doesn't execute.
Content-Security-Policy: default-src 'self'; script-src 'self' 'nonce-r4nd0m'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'Scripts must then come from your own origin or carry the per-response random nonce. Also set session cookies HttpOnly, so injected script cannot read them directly.
Go further: Reflected and Stored XSS follows a payload from the server to the browser, and XSS Defences adds sanitisation, CSP and Trusted Types.
Test yourself
A comment containing a script is saved and shown to every visitor. Which type of XSS is this?
- Reflected
- Stored
- DOM-based
- CSRF
Why is html.escape alone not enough for a user-supplied link in href?
- It doesn't escape
< - A
javascript:URL contains no special characters, so it passes through unchanged - href can't contain text
- It escapes too much
Which JavaScript property safely inserts user text into an element?
- innerHTML
- outerHTML
- textContent
- document.write