What Is XSS? Preventing User Data from Becoming Browser Code
Cross-site scripting (XSS) occurs when an application places untrusted data in a page so the browser interprets it as markup or code instead of text. The central defense is to render ordinary data as text or apply output handling for its exact destination context; deleting a few suspicious input strings is not a general fix.
How does the browser turn data into code?
Browsers parse HTML text, attributes, URLs, CSS, and JavaScript according to different rules. If a profile name or search term is concatenated into HTML, the browser may parse part of it as markup. For an illustrative display name Jin <preview>, a template's normal auto-escaping or element.textContent = displayName presents the characters as text. innerHTML parses a string as HTML and is therefore a poor choice for ordinary user text.
Code in an XSS flaw runs in the victim's browser under the vulnerable site's origin. Depending on the page and the user's permissions, it may read data available on that page or perform actions as the signed-in user. Cookie theft is not a necessary condition: HttpOnly limits JavaScript access to a cookie, but does not stop all actions available within an authenticated page. OWASP describes possible impacts including account impersonation and sensitive-data exposure (prevention guide).
How do reflected, stored, and DOM-based XSS differ?
These labels describe overlapping parts of a data flow. Reflected and stored usually describe how data reaches a victim; DOM-based describes unsafe processing by browser code. A stored or reflected value may also be handled in the DOM.
| Type | Data flow | Safe review focus |
|---|---|---|
| Reflected | A request value, such as a search term, is included in the immediate server response. | In an authorized test environment, check that a benign string containing punctuation is rendered as text in the response's actual context. |
| Stored | A submitted comment or profile value is saved and later shown to other users. | Use isolated test accounts and a harmless marker; check both the author's and a separate viewer's pages for text rendering and unintended side effects. |
| DOM-based | A URL fragment or other browser-side source reaches a risky DOM sink such as innerHTML. | Trace the source-to-sink path in client code; inspecting only the server response may miss it. |
“Server-side” and “client-side” describe where unsafe handling occurs. A server template can insert a value unsafely; page JavaScript can also pass a URL value to innerHTML. In both cases, execution happens in the browser, so locate the real output point and context. OWASP notes these classifications can overlap in its DOM XSS guide.
Choose a defense for the destination
First decide whether the product needs plain text or user-authored HTML, then identify the exact output context. There is no universal “XSS cleaner” that can safely replace this decision. Generic input filtering can damage data and cannot know where a value will later be used.
| Destination | Preferred approach | Important limit |
|---|---|---|
| Ordinary text in an HTML element | Keep the template framework's auto-escaping or use context-aware HTML output encoding. | Do not disable escaping for untrusted values. |
| Ordinary text in the browser DOM | Use textContent, createTextNode, or DOM construction APIs. | textContent on an ordinary element is for text; it does not make script or style content safe. |
| Plain-text attribute | Use the framework's attribute handling, a fixed attribute name, and a quoted value. | URL attributes also need scheme/destination validation; event-handler attributes are executable contexts. |
| User-authored formatted HTML | Use a maintained sanitizer with a narrow allowlist of permitted tags and attributes. |
For comments intended as plain text, preserve default template escaping or use textContent. If formatting is a real product requirement, define the small set of allowed markup and render only the output of a maintained HTML sanitizer. OWASP recommends contextual encoding, safe framework defaults, and sanitization when HTML must be accepted; framework escape hatches need review (OWASP guide).
A safe remediation and verification sequence
Work only within an approved test scope, preferably with isolated accounts and data. Do not test stored behavior using other people's records.
Inventory untrusted sources: URL parameters and fragments, forms, stored comments or profiles, and external-service responses.
Trace every rendering point in server templates and browser code. Identify whether the value reaches HTML text, an attribute, URL, script, CSS, or DOM sink; fixing one screen may leave another use vulnerable.
Prefer plain-text rendering. Keep framework auto-escaping enabled and review APIs that interpret strings, such as `innerHTML`, `document.write`, and `eval`.
Apply the destination-specific control. Use safe text APIs for text, a maintained sanitizer for necessary formatted HTML, and URL scheme/destination validation for URLs. Input validation helps enforce business formats but does not replace output protection.
Use an authorized benign marker such as `A&B <preview> "quote"`. Confirm it appears as readable text rather than creating markup. For stored flows, check an isolated author and a separate test viewer; for DOM flows, follow the browser-side source-to-sink path. A server-response-only scanner may miss DOM XSS.
Check both allowed behavior and regression: intended text or formatting still works, prohibited markup does not execute, and every other view of that data is fixed. If rendering breaks, re-check each destination context rather than repeatedly encoding the same string.
The OWASP Web Security Testing Guide recommends examining reflected values and their returned encoding. DOM review also needs client-side data-flow analysis; no single scan proves every rendering path safe.
Why are CSP and cookie settings only supporting defenses?
A Content Security Policy (CSP) limits which scripts and resources the browser may run, reducing impact if the primary rendering defense fails. A strict policy may authorize scripts with nonces or hashes, but it must be designed and tested for the application. CSP does not make unsafe DOM operations or context-insensitive output safe.
Cookie attributes such as HttpOnly, Secure, and SameSite can limit some cookie exposure or request paths, but they do not remove XSS. Even when JavaScript cannot read an HttpOnly cookie, code running in an authenticated page may attempt actions available to that user. CSP, cookie settings, and WAFs are layers, not substitutes for safe DOM APIs, contextual output handling, and sanitization. MDN describes CSP as a backup defense (MDN XSS guide); OWASP cautions that WAFs cannot fix vulnerable code.
Common misconceptions
Removing only the string `<script>` is incomplete: markup, attributes, URLs, and parsing contexts also matter.
HTML encoding is not interchangeable with JavaScript, CSS, or URL handling.
Modern frameworks help through auto-escaping, but unsafe HTML features, escape hatches, plugins, and URL handling still need review.
CSP or a WAF can reduce some risk but does not fix the vulnerable output point.
Cookie protection limits cookie access, not every action XSS can perform in an authenticated page.
References
OWASP, [Cross Site Scripting Prevention Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html)
OWASP, [DOM based XSS Prevention Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/DOM_based_XSS_Prevention_Cheat_Sheet.html)
OWASP, [Testing for Reflected Cross Site Scripting](https://wstg.owasp.org/latest/11-Injection/01-Reflected_Cross_Site_Scripting/)
MDN, [Cross-site scripting (XSS)](https://developer.mozilla.org/en-US/docs/Web/Security/Attacks/XSS)