Programming
We provide developers and engineers the guides and tutorials they...
Search
We provide developers and engineers the guides and tutorials they...
Content is king. It's not just about how you're going to write, b...
Looking for an engaging connection with thousands of other people...
Cross-site scripting (XSS) explained: stored, reflected and DOM-based XSS, why output encoding matters, and defences like CSP and HttpOnly cookies.
Quick answer: Cross-site scripting (XSS) is a vulnerability in which a website includes untrusted content in a page without making it safe, so that the visitor's browser treats that content as code and runs it. Because the script runs as part of the trusted site, it can do anything the user can do there: read page content, act on the user's behalf, or capture what they type. The main defence is output encoding: converting special characters so that user-supplied text is displayed as text and never interpreted as HTML or JavaScript. Modern frameworks do this automatically, and a Content Security Policy adds a second layer.
A browser receives a page as one stream of HTML. It has no idea which parts the developer wrote and which parts came from a user's comment, a search term or a database field. If the stream contains a <script> element, the browser runs it.
Suppose a site displays comments by inserting them straight into the page:
<div >USER COMMENT GOES HERE</div>
If a comment contains HTML markup, and the site inserts it unchanged, that markup becomes part of the page. Markup that includes script will execute in the browser of everyone who views the comment.
The cause is the same as in SQL injection: data was mixed into code. There it was a database query; here it is a web page.
The browser's same-origin policy keeps one site's scripts away from another site's data. A script injected through XSS gets round it, because it runs as the vulnerable site. See how CORS works for the policy itself.
Such a script can:
On a banking, email or admin site, that amounts to account takeover.
| Type | Where the malicious input lives | Who is affected |
|---|---|---|
| Stored | Saved on the server: a comment, a profile field, a product review | Everyone who views that content |
| Reflected | In the request itself, such as a URL parameter that the server echoes back into the page | Someone who follows a crafted link |
| DOM-based | Never reaches the server; the page's own JavaScript reads untrusted data and writes it into the page unsafely | Someone who follows a crafted link |
Stored XSS is the most serious, because it needs no further action from the attacker and reaches every visitor.
Reflected XSS typically arises on search pages and error messages: "No results for [whatever was in the URL]".
DOM-based XSS has grown with single-page applications. The server response may be perfectly safe, and the flaw is in client-side code that takes something like the URL fragment and inserts it with innerHTML.
The central rule: when you put untrusted data into a page, encode it for the place it is going.
For HTML body content, that means replacing the characters HTML treats as special:
| Character | Becomes |
|---|---|
< | < |
> | > |
& | & |
" | " |
' | ' |
After encoding, a comment containing a script tag is displayed on screen as literal text, angle brackets and all. It is no longer markup.
Context matters. The correct encoding differs depending on where the data lands:
| Context | Example | Needs |
|---|---|---|
| HTML body | <p>DATA</p> | HTML entity encoding |
| HTML attribute | <input value="DATA"> | Attribute encoding, and always quote the attribute |
| JavaScript | <script>var x = "DATA"</script> | JavaScript string encoding; better, avoid this pattern |
| URL | <a href="/search?q=DATA"> | URL encoding |
| CSS | class="page_speed_4cce1733b8a52719d5f6e28b6f4b0492" | Strict validation; avoid if possible |
The OWASP XSS Prevention Cheat Sheet covers each context in detail.
You should rarely write this encoding by hand. Modern frameworks do it automatically:
// Safe: React escapes this
<p>{comment.text}</p>
XSS in modern applications nearly always comes from opting out of that protection:
| Framework | The escape hatch |
|---|---|
| React | dangerouslySetInnerHTML |
| Vue | v-html |
| Angular | bypassSecurityTrust... |
| Plain JavaScript | innerHTML, document.write, eval |
| Template engines | safe or raw filters |
Treat each use as something that needs a specific justification and review. In plain JavaScript, prefer textContent, which always treats its input as text.
Two more traps that frameworks do not cover:
href and src. A link whose address uses the javascript: scheme runs code when clicked. Check that user-supplied URLs begin with http: or https:.Sometimes you need to accept real HTML: a rich text editor, rendered Markdown, an email viewer. Encoding would destroy the formatting.
Use a dedicated sanitiser library, such as DOMPurify, which parses the HTML and removes everything not on an allow-list of safe tags and attributes. Do not attempt this with regular expressions; HTML is too irregular. See how regular expressions work.
A Content Security Policy (CSP) is a response header that tells the browser which sources of script are allowed.
Content-Security-Policy: script-src 'self' 'nonce-r4nd0m'; object-src 'none'; base-uri 'none'
With a strict policy:
So even if markup is injected, the browser refuses to run it. CSP is a safety net for when encoding is missed somewhere. It is not a replacement for encoding.
HttpOnly cannot be read by JavaScript, so an injected script cannot copy it. It can still make requests while the user is on the page, so this reduces harm without removing it. See cookies vs localStorage vs sessions.localStorage is readable by any script on the page. This is central to the JWT vs sessions debate.<script>. There are many other ways to run script in HTML, and many ways to disguise markup.| XSS | CSRF | |
|---|---|---|
| What happens | Attacker's script runs inside the trusted site | Another site causes the user's browser to send a request to the trusted site |
| What is abused | The user's trust in the site | The site's trust in the user's browser |
| Main defence | Output encoding, CSP | Anti-CSRF tokens, SameSite cookies |
An XSS flaw can defeat CSRF protections, since the script runs on the site itself and can read the tokens.
Cross-site scripting. The abbreviation uses an X to avoid confusion with CSS, the stylesheet language.
Stored XSS is saved on the server and served to every visitor of the affected page. Reflected XSS comes from the request itself and affects only someone who opens a crafted link.
It escapes values in JSX by default, which prevents most cases. Risks remain in dangerouslySetInnerHTML, user-controlled URLs and direct DOM manipulation.
No. It is a valuable second layer, but the primary fix is correct output encoding.
XSS happens when a page lets data become code. The answer is to keep them apart: encode on output for the right context, let your framework escape by default, sanitise any HTML you must accept, and add a Content Security Policy and HttpOnly cookies to contain mistakes. With those in place, a malicious comment is just some odd-looking text.