Cross-site scripting (XSS): running code in other people's browsers
If your page renders user content as HTML, an attacker can make it run their JavaScript for every visitor, with that visitor's session. The types of XSS, why React mostly saves you, and where it doesn't.
In one sentence
XSS is injection into HTML instead of SQL. Escape output by default, never inject raw HTML, and add a Content Security Policy as the safety net.
The idea
A product review that contains <script> is harmless text, unless the page puts it into the DOM as HTML. Then the browser runs it as if you wrote it, with access to the page, the user's session and every API the page can call.
- Great headphones, battery lasts all week!
✓
Three flavours
| Type | Where the payload lives | Example |
|---|---|---|
| Stored | Saved in your database and shown to others | A comment, a username, a product review |
| Reflected | In the URL, echoed back in the response | /search?q=<script>…</script> sent in a phishing email |
| DOM-based | Never reaches the server; client JS puts it in the page | element.innerHTML = location.hash |
What attackers do with it: steal session tokens readable from JavaScript, perform actions as the user (change email, transfer money), show a fake login form on your real domain, or log keystrokes.
How to prevent it
- Escape by default. React, Vue, Svelte and templating engines escape
{value}for you. Keep it that way. - Avoid raw HTML sinks:
dangerouslySetInnerHTML,innerHTML,v-html,document.write. If you must render user HTML (rich text), sanitize it with a maintained library like DOMPurify. - Validate URLs:
<a href={userUrl}>withjavascript:is XSS even in React. Allow onlyhttps:andmailto:. - Content Security Policy: forbid inline scripts and unknown origins so injected code can't run even if it lands in the page.
- HttpOnly cookies: a successful XSS still can't read the session cookie.
Content-Security-Policy: default-src 'self'; script-src 'self' 'nonce-r4nd0m'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'Key takeaways
- 01XSS lets attackers run JavaScript in your users' browsers, as them.
- 02Escape output by default; framework escaping only fails when you bypass it.
- 03Sanitize rich HTML and validate URL schemes.
- 04CSP and HttpOnly cookies limit the damage when something slips through.
Check your understanding
1 of 3
What does XSS let an attacker do?
Related concepts
Sessions & cookies
A session cookie is as good as a password while it's valid. Ship it as HttpOnly; Secure; SameSite=Lax, keep it short-lived, and rotate it on login and privilege changes.
7 min read →CSRF
Cookies prove which browser sent a request, not which site asked for it. SameSite cookies and CSRF tokens tell your server the request really came from your own pages.
6 min read →SQL injection
If user input is concatenated into a query, a single quote turns data into SQL. Parameterized queries keep data and code apart, so the attacker's text is only ever text.
8 min read →