← Back to JavaScript, page 4

javascript-0080 · Medium mid

What is cross-site scripting (XSS), and how do you prevent it in front-end JavaScript?

XSS happens when untrusted text is treated as HTML or script in a page, letting an attacker run code in a victim's session. Prevent it by inserting text with textContent, escaping or sanitizing when HTML is unavoidable, validating URL schemes, avoiding dangerous sinks like innerHTML and eval, and adding a Content Security Policy as a second layer.

Full answer

An attacker who can place <script> or an event handler such as <img onerror=...> into your page can read cookies that are not HttpOnly, call APIs as the user, and change what the user sees. There are three kinds. Stored XSS saves the payload in a database and shows it to every visitor, reflected XSS puts it in a link that the server echoes back, and DOM-based XSS happens entirely in the browser when script writes untrusted data into a dangerous place.

The core defense is to treat user data as text unless there is a strong reason not to. element.textContent = value shows the characters literally, even if they look like HTML. Frameworks such as React escape interpolated values for the same reason, and the risky escape hatches (dangerouslySetInnerHTML, v-html) deserve review.

Dangerous sinks include innerHTML, outerHTML, insertAdjacentHTML, document.write, eval, new Function, setTimeout with a string, and setting href or src to untrusted URLs. A link such as javascript:alert(1) runs code, so URLs from users must be parsed and limited to http: and https:.

When user-provided HTML is a real requirement (a rich text editor), sanitize it with a well-maintained library such as DOMPurify or the browser's Sanitizer API where supported, not with a hand-written regular expression. Escaping must match the context: HTML text, an attribute, a URL, and a script each have different rules.

Defense in depth: set a Content Security Policy that blocks inline script and limits script sources, mark session cookies HttpOnly, and validate on the server too, since a client-side check can be bypassed.

javascript
const payload = '<img src="x" onerror="stealCookies()">';

const unsafe = document.createElement('div');
unsafe.innerHTML = payload;
const unsafeImage = unsafe.firstElementChild;
console.log('innerHTML created an element:', unsafeImage.tagName, 'with handler attribute:', unsafeImage.hasAttribute('onerror'));

const safe = document.createElement('div');
safe.textContent = payload;
console.log('textContent children:', safe.children.length, '| shown as text:', safe.textContent === payload);
console.log('serialized:', safe.innerHTML);

function escapeHtml(text) {
  return String(text)
    .replaceAll('&', '&amp;')
    .replaceAll('<', '&lt;')
    .replaceAll('>', '&gt;')
    .replaceAll('"', '&quot;')
    .replaceAll("'", '&#39;');
}
const escaped = escapeHtml(payload);
const viaTemplate = document.createElement('div');
viaTemplate.innerHTML = `<p title="${escapeHtml('" onmouseover="bad()')}">${escaped}</p>`;
console.log('escaped output has no img element:', viaTemplate.querySelector('img') === null);
console.log('attribute stayed one attribute:', viaTemplate.firstElementChild.attributes.length, viaTemplate.firstElementChild.hasAttribute('onmouseover'));

function safeUrl(input) {
  try {
    const url = new URL(input, 'https://example.com');
    return ['http:', 'https:'].includes(url.protocol) ? url.href : null;
  } catch {
    return null;
  }
}
for (const candidate of ['https://school.example/page', '/relative/path', 'javascript:alert(1)', 'JaVaScRiPt:alert(1)', 'data:text/html,<b>x</b>']) {
  console.log(candidate.padEnd(30), '->', safeUrl(candidate));
}

const link = document.createElement('a');
link.href = safeUrl('javascript:alert(1)') ?? '#';
link.textContent = 'profile';
console.log(link.outerHTML);

Written for a browser console or script tag; checked here with Node.js v24.22.1 and jsdom, two runs with identical output. Output: innerHTML created an element: IMG with handler attribute: true textContent children: 0 | shown as text: true serialized: &lt;img src="x" onerror="stealCookies()"&gt; escaped output has no img element: true attribute stayed one attribute: 1 false https://school.example/page -> https://school.example/page /relative/path -> https://example.com/relative/path javascript:alert(1) -> null JaVaScRiPt:alert(1) -> null data:text/html,<b>x</b> -> null <a href="#">profile</a>

Key points

  • XSS lets untrusted input run as script in a victim's session; kinds are stored, reflected, and DOM-based.
  • Prefer textContent and framework escaping over innerHTML.
  • Dangerous sinks: innerHTML, document.write, eval, string timers, and untrusted URLs.
  • Allow only http and https URLs from users.
  • Sanitize required HTML with a vetted library, and add CSP and HttpOnly cookies.

Common mistakes

  • Using innerHTML to insert user text because it is shorter.
  • Blocking only the word script, which misses event-handler attributes and javascript: URLs.
  • Writing a regular expression to sanitize HTML instead of using a vetted library.
  • Trusting client-side checks and skipping server-side validation and output escaping.

Follow-ups

  • How does a Content Security Policy reduce the impact of XSS?
  • What makes DOM-based XSS different from stored XSS?
  • How does React protect against XSS, and when does it not?

Tips

  • Name the three kinds and give one sentence on each.
  • Lead the fix with "treat data as text"; then mention sinks and CSP.
  • Include URL scheme validation; it is a frequent gap.