Skip to content
FrontDepth, Home

Security

Cross-site scripting (XSS)

How attacker-controlled text ends up running as code in your page — reflected, stored and DOM-based XSS, dangerous sinks, context-aware encoding, framework escape hatches, sanitising, strict CSP, Trusted Types and cookies as defence in depth.

JuniorMiddleSeniorUpdated 16 November 2026

Reading level

Shows sections up to the selected level.

Before you start

No prerequisites.

This topic starts at Junior level.

JuniorConcept

What XSS is and what an attacker can do

Cross-site scripting (XSS) happens when a site takes input an attacker can control and puts it into a page in a way that the browser runs it as code. The attacker's script then runs in your origin, as if you had written it. The same-origin policy no longer protects anything, because the code is already inside.

JavaScript
const params = new URLSearchParams(location.search);
document.querySelector("#greeting").innerHTML = "Hello, " + params.get("name");

With ?name=Ada this greets Ada. With ?name=<img src=x onerror="steal()"> the browser parses the value as HTML, the image fails to load, and the onerror handler runs. A link with that URL is all an attacker needs.

What the attacker's code can do

Everything your own JavaScript can do on that page, with the user's session:

  • Act as the user. Send same-origin requests with the user's cookies attached: change the delivery address or email, place an order, post content.
  • Read the page. Personal data, messages, CSRF tokens rendered into the HTML, anything in the DOM.
  • Read storage. Tokens in localStorage or sessionStorage can be sent to the attacker and reused from anywhere.
  • Change the page. Show a fake login form on your real domain, record keystrokes in forms.

What it usually cannot do is read an HttpOnly cookie: document.cookie does not expose it. That limits stealing the session for later, but it does not stop the attack — the script does not need the cookie to send requests as the user while the page is open.

Why it matters

XSS turns a display bug into account takeover. It is still one of the most common vulnerabilities in web apps, and it is a frontend problem as much as a backend one: many XSS bugs never touch the server's templates and live entirely in client-side code.

Key points

  • XSS = attacker-controlled data interpreted as code (HTML, JavaScript, URLs) in your page.
  • The impact is "the attacker is the user on your site", not just "an alert() pops up".
  • The defence is to keep data as data: encode or sanitise for the exact context, and add browser-enforced layers (CSP, Trusted Types) for the mistakes that slip through.
JuniorConcept

Reflected, stored and DOM-based XSS

XSS is usually grouped by where the malicious input comes from and where it is turned into code.

Reflected XSS

The server takes input from the request and puts it straight into the response:

JavaScript
app.get("/search", (req, res) => {
  res.send(`<h1>Results for ${req.query.q}</h1>`);
});

The payload lives in the URL. The attacker has to get the victim to open a crafted link (an email, a chat message, a redirect), and it hits only the people who open it.

Stored XSS

The payload is saved — a review, a comment, a profile name, a support ticket — and rendered later for everyone who views it. No crafted link is needed, it can hit every visitor, and it can reach admins who look at user content in a back office. MDN calls it particularly severe for that reason.

A typical case: comments rendered with innerHTML so that users can use a little formatting. One comment containing <img src=x onerror=…> then runs in the page of everyone who opens the thread.

DOM-based XSS

The whole flow happens in the browser: client-side code reads a source an attacker can influence and writes it into a sink that interprets it.

JavaScript
const tab = decodeURIComponent(location.hash.slice(1));
document.querySelector("#title").innerHTML = tab;

Typical sources: location.search, location.hash, document.referrer, window.name, postMessage data, and data from your own API that a user wrote. The URL fragment after # is never sent to the server, so server-side filters and logs never see such a payload. Client-side code review and browser-enforced controls (Trusted Types) are what catch it.

The categories overlap

A stored value can be rendered by client-side code into innerHTML (stored and DOM-based). The labels help you search for the bug; the fix is the same everywhere: find where untrusted data meets an interpreter, and make sure it arrives there as data.

Questions to ask in a code review

  • Where can this value come from? Who can write it, now or in a year?
  • Where does it end up — text, an attribute, a URL, a script?
  • Is that place encoded or sanitised for exactly that context?
MiddleWeb platform

Dangerous sinks: where strings become code

A sink is an API that interprets a string as HTML, JavaScript or a URL to load or navigate to. Most XSS bugs are a sink fed with untrusted data. Learn to spot them in code review.

HTML sinks

element.innerHTML, outerHTML, insertAdjacentHTML(), document.write(), Range.createContextualFragment(), and wrappers around them (jQuery's .html(), React's dangerouslySetInnerHTML, Vue's v-html).

A common false sense of safety: <script> elements inserted with innerHTML do not run. Many other things do:

JavaScript
el.innerHTML = "<script>steal()</script>";
el.innerHTML = '<img src=x onerror="steal()">';
el.innerHTML = "<details open ontoggle=steal()>";

The first line does nothing; the second and third run steal() as soon as the image fails or the element opens. document.write() is worse: scripts it writes are executed.

JavaScript sinks

eval(), new Function(string), and setTimeout / setInterval called with a string instead of a function. Any of them turns data into code directly:

JavaScript
setTimeout("showToast('" + message + "')", 1000);
setTimeout(() => showToast(message), 1000);

The first line is a sink; the second passes a function and is safe whatever message contains.

URL sinks

A javascript: URL runs its code when the browser navigates to it: <a href>, <form action>, <iframe src>, location.href = …, window.open(…). A "link to the user's website" field is a sink if the value is not checked:

JavaScript
link.href = profile.website;

Escaping does not help here (javascript: contains nothing to escape); the scheme must be allow-listed.

Attribute and handler sinks

Inline event handler attributes (onclick, onerror, onload, …) are JavaScript. el.setAttribute("onclick", value) or building <div onclick="…${value}…"> puts data into a script. So does src on <script> or <iframe>, and srcdoc on an iframe.

Safe counterparts

  • textContent, innerText, createTextNode() and an input's value — always text, never parsed.
  • addEventListener() with a function instead of handler attributes.
  • setAttribute() for harmless attributes (title, alt, data-*), and URL attributes only after a scheme check.
  • JSON.parse() instead of eval() for data.

The has a safe API for nearly every unsafe one; "find the sink, replace it with the text API" fixes most DOM-based XSS.

MiddleConcept

Context-aware output encoding

Output encoding turns characters that have a meaning in the target language into a form that the parser reads as plain text. There is no single "escape" function: what is dangerous depends on the context the value lands in, so you encode for that context at the moment of output.

HTML text and quoted attributes

Between tags and inside quoted attribute values, encode these five characters (OWASP's list):

JavaScript
function escapeHtml(text) {
  return text
    .replaceAll("&", "&amp;")
    .replaceAll("<", "&lt;")
    .replaceAll(">", "&gt;")
    .replaceAll('"', "&quot;")
    .replaceAll("'", "&#x27;");
}

& goes first, or the & of every entity you just produced is encoded again. Always quote attributes. In an unquoted attribute a space is enough to start a new attribute, and escapeHtml does not touch spaces:

HTML
<p title="x&quot; onmouseover=&quot;steal()">
<p title=x onmouseover=steal()>

The first is one harmless title. The second is a title plus an event handler.

URLs

HTML-encoding a URL does not make it safe: javascript:steal() contains no character to encode. For a whole URL, validate the scheme against an allow-list (http:, https:, maybe mailto:). For a value inside a URL, encode just that part:

JavaScript
const href = `/search?q=${encodeURIComponent(query)}`;

JavaScript and CSS

Don't build script or style source from untrusted data; OWASP calls these contexts where encoding alone does not reliably help. A classic server-rendering bug is injecting state into an inline script:

HTML
<script>window.__STATE__ = ${JSON.stringify(state)}</script>

JSON.stringify produces valid JavaScript, but the HTML parser ends the script at the first </script> — even inside a JSON string. A review text containing </script><img src=x onerror=…> breaks out. Escape < as \u003c in the serialized JSON (or use a serializer that does), or put the data in a <script type="application/json"> element with the same escaping and read it with JSON.parse(el.textContent).

Rules

  • Encode at output, for the context of that output. Storing pre-escaped text leads to double escaping and to raw text in places nobody escaped.
  • Prefer APIs that need no encoding at all: textContent, a framework's text interpolation, URLSearchParams.
  • If a value must be HTML, encoding is the wrong tool: you need a sanitiser.
MiddleFramework

React and other frameworks: auto-escaping and escape hatches

Modern frameworks encode by default. In React, a string in JSX is always rendered as text, and attribute values are set as attributes, never parsed as markup:

JSX
function Review({ review }) {
  return (
    <article title={review.author}>
      <p>{review.text}</p>
    </article>
  );
}

If review.text is <img src=x onerror=…>, the user sees exactly those characters. Server rendering escapes too: renderToString outputs &lt;img src=x onerror=…&gt;. This default is why most React apps have far fewer XSS bugs than string-template apps. The bugs live in the escape hatches.

dangerouslySetInnerHTML

JSX
<div dangerouslySetInnerHTML={{ __html: html }} />

This sets innerHTML, with all the risks of that sink. react.dev: unless the markup comes from a completely trusted source, "it is trivial to introduce an XSS vulnerability this way". It accepts a sanitised string or a TrustedHTML object. Treat every occurrence as a security review item; the ESLint rule react/no-danger flags them.

URLs in href and src

React escapes the value, but escaping does not make a javascript: URL safe. React 19 blocks it: for href, src, action and formAction it replaces a javascript: URL with one that throws "React has blocked a javascript: URL as a security precaution." (checked in react-dom 19.3.0, on the client and in server rendering). It blocks only that scheme. OWASP notes that this does not replace application-level URL validation: allow-list http: and https: for user-supplied links.

Other escape hatches

  • Direct DOM access: ref.current.innerHTML = …, or a third-party widget fed user strings.
  • Spreading untrusted objects into props: <a {...userProvidedProps}> lets data choose href or even dangerouslySetInnerHTML.
  • Markdown and rich text rendered to HTML by a library, then inserted raw.
  • Serialized state in an inline <script> during SSR (see the previous section).
  • Other frameworks have the same shape: Vue's v-html, Svelte's {@html …}, Angular's bypassSecurityTrustHtml() and friends, which switch off Angular's built-in sanitising.

Example: a little formatting without HTML strings

A comment feature that supports **bold** and line breaks is often built by turning the text into an HTML string (**…** → <strong>, \n → <br>) and passing it to dangerouslySetInnerHTML. Everything else the user typed becomes markup too. The safe version keeps the feature without HTML strings: split the text, render the parts as React children and create <strong> and <br> as elements. When you only need a little formatting, build elements; reach for HTML plus a sanitiser only when users really author HTML.

MiddleExample

Sanitising HTML and URLs

Encoding is for text. When users really do author HTML (a rich-text editor, a CMS, email bodies), you need a sanitiser: it parses the HTML and keeps only an allow-list of harmless elements and attributes.

Use a maintained library, not a regex

JavaScript
import DOMPurify from "dompurify";

const clean = DOMPurify.sanitize(dirty, {
  ALLOWED_TAGS: ["p", "br", "strong", "em", "ul", "ol", "li", "a"],
  ALLOWED_ATTR: ["href"],
});
container.innerHTML = clean;

OWASP recommends DOMPurify. It removes event handler attributes and unsafe URLs such as javascript: in href, and it parses with the browser's own HTML parser, so what it checks is what the browser will build. A regex cannot do that: HTML has case-insensitive names, optional quotes, entities, nested and broken markup, and dozens of tags and attributes that run code. A filter that deletes <script>…</script> leaves <img onerror> untouched, and on <scr<script></script>ipt> it creates a script tag.

Rules that keep a sanitiser effective:

  • Sanitise right before inserting, and insert the result unchanged. OWASP: modifying content after sanitising can void it.
  • Keep the allow-list as small as the feature needs, and keep the library updated: sanitiser bypasses are found and fixed regularly.
  • On the server, a DOM implementation is needed (DOMPurify with jsdom, for example), or sanitise in the browser.

The HTML Sanitizer API (element.setHTML()) brings this into the platform. Per MDN's compatibility data it ships in Chrome 146 and Firefox 148 but not in Safari yet, so it is not a replacement for a library today.

Allow-list URL schemes with the URL API

JavaScript
const ALLOWED = new Set(["http:", "https:", "mailto:"]);

function safeHref(input) {
  try {
    const url = new URL(input, location.href);
    return ALLOWED.has(url.protocol) ? url.href : "about:blank";
  } catch {
    return "about:blank";
  }
}

Parse first, then check: the URL parser lowercases the scheme and removes the tabs, newlines and leading spaces that browsers also ignore, so Java\tScript:… is reported as javascript:. A string check like startsWith("javascript:") misses those variants, and a block-list misses schemes you did not think of (data:, vbscript:). Check allowed schemes, not forbidden ones.

Choosing the tool

DataTool
Plain textText APIs or framework interpolation; no sanitiser needed
A little formatting (bold, line breaks)Parse your own syntax and create elements
User-authored HTMLDOMPurify with a strict allow-list
User-supplied linksURL API plus a scheme allow-list
SeniorWeb platform

Content Security Policy: strict CSP and report-only

Content Security Policy is a response header that tells the browser which scripts (and other resources) the page may use. It does not fix an injection; it is a second layer that stops injected code from running when encoding was missed.

Strict CSP: nonces or hashes

MDN and web.dev recommend a strict policy, based on nonces or hashes rather than host lists:

Text
Content-Security-Policy:
  script-src 'nonce-R4nd0mPerResp0nse' 'strict-dynamic';
  object-src 'none';
  base-uri 'none';
HTML
<script nonce="R4nd0mPerResp0nse" src="/assets/index-5c71ab.js"></script>
  • The server generates a new, unpredictable nonce for every response and puts it on each script tag it renders. Injected markup cannot guess it, so an injected <script> does not run.
  • Static pages can list hashes of their inline scripts instead ('sha256-…').
  • 'strict-dynamic' passes the trust on: scripts that a nonced script loads (for example with document.createElement("script")) may run too, so bundlers and tag managers keep working. In browsers that support it, host lists, 'self' and 'unsafe-inline' in the same directive are ignored — which is why web.dev suggests adding https: 'unsafe-inline' only as a fallback for very old browsers.
  • A strict policy also blocks inline event handlers, javascript: URLs and eval(). Expect to refactor onclick="…" into addEventListener().

Why host allow-lists are weak

script-src 'self' https://cdn.example.com allows every script on those hosts. If an allowed host serves a JSONP endpoint or an old library that evaluates templates from the DOM, an attacker can use it to run code. Google's research behind strict CSP ("CSP Is Dead, Long Live CSP!", 2016) found that most allow-list policies could be bypassed.

Report-only first

Text
Content-Security-Policy-Report-Only: script-src 'nonce-…' 'strict-dynamic'; object-src 'none'; base-uri 'none'; report-to csp
Reporting-Endpoints: csp="https://shop.example/csp-reports"

The report-only header enforces nothing and reports every violation; it cannot be set in a <meta> element. report-uri is deprecated, but MDN suggests sending it alongside report-to until every browser supports report-to. Expect noise: browser extensions inject inline scripts too.

A report-only policy can describe an attack precisely — an inline event handler executing on a page, an image loaded from a host you never use — and still block none of it. Enforced, script-src would stop the handler and img-src the request that carries data out. Treat a new kind of report concentrated on one page as a signal to investigate, and treat report-only as a phase with an end date, not a destination.

The platform's review-xss incident lets you trace strange CSP reports in a running shop back to their source.

SeniorWeb platform

Trusted Types, cookies and defence in depth

Encoding and sanitising depend on every developer getting every sink right. Trusted Types and cookie attributes are browser-enforced layers for when someone does not.

Trusted Types

With this CSP directive, DOM XSS sinks stop accepting strings:

Text
Content-Security-Policy: require-trusted-types-for 'script'; trusted-types reviews

Passing a plain string to innerHTML, outerHTML, insertAdjacentHTML(), document.write(), a script's src and similar sinks now throws a TypeError (string eval() and new Function() throw an EvalError). Only objects created by a policy are accepted:

JavaScript
const policy = trustedTypes.createPolicy("reviews", {
  createHTML: (input) => DOMPurify.sanitize(input),
});

container.innerHTML = policy.createHTML(review.html);
container.innerHTML = review.html;

The first assignment works; the second throws. The trusted-types directive lists the policy names your code may create, so the risky code is concentrated in a few reviewed policies instead of every innerHTML in the codebase. The API sanitises nothing by itself: the policy does what you write in it. React passes a TrustedHTML given to dangerouslySetInnerHTML to the browser unchanged. A policy named default receives every plain string that reaches a sink; MDN recommends it only during migration. Roll out with Content-Security-Policy-Report-Only to collect violations first.

Support: Trusted Types is Baseline 2026, newly available since February 2026 (Chrome 83, Safari 26, Firefox 148, per MDN). Older browsers simply do not enforce it.

Cookies and tokens

  • HttpOnly hides a cookie from document.cookie, so an XSS payload cannot copy the session to use later. A token kept in localStorage is different: a payload can read it and send it to another host, for example in an image URL. With an HttpOnly session cookie that theft does not work.
  • SameSite limits when the browser sends a cookie on cross-site requests. It is a CSRF defence. Injected script runs on your own site, so its requests are same-site and carry the cookie anyway.
  • Secure keeps the cookie off plain HTTP.

None of them stops the script from acting as the user while the page is open: changing a delivery address needs only a same-origin request. Ask for re-authentication before sensitive changes (email, password, payout or delivery details).

When it happens anyway

Fix the rendering (the root cause), remove the stored payloads, revoke the sessions and tokens that could have been exposed, review the actions taken in that window, and add a test that renders the payload as text. Then enforce the CSP you were only reporting.

SeniorInterview tips

Interview tips

A 30-second answer. "XSS is when attacker-controlled data reaches a place where the browser interprets it as code — HTML, a script, a javascript: URL — so the attacker's script runs in our origin and can do anything the user can. I prevent it by keeping data as data: framework text rendering or context-specific encoding, a sanitiser like DOMPurify when HTML is really needed, a scheme allow-list for URLs. Then I add browser-enforced layers: a strict nonce-based CSP, Trusted Types, and HttpOnly session cookies."

Questions you are likely to get

  • Reflected vs stored vs DOM-based? Where the payload comes from (the request, the database, a client-side source) and where it becomes code (the server's HTML or a client-side sink). Give one example of each.
  • Is React safe from XSS? Text and attributes are escaped by default, and React 19 blocks javascript: URLs in href, src, action and formAction. The holes are dangerouslySetInnerHTML, direct DOM writes through refs, other URL schemes, spreading untrusted props and serialized SSR state.
  • Why doesn't <script> in innerHTML run — so is innerHTML safe? Scripts inserted that way don't run, but event handler attributes do (<img src=x onerror=…>).
  • Does HttpOnly stop XSS? No. It stops reading the cookie; the script can still send requests as the user.
  • How would you roll out CSP on an existing app? Strict nonce-based policy, Content-Security-Policy-Report-Only first with a reporting endpoint, remove inline handlers and eval, triage reports (extensions add noise), then enforce.

Mistakes that cost points

  • Treating XSS as "an alert() pops up". Talk about the impact: account changes, data theft, actions as the user.
  • One "escape" function for every context. HTML-escaping a URL or a script does not make it safe.
  • Regex sanitisers and block-lists (replace(/<script>/g, ""), !url.startsWith("javascript:")).
  • Calling CSP the fix. It is a second layer; the fix is at the sink.
  • Saying a WAF solves it. OWASP: WAFs cannot reliably prevent XSS and are not a substitute for encoding, safe DOM APIs and sanitising.

Senior signal

Walk through a stored-XSS incident end to end: how you would notice it (CSP reports concentrated on one page, an account change nobody made), how you would find the sink (search for HTML sinks fed with user content), a fix that keeps the feature, the response (remove payloads, revoke sessions, audit actions), and what prevents the next one (lint rules, enforced CSP, Trusted Types, sessions out of localStorage, XSS payloads in tests).

JuniorReview checklist

What to check when reviewing code for XSS

Use this list on code you did not write that puts data into a page: a teammate's pull request, a snippet from a library's issue tracker or an AI assistant's suggestion. One sink fed with untrusted data lets an attacker's script run in your origin as the user, and tests with normal input never reveal it.

  • Does any HTML sink (innerHTML, insertAdjacentHTML(), document.write(), dangerouslySetInnerHTML, v-html) receive a string a user or the URL controls? Text belongs in textContent or JSX interpolation. Test with <img src=x onerror=alert(1)>: a <script> payload proves nothing, because scripts inserted with innerHTML do not run.
  • If HTML must stay HTML, does DOMPurify with a small allow-list clean it right before insertion? A regex or block-list such as replace(/<script>/g, "") leaves <img onerror> untouched.
  • Are user-supplied URLs checked against an allow-list of schemes? href, src, location.href and window.open() run javascript: URLs, and escaping does not help. Look for new URL(input) plus a protocol check for http: or https:; startsWith("javascript:") misses "JaVa\tScript:…", and React 19 blocks only javascript:.
  • Is any string turned into code? Look for eval(), new Function(), setTimeout with a string and onclick attributes built from data. Pass functions, use addEventListener(), parse data with JSON.parse().
  • Are untrusted objects spread into props, as in <a {...data}>? The data can then choose href or even dangerouslySetInnerHTML.
  • In server rendering, is state written into an inline <script> escaped? JSON.stringify keeps </script> intact, and the HTML parser ends the script there. Escape < as \u003c, or use a serializer that does.
  • Are session tokens kept out of localStorage? An injected script can read and send them to another host; an HttpOnly cookie is hidden from document.cookie.

Check your understanding

  • Practice

    Predict-output and open interview questions with self-assessment.

    3 predict-output · 4 open

  • Quiz

    Multiple-choice questions with explanations and a score.

    6 questions

Hands-on work that uses this topic.