Cross-site scripting (XSS)
Trick a trusted site into serving your JavaScript, and it runs with the victim's session.
XSS injects attacker-controlled script into a page so it executes in the victim's browser with the site's origin and cookies. It comes in three flavors — stored, reflected, and DOM-based — but the outcome is the same: the script can read sessions, forge requests, and impersonate the user. Defenses stack: encode output, ship a Content-Security-Policy, mark cookies HttpOnly, and validate input.
Craft the payload
The attacker writes a snippet of JavaScript designed to run in someone else's browser — for example a script that reads document.cookie and sends it to an attacker-controlled URL. The goal is to get this string treated as code rather than as text by a trusted site.
Find an injection vector
The attacker looks for input the site reflects back into a page without neutralizing it. Stored XSS saves the payload on the server (a comment or profile field); reflected XSS puts it in a URL parameter the page echoes; DOM-based XSS abuses client-side JS that writes untrusted input into the DOM.
Serve it to the victim
The victim loads a page from the site they trust, and the tainted content is delivered as part of that page. Because it arrives from the legitimate origin, the browser has no reason to treat the embedded script as anything other than the site's own code.
Script executes in-origin
The browser parses the injected <script> and runs it with the full privileges of the trusted site: same origin, same cookies, same access to the DOM and any tokens the page can reach. The same-origin policy that normally isolates sites offers no protection, because the code is running as the site.
Steal the session
The script reads the victim's session cookie or auth token and exfiltrates it to the attacker's server, or silently fires authenticated requests — changing a password, posting content, moving money — all indistinguishable from the real user. One view of a poisoned page is enough.
Layered defenses
You stop XSS by never letting input become code: escape/encode all output for its context, ship a Content-Security-Policy to block inline and foreign scripts, mark session cookies HttpOnly so script can't read them, and validate input at the edge. No single control is enough; they overlap on purpose.
What XSS actually is
Cross-site scripting is an injection attack where an attacker gets their own JavaScript to run inside a page served by a site the victim trusts. The name is a little misleading — the interesting word is *scripting*, not *cross-site*. The essence is a confusion of code and data: the site meant to display some text (a username, a comment, a search term), but because that text wasn't neutralized, the browser interpreted part of it as executable script.
Why is that so dangerous? Because of the browser's trust model. A page's JavaScript runs with the authority of its origin — it can read that origin's cookies, its localStorage, its DOM, and it can make requests as the logged-in user. The same-origin policy is supposed to stop evil.com from touching bank.com's data. But XSS smuggles the attacker's code *into* bank.com's own pages, so it runs as bank.com with all of bank.com's privileges. The isolation boundary isn't broken; it's bypassed, because the malicious code is now on the trusted side of it.
The three types
XSS is usually classified by how the payload reaches the victim's browser.
- Stored (persistent) XSS — the attacker submits the payload and the server *saves* it: a forum comment, a product review, a profile bio, a support ticket. Every user who later views that content is served the script. This is the most dangerous variant because it's self-propagating and hits many victims without any further attacker action; a single poisoned comment can compromise everyone who reads the thread.
- Reflected XSS — the payload isn't stored; it's included in a request and immediately *reflected* back in the response. A classic case is a search page that echoes
You searched for: <term>— put script in the term and it runs. Because nothing is persisted, the attacker must deliver the payload per-victim, typically via a crafted link in a phishing email or a malicious ad. - DOM-based XSS — the vulnerability lives entirely in the client-side JavaScript and the server may never see the payload at all. Vulnerable code reads untrusted input (a URL fragment,
location.hash, a query parameter) and writes it into the page with something likeelement.innerHTML = input. The server returns a perfectly clean page; the browser's own script does the injecting.
All three end in the same place — attacker script executing in the victim's browser — but they demand different defenses and are found in different places, which is why the distinction matters.
What the injected script can do
Once the attacker's code is running in-origin, it inherits everything the page can do, and the consequences escalate fast.
The headline attack is session theft. If the site keeps its session ID or auth token somewhere script can reach — a non-HttpOnly cookie, localStorage — the payload reads it and sends it to an attacker-controlled server with a one-line fetch. The attacker then replays that session and *is* the victim, no password required.
But it doesn't stop at stealing credentials. The script can act as the user, from the user's browser, firing authenticated requests that are indistinguishable from legitimate ones: change the account email, add a new payment method, post spam, transfer funds, or silently create an attacker-controlled admin. It can rewrite the visible page to phish for passwords, log keystrokes, or pull in a larger exploit framework. Because everything happens inside a trusted session on a trusted origin, server-side logs often show nothing but ordinary user activity. That combination — full in-page power plus near-invisibility — is why XSS consistently ranks among the most serious web vulnerabilities.
Defenses, layer by layer
There is no single switch that fixes XSS; robust protection is a stack of controls, each catching what the others miss.
- Output encoding / escaping is the primary defense and it targets the root cause. Whenever untrusted data is placed into a page, encode it for that exact context so it is rendered as inert text, not parsed as markup or code —
<becomes<, and so on. Encoding is context-sensitive: HTML body, HTML attributes, JavaScript, and URLs each need different escaping, which is why using a framework's auto-escaping templates (and avoiding rawinnerHTML) is far safer than hand-rolling it. - Content-Security-Policy (CSP) is a defense-in-depth backstop. A CSP header tells the browser which script sources to trust and can forbid inline scripts entirely, so that even if a payload slips through, the browser refuses to execute it. It turns a would-be compromise into a blocked, reported event.
- HttpOnly cookies shrink the blast radius. Marking session cookies
HttpOnlyhides them fromdocument.cookie, so injected script can't read and exfiltrate them directly — an attacker may still make requests as the user, but can't walk away with the raw session token. - Input validation filters obviously bad input at the edge (reject or constrain what a field may contain), which reduces the attack surface but must never be relied on alone.
Putting it together in practice
The mental model that prevents XSS is simple to state and easy to forget under deadline pressure: treat every piece of data that originated outside your code as untrusted, and never let it cross the line from data into code. Attackers are creative about where "outside" input hides — it's not just form fields but URLs, headers, cookies, filenames, imported data, and content from other users — so the safe posture is to encode on the way *out*, at the moment data is written into a response, for the context it's being written into.
In a real application you combine the layers rather than betting on one. You lean on a modern framework's automatic, context-aware escaping and avoid the dangerous escape hatches (innerHTML, dangerouslySetInnerHTML, eval) unless you sanitize with a vetted library first. You ship a strict CSP so a missed spot fails safe. You set HttpOnly and Secure on session cookies so a breach doesn't immediately hand over the session. And you validate input where it enters. Any one of these can be bypassed; together they mean an attacker has to defeat several independent controls at once, which is exactly the depth XSS defense requires.
XSS makes the victim's browser run attacker script under the trusted site's origin.
Stored XSS persists the payload on the server (a comment, profile) and hits everyone who views it.
Reflected XSS bounces the payload straight back in the response, delivered via a crafted link.
DOM-based XSS never touches the server — vulnerable client-side JS writes untrusted input into the page.
The script can read document.cookie, tokens, and the DOM, then exfiltrate them or act as the user.
Defenses layer: output encoding, Content-Security-Policy, HttpOnly cookies, and input validation.
Quick quiz
What distinguishes DOM-based XSS from stored and reflected XSS?
Why does marking a session cookie HttpOnly help against XSS?
SQL injection
When user input becomes code, your database does the attacker's bidding.
Access control explained
First prove who you are, then the system decides what you're allowed to touch.
Top tips for API security
An API is a door into your data — these are the locks every one of them needs.
How HTTPS works
The TLS handshake that turns a plain TCP connection into a private, verified channel.