Cross-Site Scripting (XSS), Explained
If you are reading this, you have probably seen <script>alert(1)</script> in a security course and you want to know why that tiny snippet matters, what the three kinds of XSS are, and how developers actually prevent it.
By the end you will be able to explain what XSS is, tell reflected, stored and DOM-based XSS apart, say what an attacker can do with it, spot the unsafe pattern in code, and apply the right fix for each place where data is displayed. It is part of the Injection category in the OWASP Top 10. Everything here is for understanding and for practice on labs you own or are allowed to test.
1. What XSS is
When you visit a website, your browser runs the JavaScript that the site sends. The browser trusts that script, within limits: a script from bank.example can read the page, use the visitor's session on bank.example and change what is shown. Scripts from other sites are kept out by the browser's same-origin policy.
Cross-site scripting (XSS) is a flaw where an attacker gets their JavaScript to run inside the victim's browser as if it came from the trusted site. The browser cannot tell the difference, so the same-origin policy no longer protects the victim.
PortSwigger defines it as a vulnerability that allows an attacker to compromise the interactions that users have with a vulnerable application. The attacker does not break into the server: they make the site itself deliver their script to the victim.
Why it is called "cross-site"
The name comes from early attacks in which a script from one site was made to act on another. It stuck, even though the core problem today is simply untrusted input shown to the browser as code. It is an injection flaw like SQL injection, but the interpreter is the browser's HTML and JavaScript engine instead of a database.
2. The simplest example
Imagine a search page that echoes what you searched for:
# Flask, vulnerable
@app.route("/search")
def search():
q = request.args.get("q", "")
return f"<h1>You searched for: {q}</h1>"
A normal visit to /search?q=shoes shows "You searched for: shoes". Now a visitor opens:
/search?q=<script>alert(1)</script>
The server puts that text straight into the HTML. The browser receives:
<h1>You searched for: <script>alert(1)</script></h1>
It sees a <script> element and runs it. A pop-up appears. The pop-up is harmless; it is only a proof that the attacker's code runs on the page. A real attacker would put something else inside the script. (PortSwigger's generic form of this example is https://insecure-website.com/status?message=<script>/* Bad stuff here... */</script>.)
The cause is the same as in SQL injection: data and code in one string. The visitor's text is treated as HTML.
3. The three types
| Type | Where the bad input comes from | Who is affected | Stored on the server? |
|---|---|---|---|
| Reflected | The current HTTP request (URL or form) | A victim who is tricked into opening a crafted link | No |
| Stored (persistent) | The site's own database or storage | Every visitor who views the affected content | Yes |
| DOM-based | JavaScript running in the browser, reading something like the URL | A victim who opens a crafted link | Not necessarily; the server may never see it |
Reflected XSS
The malicious input is in the request, and the server reflects it back in the response, as in the example above. The attacker must get the victim to open the crafted link, usually by sending it in a message (phishing or smishing) or by hiding it behind a shortened or friendly-looking address. Because the link points to the real site, it looks trustworthy.
Stored XSS
The input is saved by the application (a comment, a profile bio, a support ticket, a username) and later displayed to other users. The attacker does not need to trick anyone: every visitor who loads the page runs the code. It can be the most damaging type because one injection reaches many people, including administrators who review the content.
DOM-based XSS
The server may be perfectly safe, and the flaw sits in the page's own JavaScript. The script takes data from a source the attacker can influence and writes it into the page through a dangerous sink.
| Common sources (attacker-influenced) | Common sinks (dangerous places to write) |
|---|---|
location (the URL), location.search, location.hash |
element.innerHTML, outerHTML, insertAdjacentHTML() |
document.referrer, window.name |
document.write(), document.writeln() |
postMessage data |
eval(), setTimeout() with a string |
| Data read from storage or from an API (once it came from a user) | Event-handler properties such as element.onclick, and URL attributes such as a link's href set from data |
Vulnerable code:
// Reads the part of the URL after '#', decodes it, and puts it in the page as HTML
document.getElementById("greeting").innerHTML = decodeURIComponent(location.hash.slice(1));
The decodeURIComponent call matters. The URL standard percent-encodes < and > in the fragment when a URL is parsed, so location.hash holds %3Cimg%20src=1...%3E, not the raw tag. Without decoding, innerHTML would only display that text, which is harmless. I tested this in Chrome by opening a page with #<img src=1 onerror=...>: location.hash came back percent-encoded and no image element was created until the value was decoded. Code that decodes the fragment (or reads it through another path that decodes it) is the vulnerable pattern.
PortSwigger's example of a DOM payload is an image with an error handler, for instance a page that shows "You searched for: " followed by <img src=1 onerror='/* Bad stuff here... */'>. The image address 1 fails to load, so the browser runs the onerror code. This shows that XSS does not need a <script> tag: any HTML that can run script will do (event-handler attributes, javascript: links in some contexts, and others).
4. What an attacker can do
PortSwigger lists the capabilities of an attacker who gets script running in the victim's session on the site:
| Capability | In plain words |
|---|---|
| Impersonate the victim | Act as that user on the site |
| Perform any action the victim can | Send messages, change settings, make purchases, post content |
| Read any data the victim can | Private messages, account details, page contents |
| Capture login credentials | By showing a fake login form inside the real page, or logging what is typed |
| Deface the page virtually | Change what the victim sees |
| Inject further malicious functionality | Load more code, redirect, or add a keylogger |
A note that matters for defenders: setting the HttpOnly attribute on a session cookie stops scripts from reading the cookie, which blocks one popular way of stealing sessions. But the injected script can still use the logged-in session, because the browser attaches the cookie to its requests automatically. So HttpOnly reduces the damage; it does not fix XSS.
A real case: the Samy worm, 2005
On 4 October 2005, Samy Kamkar released a stored XSS worm on the social network MySpace. A profile that contained the code, when viewed, made the viewer send a friend request to its author, added the line "but most of all, samy is my hero" to the viewer's own profile, and copied the code there too, so it spread by itself. Reports say over a million users ran it within about 20 hours. The worm itself did no direct harm, but it showed how quickly stored XSS can spread, and MySpace had to fix the hole. The author later reached a plea agreement and received probation and community service.
5. Contexts: why "just escape it" is not one rule
The same text means different things in different places on the page, so the safe encoding depends on where it is inserted:
| Where the data goes | Example | What must be escaped |
|---|---|---|
| HTML body text | <p>Hello, DATA</p> |
HTML-entity encode &, <, >, " and ' |
| HTML attribute value | <input value="DATA"> |
Attribute-encode, and always surround attribute values with quotation marks |
| JavaScript string | var name = 'DATA'; |
Use an encoder documented for both the JavaScript string and the HTML around it. OWASP lists putting variables directly inside a script block as unsafe |
| URL parameter | <a href="/s?q=DATA"> |
URL-encode the value (the %HH format) |
| A whole URL | <a href="DATA"> |
Allow only http: and https:; block javascript: |
| CSS | style="color: DATA" |
OWASP: put variables only in a CSS property value; other CSS contexts are unsafe |
A function that is correct for the HTML body is wrong in a JavaScript string. That is why developers should not write their own escaping but use the template engine or framework, which knows the context.
6. How to prevent XSS
The main rule: encode on output, in context
PortSwigger's advice is to encode data on output at the point where user-controllable data is placed into a page, using the right encoding for the context (HTML, URL, JavaScript or CSS). The safe version of the search example:
from markupsafe import escape
@app.route("/search")
def search():
q = request.args.get("q", "")
return f"<h1>You searched for: {escape(q)}</h1>"
Now <script> is sent as <script>, which the browser displays as text instead of running it. Even better is to use templates that escape automatically.
Use frameworks and APIs that are safe by default
| Technology | Safe by default? | The pitfall |
|---|---|---|
| Django templates | Yes: every variable is escaped by default | The safe filter, or an {% autoescape off %} block, turns escaping off |
| Jinja2 and Flask | Jinja2 on its own does not autoescape by default. Flask turns it on for templates ending in .html, .htm, .xml, .xhtml and .svg when using render_template(), and for all strings with render_template_string() |
The safe filter, Markup, or an {% autoescape false %} block. Building HTML with an f-string, as in the example above, has no escaping at all |
| React, Angular, Vue | Content placed in templates is escaped | dangerouslySetInnerHTML (React), bypassSecurityTrust… functions (Angular) and v-html (Vue). OWASP also notes React cannot safely handle javascript: or data: URLs |
| Plain JavaScript | textContent is safe |
innerHTML is not |
OWASP's summary is that modern frameworks lead to fewer XSS bugs because they steer developers towards good practice, but the escape hatches above remove that protection.
For the DOM example, the fix is to put the text in as text, not HTML:
document.getElementById("greeting").textContent = decodeURIComponent(location.hash.slice(1));
When you must allow some HTML
If users are allowed to post formatting (a blog comment with bold and links), encoding would show the tags as text. In that case, run the content through a well-maintained HTML sanitizer such as DOMPurify, which removes dangerous elements and attributes while keeping safe ones. Use the sanitizer on the final HTML, just before it goes into the page. (This blog does exactly this when it renders posts.) Sanitizer libraries occasionally have vulnerabilities of their own, so keep them updated, and OWASP warns that if you sanitize content and then modify it afterwards, you can void the protection.
Defence in depth
| Control | What it does |
|---|---|
| Content Security Policy (CSP) | A response header that tells the browser which script sources are allowed. A strong policy (for example script-src 'self' with no inline scripts) can stop injected scripts from running even if one gets onto the page. PortSwigger calls it the last line of defence, and OWASP an additional layer |
Correct Content-Type and X-Content-Type-Options: nosniff |
Stops the browser from treating a non-HTML response as HTML |
| HttpOnly, Secure and SameSite cookies | Keep scripts from reading session cookies and limit cross-site use (see CSRF) |
| Input validation | Reject input that does not fit (a phone number should contain digits). It reduces risk but never replaces output encoding, because some fields must accept any text |
| Trusted Types | A browser feature (OWASP notes it on Chromium-based browsers) that makes the browser reject plain strings assigned to dangerous DOM sinks |
| Scanning and code review | Search your code for innerHTML, document.write, eval, the safe filter and dangerouslySetInnerHTML |
7. How testers find it
With permission, a tester submits a unique harmless string into every input and then searches the responses and the rendered page for where it appears. For each place it appears, they check which context it lands in (HTML body, attribute, script, URL) and craft input that breaks out of that context. For DOM-based XSS they trace data from sources to sinks in the page's JavaScript, often using the browser's developer tools. PortSwigger notes that most XSS can be found quickly with a scanner such as Burp Suite's, but manual testing is needed to be thorough.
Practise on:
| Resource | What you get |
|---|---|
| PortSwigger Web Security Academy: XSS | Free labs for reflected, stored and DOM-based XSS, in many contexts |
| OWASP Juice Shop | A vulnerable web shop with XSS challenges |
8. Common mistakes
| Myth | The facts |
|---|---|
"If I block <script>, I am safe" |
Many other tags and attributes run code (<img onerror=…>, <svg onload=…>). Blocklists are easy to get around |
| "Validating input is enough" | Encode on output, in context. Validation is an extra layer |
| "HttpOnly cookies make XSS harmless" | The script cannot read the cookie, but it can still act as the user |
| "Only forms and search boxes matter" | URLs, headers, file names, JSON fields and data from other systems can all carry XSS |
"The alert(1) pop-up is the attack" |
It is only a proof of execution. The real impact is whatever the script does |
| "We use React, so XSS is impossible" | Frameworks help, but unsafe escape hatches, unsafe URLs and server-side injection can still cause it |
| "Stored data from our own database is safe" | If it was ever user input, encode it when you display it |
| "A WAF handles XSS" | OWASP does not recommend relying on WAFs to prevent XSS, especially DOM-based XSS |
Closing
Cross-site scripting happens when a site shows untrusted data to the browser as code. The attacker's script then runs with the victim's access to that site. Reflected XSS arrives through a crafted link, stored XSS sits in the site's data and hits every visitor, and DOM-based XSS lives in the page's own JavaScript. The fix is to treat all data as text: encode it for the place it is shown, use safe APIs and auto-escaping templates, sanitize HTML when you must allow it, and add a Content Security Policy as a backstop.
Keep these points:
- XSS = attacker's script running as the trusted site.
- Three types: reflected (crafted link), stored (saved on the site) and DOM-based (flaw in client-side code).
- Impact: acting as the user, reading their data, stealing credentials, spreading.
- Encode on output, in context; prefer
textContentand auto-escaping templates. - Sanitize with a trusted library when HTML is allowed.
- CSP and HttpOnly cookies limit the damage; they do not replace the fix.