XSS Prevention: Escaping, Sanitising and CSP
Cross-site scripting runs attacker code in your users' browsers. Learn the three types and the defences that actually stop them.
By Velloreth
What XSS is
Cross-site scripting is when untrusted input is rendered as HTML or JavaScript in a browser. The attacker’s code runs in the context of your origin, which means it has the same access as your own code: it can read the page, make authenticated requests, and exfiltrate anything the page can reach.
The name is misleading. The attack is not about crossing sites; it is about getting code into your page.
The three types
Stored XSS is when the payload is saved on the server and served to every visitor. A comment, a profile bio, or a support ticket is the usual vector. It is the most dangerous because it needs no interaction beyond viewing the page.
Reflected XSS is when the payload is in the request and echoed in the response. A search term that is printed back, or an error message that includes the input, is the usual vector. It needs the victim to click a crafted link.
DOM-based XSS is when client-side JavaScript writes untrusted data into the page without a server round trip. Reading location.hash and assigning it to innerHTML is the classic case. The server never sees the payload, so a server-side filter does not help.
The primary defence: context-aware output encoding
The rule is that untrusted data must be encoded for the context where it is placed. The context determines the encoding, and using the wrong one leaves the vulnerability open.
In an HTML body, encode <, >, &, " and '.
function escapeHtml(s) {
return s.replace(/[&<>"']/g, (c) => ({
'&': '&', '<': '<', '>': '>', '"': '"', "'": ''',
}[c]));
}
In an HTML attribute, the same encoding applies, and the attribute value must be quoted.
<!-- Safe: quoted and encoded -->
<div title="<script>alert(1)</script>">...</div>
In a URL, encode with encodeURIComponent and validate the scheme.
const url = `/search?q=${encodeURIComponent(query)}`;
In a JavaScript string, use JSON.stringify rather than string concatenation.
// Safe
const data = JSON.parse(document.getElementById('data').textContent);
<script type="application/json" id="data">{"name":"<%= JSON.stringify(name) %>"}</script>
The practical rule: use a templating engine that escapes by default, and reach for a raw-output helper only when you have a reason and have checked the context.
Sanitising HTML
When the input is meant to contain markup, such as a rich-text comment, escaping is not an option because it would destroy the formatting. The input must be sanitised: parsed, and the dangerous parts removed.
Use a maintained library. DOMPurify is the standard choice in the browser, and a server-side equivalent exists for each language. Writing your own sanitiser with a regular expression is a well-known way to introduce a vulnerability, because HTML parsing is not regular.
import DOMPurify from 'dompurify';
const clean = DOMPurify.sanitize(userHtml, {
ALLOWED_TAGS: ['b', 'i', 'em', 'strong', 'a', 'p', 'ul', 'ol', 'li'],
ALLOWED_ATTR: ['href'],
});
Sanitise on output, not only on input. A payload that is stored safely can become dangerous when a different part of the application renders it. Sanitising at the point of rendering is the safer default.
The second layer: Content Security Policy
A CSP tells the browser which sources of script, style and other resources are allowed. An injected inline script is blocked unless it is explicitly permitted, which turns many payloads into a console error.
Content-Security-Policy:
default-src 'self';
script-src 'self' 'nonce-abc123';
object-src 'none';
base-uri 'self';
A nonce is the modern approach. The server generates a random value per response, includes it in the policy, and adds it to each legitimate script tag. An injected script does not have the nonce, so it is blocked.
unsafe-inline defeats much of the protection. A policy that allows inline script lets an injected <script> run. It is a common shortcut and it removes the main benefit.
A CSP is a second layer. It limits the damage when an encoding bug slips through; it does not replace encoding.
Other defences
HttpOnly cookies. A session cookie that a script cannot read cannot be stolen by an XSS payload. The script still runs, but the session is not exfiltrated.
SameSite cookies. A SameSite=Lax or Strict cookie is not sent on a cross-site request, which limits what an injected script can do with the session.
Trusted Types. A browser API that requires a value to be created by a policy before it can be assigned to innerHTML. It turns a DOM-based XSS into a runtime error, and it is enforced through the CSP.
Avoid innerHTML. Use textContent when the value is text, and createElement when it is markup. The dangerous sinks are innerHTML, outerHTML, insertAdjacentHTML, document.write, and eval.
Framework defaults. React, Vue and Angular escape by default. The vulnerability appears when a raw-HTML escape hatch is used, such as dangerouslySetInnerHTML in React or v-html in Vue. Treat those as a code-review flag.
Common mistakes
Encoding for the wrong context. HTML-escaping a value that is placed in a JavaScript string or a URL leaves the vulnerability open.
Using a regular expression to sanitise HTML. HTML is not regular, and a regex-based sanitiser is bypassable.
Relying on a blocklist. A filter that removes <script> misses <img onerror>, <svg onload>, and a dozen other vectors. Encode or sanitise; do not blocklist.
A CSP with unsafe-inline. The policy then allows the exact thing it was meant to stop.
Sanitising on input only. A value that is safe in one context can be dangerous in another, so sanitise at the point of rendering.
Trusting client-side validation. An attacker does not use your form. Validate and encode on the server.
A quotable summary
XSS is when untrusted input is rendered as HTML or JavaScript in a browser, in one of three forms: stored, reflected or DOM-based. The primary defence is context-aware output encoding, which must match the context where the value is placed. When the input is meant to contain markup, sanitise it with a maintained library such as DOMPurify rather than a regular expression. A Content Security Policy with a nonce is a strong second layer, and HttpOnly cookies limit the damage by keeping the session out of reach.
Related reading
For the input side, see input-validation-guide and for the policy details, content-security-policy-guide. For the broader context, csrf-explained and security-headers-guide.