Cross-Site Scripting (XSS)
How attackers inject JavaScript into web pages — stored, reflected, and DOM-based XSS with real defences
Skills taught: websecurity.xss, websecurity.stored-xss, websecurity.reflected-xss, websecurity.dom-xss, websecurity.csp, websecurity.output-encoding
What is XSS?
Cross-Site Scripting (XSS) lets an attacker inject JavaScript into a web page that runs in other users' browsers. Once JavaScript is running in your page's context, the attacker has the same access as your own scripts: cookies, localStorage, DOM content, form values, and the ability to make requests to your API using the victim's session. XSS is consistently in the OWASP Top 10 and is the root cause of many high-profile data breaches.
Three types of XSS
STORED XSS (persistent, highest impact):
Payload stored in the database, served to all users who visit the page
Example: comment field stores <script>stealCookies()</script>
Victim: every user who views the comment
Fix: sanitize HTML on output, use textContent instead of innerHTML
REFLECTED XSS (non-persistent):
Payload in the URL, reflected back in the response
Example: /search?q=<script>alert(1)</script>
Victim: user who clicks a crafted URL (attacker sends via email/phishing)
Fix: encode output, validate input
DOM-BASED XSS (client-side only):
Payload never hits the server — attacker controls client-side data flows
Example: page reads location.hash and writes it to innerHTML
// Malicious URL: https://myapp.com/#<img src=x onerror=alert(1)>
Victim: user who visits the malicious URL
Fix: never write untrusted data to innerHTML/document.write/eval
BLIND XSS:
Payload fires in an admin panel or logging system, not the public page
Example: support ticket input field viewed by an admin
Victim: the admin user
Fix: treat all stored content as untrusted, regardless of the source
XSS in React (safer but not immune)
// SAFE — React escapes all expressions by default
function Comment({ text }: { text: string }) {
// If text = '<script>alert(1)</script>'
// React renders it as the literal string, not as HTML
return <p>{text}</p>;
// Rendered: <p><script>alert(1)</script></p>
}
// DANGEROUS — dangerouslySetInnerHTML bypasses React's escaping
function RichComment({ html }: { html: string }) {
// If html contains <script> or <img onerror=...>, it RUNS
return <div dangerouslySetInnerHTML={{ __html: html }} />;
// XSS is possible — only use with sanitized HTML
}
// SAFE usage of dangerouslySetInnerHTML — sanitize first
import DOMPurify from 'dompurify';
function SafeRichComment({ html }: { html: string }) {
const clean = DOMPurify.sanitize(html); // Strips dangerous tags/attrs
return <div dangerouslySetInnerHTML={{ __html: clean }} />;
}
// OTHER DANGEROUS PATTERNS IN REACT:
// href injection — if href comes from user input:
const url = userInput; // 'javascript:alert(1)' is a valid URL!
return <a href={url}>Click</a>; // XSS via javascript: protocol
// SAFE — validate URL scheme
const safeUrl = url.startsWith('http') ? url : '#';
return <a href={safeUrl}>Click</a>;
Output encoding — the primary defence
// When rendering HTML on the server (SSR, templates, email)
// EVERY user-provided value must be HTML-encoded before insertion
// VULNERABLE — template string with raw user data
const html = `<h1>Hello, ${req.query.name}!</h1>`;
// If name = '<script>alert(1)</script>'
// Rendered: <h1>Hello, <script>alert(1)</script>!</h1> ← XSS
// SAFE — HTML-encode the value
function htmlEncode(str: string): string {
return str
.replace(/&/g, '&') // Must be first!
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
const html = `<h1>Hello, ${htmlEncode(req.query.name)}!</h1>`;
// If name = '<script>alert(1)</script>'
// Rendered: <h1>Hello, <script>alert(1)</script>!</h1>
// Browser displays: Hello, <script>alert(1)</script>!
// No script runs.
// In practice, use a templating engine that auto-escapes:
// Handlebars: {{name}} ← auto-escaped
// {{{name}}} ← raw, not escaped (dangerous)
// EJS: <%= name %> ← auto-escaped
// <%- name %> ← raw, not escaped (dangerous)
Tip: DOMPurify is the standard library for sanitising HTML. If you allow users to input rich text (bold, links, images) and need to display it as HTML, use DOMPurify: const clean = DOMPurify.sanitize(dirty). It strips all dangerous tags (<script>, event handlers, javascript: URLs) while preserving safe formatting. It's maintained by the security community, used by millions of sites, and updated as new bypass techniques emerge. Don't write your own HTML sanitiser.
Frequently Asked Questions
I use React — am I safe from XSS?
Mostly, but not completely. React escapes JSX expressions by default, which prevents the most common XSS patterns. But React doesn't protect you from: dangerouslySetInnerHTML with unclean HTML, href/src attributes set to user-controlled values (javascript: URL injection), string concatenation in template literals used to build HTML, or server-side rendering with unencoded data. The principle is the same: never trust user input, encode output.