Cross-site scripting (XSS)
Stop attacker-controlled text from running as code in your users' browsers.
Learning objectives
- Distinguish reflected, stored and DOM-based XSS
- Choose safe DOM APIs and output encoding for each context
- Sanitise HTML only when you truly need to accept it
What XSS is
Cross-site scripting happens when an attacker gets their JavaScript to run in another user’s browser, inside your site’s origin. From there it can read the page, act as the user, and steal anything the page can reach.
There are three main kinds:
- Reflected: the payload comes in a request, such as a search query, and is echoed back in the response.
- Stored: the payload is saved (a comment, a profile name) and shown to every viewer.
- DOM-based: client-side JavaScript moves untrusted data, such as
location.hash, into a dangerous sink without involving the server.
Vulnerable and safe DOM sinks
// VULNERABLE: innerHTML parses the string as HTML, so <img onerror=...> runs
document.getElementById('greeting').innerHTML = location.hash.slice(1);
// SAFE: textContent treats the value as plain text
document.getElementById('greeting').textContent = location.hash.slice(1);
Other dangerous sinks include outerHTML, insertAdjacentHTML, document.write, eval, and setting href or src to untrusted URLs.
Encoding depends on context
The right escaping depends on where the data lands:
| Context | Example | Safe approach |
|---|---|---|
| HTML body | <p>{name}</p> |
HTML-encode <, >, &, ", ' |
| HTML attribute | <input value="{name}"> |
Encode, and always quote the attribute |
| JavaScript string | const n = "{name}" |
Avoid. Pass data as JSON in a separate element instead |
| URL | <a href="{url}"> |
Allow only https: or http:, so javascript: is blocked |
Modern frameworks encode by default. Astro, for example, escapes {expressions} in templates:
---
const name = Astro.url.searchParams.get('name') ?? 'guest';
---
<!-- Escaped automatically: safe -->
<p>Welcome, {name}</p>
<!-- Bypasses escaping: only use with trusted HTML -->
<div set:html={name} />
The set:html directive is the Astro equivalent of innerHTML. Treat every use of it as a security review item.
When you must accept HTML
Sometimes users really do need rich text. Sanitise it with a well-maintained library such as DOMPurify, and only at the point of rendering:
import DOMPurify from 'dompurify';
el.innerHTML = DOMPurify.sanitize(untrustedHtml);
Do not write your own regular-expression filter. They are reliably bypassed.
Defence in depth
- Content Security Policy. A strict CSP that blocks inline scripts stops many XSS payloads from running even when they are injected. See Security headers and CSP.
HttpOnlycookies. Session cookies that scripts cannot read limit what a successful XSS can steal. See HTTP, cookies and sessions.- Keep dependencies current. Old frameworks and sanitisers have known bypasses.
Lab: spot the sink
Review a small component you have written and list every place that writes data into the DOM or HTML. For each one, answer:
- Where did the data originate?
- Is it encoded for this context?
- Could it be replaced by a
textContentassignment or a template expression?
Key takeaways
- Use
textContent, framework templating and encoding by default. Reach for raw HTML only with a good reason. - Sanitise any HTML you accept from users, with a maintained library.
- Combine output encoding with a strict Content Security Policy.