Skip to main content
Security guideReviewed

XSS (cross-site scripting): what it is, the three types and how to prevent it

Cross-site scripting happens when text from someone else lands in your page in a way the browser treats as code.

This guide explains what that lets an attacker do, how reflected, stored and DOM-based XSS differ, and why the fix depends on where the text lands. Then it gives you a test suite to run with Node.js alone: one marker, five contexts, and the unsafe and safe versions side by side.

XSS test suite, DOM source-to-sink map and browser checks

An illustration, not a client system: five pieces of an invented bakery's order page. Part 1 is a test suite that runs with Node.js alone and places one marker in the HTML body, attribute, JavaScript, URL and CSS contexts, with unsafe and safe versions and the real output of each run.

How to use it

Part 2 maps DOM sources and sinks to safe replacements, each with its source. Part 3 lists browser checks for you to run on your own code before and after a fix. For learning and for testing code you own.

xss.txt

Introduction6 lines

ILLUSTRATION ONLY. The bakery, its order page and every input below were written for this page. Nothing here is a client's code or a client's result. Use it to learn, and to test code you own. Do not point any part of it at a system you do not own or are not authorised in writing to test. The asset has three parts: Part 1 A context-aware encoding test suite: five files that run with Node.js alone. Part 2 A DOM source-to-sink map, with the safe replacement for each sink. Part 3 Browser checks before and after a fix, for you to run on your own code.

What cross-site scripting is

Cross-site scripting, or XSS, happens when a website takes text it did not write, such as a search term, a customer's name or a comment, and puts it into a page in a way the browser treats as code.

OWASP's Cross Site Scripting Prevention Cheat Sheet puts it as an application putting untrusted data into a page in a way that lets the browser treat it as code, and gives its own example: a user's comment that should appear as plain text instead runs as JavaScript or adds HTML the attacker controls.

The cheat sheet treats as untrusted anything your application did not create itself, including form input, URL parameters, data stored by users and responses from other services.

MITRE catalogues the weakness as CWE-79, Improper Neutralization of Input During Web Page Generation. Its description is one sentence: the product does not neutralise, or incorrectly neutralises, user-controllable input before it is placed in output that is used as a web page served to other users.

The OWASP Top 10:2025 files cross-site scripting under A05 Injection and describes it as high frequency and low impact, with more than 30k CVEs, adding that the massive number of CVEs for CWE-79 brings down the category's average weighted impact.

For a single flaw, CWE-79 says the effect on the end user can range in severity from an annoyance to complete account compromise.

The name is older than the problem it now covers. The cheat sheet calls it a misnomer: the term came from early versions of the attack that were primarily focused on stealing data cross-site, and has since widened to include injection of basically any content.

In business terms: your site sends a page, and part of that page came from someone else. If the browser cannot tell your code from their text, their text runs as if your site had written it, in the browser of whoever is viewing the page.

What XSS lets an attacker do in a visitor's browser

MDN's guide to Content Security Policy describes an XSS attack as one where an attacker can execute their code in the context of the target website, and says that code can then do anything the website's own code could do.

Its examples are reading or changing the content of the site's loaded pages, reading or changing what the site keeps in local storage, and making HTTP requests with the user's credentials, which lets the attacker impersonate the user or reach sensitive data.

OWASP's cheat sheet lists account impersonation, observing user behaviour, loading external content and stealing sensitive data. CWE-79 adds creating requests that can be mistaken for those of a valid user, redirecting the user to another page or site, and changing how content is presented, and it notes that this could be especially dangerous to the site if the victim has administrator privileges.

Who views the page decides how far that reaches. Script that runs in a customer's browser can act as that customer. Script that runs in a staff member's browser, because a customer's note or name appears on a staff screen, can act as that staff member, with everything their account can see and change.

OWASP's test for stored XSS makes the same point: the flaw is particularly dangerous in areas where users with high privileges have access, because when an administrator visits the page, the attack runs automatically in their browser.

This page describes the mechanics at the level a defender needs. Its test inputs are markers that, at most, add an empty element or set a page title. It does not show how to take over sessions or attack anyone else's site, and the test suite is for learning and for testing code you own.

Reflected, stored and DOM-based XSS

OWASP and MITRE name three types.

They differ in how the attacker's text reaches the page and in where it is mishandled, not in what it can do once it runs. CWE-79 says the consequence of an XSS attack is the same whether it is stored or reflected, and OWASP's DOM-based XSS test says those flaws should be treated with the same severity as the other forms.

Reflected XSS

The text arrives in a request and comes straight back in the response. OWASP's test for it, WSTG-INPV-01, says the injected code is not stored within the application: it is non-persistent and only affects users who open a maliciously crafted link or third-party web page. CWE-79 calls it Type 1 and says the most common way to deliver it is a parameter in a URL that is posted publicly or emailed directly to the victim.

A search results page that repeats the search term back to the visitor is the shape to check.

Stored XSS

The text is saved first and shown later. WSTG-INPV-02 says this typically involves at least two requests to the application, which is why it may also be called second-order XSS, and that it needs no malicious link: the attack succeeds when someone visits the page that holds it.

CWE-79 calls it Type 2 and says the place an attacker would choose is an area displayed to many users or to particularly interesting ones, who typically have elevated privileges in the application or interact with sensitive data that is valuable to the attacker.

Its example is XSS planted in a log message that an administrator later views. On a business site, that means order notes, customer names, support messages, reviews and profile fields, and above all the staff screens that display them.

DOM-based XSS

The server may never see the problem at all. OWASP's WSTG-CLNT-01 describes DOM-based XSS as the result of active browser-side content on a page, typically JavaScript, obtaining user input through a source and using it in a sink, leading to the execution of injected code. Its example is a script that writes the page's own address into the document.

Anything after the # in that address is a fragment the browser does not send to the server, so the server cannot see it, yet the page's script writes it in. CWE-79 calls this Type 0.

Why the labels overlap

The labels describe two different things. OWASP's DOM based XSS Prevention Cheat Sheet explains that stored and reflected describe how an attack reaches a victim, while server-side and client-side describe where untrusted data is handled unsafely, so a stored or reflected attack can also be DOM-based. Its advice follows: choose the controls for the actual data flow and the context the data is placed in.

XSS prevention: why the fix depends on where the data lands

A browser reads one page with several parsers.

The XSS cheat sheet explains that there are many output encoding methods because browsers parse HTML, JavaScript, URLs and CSS differently, and that using the wrong method may introduce weaknesses or harm how the application works.

CWE-79 lists parts of one page that can need different encodings, including the HTML body, element attributes, URIs, JavaScript sections and CSS, and notes that HTML entity encoding is only appropriate for the HTML body.

So the same customer name needs different handling depending on where it lands. The test suite on this page uses one invented bakery order page and one marker, "></script><i data-xss="marker">, placed in five contexts. Joined in as it is, the marker creates an element in every one of them. With the protection for each context, it stays data in all five.

Two requirements from ASVS 5.0 frame the job. Requirement 1.2.1, at Level 1, asks for output encoding relevant to the context, such as the relevant characters for HTML elements, HTML attributes, HTML comments, CSS or HTTP header fields, to avoid changing the document's structure. Requirement 1.1.2, at Level 2, asks that encoding happens as a final step before the interpreter uses the data, or inside the interpreter itself, and the chapter adds that stored data should stay in its original form rather than being saved encoded, to prevent double encoding.

HTML body

Text between two tags, such as an order note in a paragraph. 1 min read

HTML attribute

A value inside an attribute, such as a name filled into a form field. 1 min read

JavaScript

Data a script needs, such as the customer's name for a greeting. 1 min read

URL

Two different jobs share this context. 1 min read

CSS

A value inside a style, such as a progress bar's width. 1 min read

Where output encoding stops working

The XSS cheat sheet is plain about the limits: output encoding is not perfect and will not always prevent XSS.

It names dangerous contexts where it says not to place variables, because even with output encoding an XSS attack will not be fully prevented there: directly inside a script, inside an HTML comment, directly inside CSS, and as the name of an attribute or a tag.

It lists other areas to be careful with, including callback functions, places where code handles URLs, untrusted event-handler code such as a whole onclick value, and functions such as eval(), setInterval() and setTimeout().

Event handlers need their own warning. The cheat sheet says HTML attribute encoding alone does not protect JavaScript in an event-handler attribute, because the HTML parser decodes character references before the JavaScript is interpreted, and recommends addEventListener() with trusted handler functions, passing user values as data.

The DOM based XSS cheat sheet shows JavaScript-encoded text still running when it is set as an onclick attribute with setAttribute(), and gives its primary recommendation as keeping untrusted data out of that context.

Validation narrows what arrives, and it is not the fix. CWE-79 says proper output encoding, escaping and quoting is the most effective solution for preventing XSS, and that input validation may add some defence in depth but will not always prevent it, especially where free-form text must be accepted.

Its example is a heart emoticon, <3, in a chat application: it would likely pass validation, yet it cannot go into the page directly because of the < character.

The XSS cheat sheet puts the same idea the other way round: validation can hold input to an expected format, and it is no substitute for safe APIs, context-specific encoding or a sanitiser.

Stripping suspicious words such as script from input is weaker still. OWASP sends readers who want the detail to its XSS Filter Evasion Cheat Sheet, which illustrates why filtering on its own falls short. This page does not reproduce it.

DOM-based XSS: sources, sinks and the safe replacements

DOM-based XSS lives in your front-end JavaScript, so you find it by following data through the code.

A source is where script reads something an attacker can influence, such as the page address. A sink is an API that turns a string into markup or code. MDN calls these APIs injection sinks, and its Trusted Types reference sorts them into three kinds: HTML sinks such as innerHTML and document.write(), JavaScript sinks such as eval(), and JavaScript URL sinks such as a script element's src.

innerHTML is the first one to search for. MDN calls it probably the most common vector for XSS and explains that, although script elements inserted through it do not execute, it is open to many other ways of running JavaScript. Its own example is an img element whose error handler runs because the src is not a valid image URL.

The fix is to use the sink that matches the job. The XSS cheat sheet's advice is to refactor away from unsafe sinks like innerHTML towards textContent or value, and its list of text sinks includes insertAdjacentText(), className, setAttribute() with a fixed, safe attribute name and createTextNode().

ASVS 5.0 requirement 3.2.2, at Level 1, asks that content meant to be displayed as text is handled with safe rendering functions such as createTextNode or textContent. The map in the asset pairs each sink it lists with a replacement and the source behind the pairing.

Three traps from the DOM based XSS cheat sheet are worth knowing. Encoding is lost when a value is read back from a form field's value property, so text the server encoded safely comes back raw. innerText, which some guides recommend in place of innerHTML, runs code when it is set on a script element.

And untrusted data used as a property name, as in window[name], can let an attacker subvert the object's internal and external attributes, so the cheat sheet adds a level of indirection, such as checking the key against the names you expect.

Messages from other windows are a source too. ASVS 5.0 requirement 3.5.5, at Level 2, asks that messages received through postMessage are discarded if the sender's origin is not trusted or the message's syntax is invalid.

Sanitising HTML is a different job from encoding

Encoding keeps every character the user typed and makes the browser show it as text.

That is the wrong result when users are meant to write formatted content in a WYSIWYG editor, such as a product description. The XSS cheat sheet explains that output encoding would prevent XSS there but break the feature, because the styling would not render, and that HTML sanitisation is the tool for that case: it strips dangerous HTML and returns a safe string of HTML. OWASP recommends DOMPurify for the job.

ASVS 5.0 draws the same line. Its sanitisation section calls context-specific encoding the ideal protection, because it keeps the meaning of the content, and treats sanitisation as necessary where encoding is not possible, noting that in some cases it may change the meaning of the input.

Requirement 1.3.1, at Level 1, asks that untrusted HTML from WYSIWYG editors or similar is sanitised with a well-known and secure HTML sanitisation library or framework feature, and requirement 1.3.5, at Level 2, covers user-supplied Markdown, CSS, BBCode and similar content.

A sanitiser protects only the string it returns. The cheat sheet and DOMPurify's own README both warn that modifying content after sanitising it can void the protection, and the README asks you to be certain that any library you pass sanitised markup to does not change it. The cheat sheet adds that DOMPurify and other sanitisers must be patched regularly, because browsers change functionality and bypasses are being discovered regularly.

Where the sanitiser runs matters. DOMPurify's README says it technically also works on the server with Node.js, but needs a DOM there, strongly recommends the latest version of jsdom, and warns that older jsdom versions have known flaws that result in XSS even when DOMPurify does everything correctly.

Browsers are adding a built-in option. MDN's HTML Sanitizer API reference describes Element.setHTML() as a safe method that always removes XSS-unsafe elements and attributes, and suggests it in place of innerHTML for untrusted HTML. The same page marks the API as limited availability: it is not Baseline, because it does not work in some of the most widely used browsers. Check the compatibility table for the browsers your customers use before relying on it.

Where frameworks protect you, and where code steps around them

Frameworks do part of this work for you.

The XSS cheat sheet says applications built with modern web frameworks have fewer XSS bugs, because the frameworks steer developers towards good security practices and help mitigate XSS through templating, auto-escaping and more, and that many frameworks escape every value they render by default, trusted or not. It recommends that default because it does not depend on someone deciding correctly which data is untrusted.

The gaps are the places where code asks the framework to stand aside. The cheat sheet's list includes escape hatches that manipulate the DOM directly, React's dangerouslySetInnerHTML without sanitising the HTML, unvalidated URL values, Angular's bypassSecurityTrustAs* functions, Lit's unsafeHTML function, template injection and out-of-date framework plugins or components.

React's own reference is direct about its escape hatch. It says dangerouslySetInnerHTML overrides the element's innerHTML, should be used with extreme caution, and that unless the markup comes from a completely trusted source it is trivial to introduce an XSS vulnerability this way. Its example of the security hole is markup stored in a database that contains an image with an error handler, and it says the embedded code will run.

Where a site enforces Trusted Types, the reference says React passes a TrustedHTML value to the browser without converting it to a string, so the browser can validate it.

Links are the other gap to check. React's changelog for version 19.0.0 lists, under React DOM, that javascript URLs are replaced with functions that throw errors. The XSS cheat sheet notes that React 19 blocks javascript: URLs in src and href, and that this does not replace application-specific URL validation. Check the scheme and destination in your own code either way.

CSP, HttpOnly cookies and Trusted Types: what they add and what they do not replace

Three browser features, and a firewall in front of the site, can reduce what an XSS flaw can do or make it harder to reach.

None of them substitutes for correct output encoding and safe DOM APIs. The XSS cheat sheet says framework protections, output encoding and HTML sanitisation give the best protection and are recommended in all circumstances, and lists cookie attributes, CSP, Trusted Types and web application firewalls as controls to consider in addition.

Content Security Policy

A Content Security Policy, delivered in a response header, tells the browser which resources, JavaScript above all, the page may load. 1 min read

HttpOnly cookies

The HttpOnly cookie attribute keeps a cookie away from script. 1 min read

Trusted Types

Trusted Types targets DOM-based XSS. 1 min read

Web application firewalls

A web application firewall can add a layer in front of the site. 1 min read

How to test for XSS on a site you own

OWASP's Web Security Testing Guide splits the work by type.

WSTG-INPV-01, for reflected XSS, has two objectives: identify variables that are reflected in responses, and assess the input they accept and the encoding applied on return. It starts by finding every input, including hidden or non-obvious ones such as hidden form fields, POST data and predefined selection values, then typically sends specially crafted input to each one and examines the resulting HTML for special characters that were not encoded, replaced or filtered out.

The characters that matter depend on the context. For HTML, the guide names >, <, &, ' and " as the key characters to find encoded as entities. Inside an HTML action or JavaScript code it lists new lines, carriage returns, apostrophes, double quotes, backslashes and unicode values.

For stored XSS, WSTG-INPV-02 adds that every area of the application administrators can reach should be tested for data submitted by users. For DOM-based XSS, WSTG-CLNT-01 sets two objectives, identifying DOM sinks and building payloads for every sink type, and notes that automated testing has only very limited success unless the tool can also analyse the client-side code. Read the front-end code where it refers to parameters, writes to the page or runs script.

On your own systems, a harmless marker is all you need. The guide's examples use alert boxes and cookie reads, and you need neither: input that would only add an empty element with a fixed data attribute, or set the page title to a fixed word, proves the input became markup.

Work on a local or staging copy with test accounts, and test only systems you own or are authorised in writing to test.

OWASP's Top 10:2025 says injection is best detected by combining source code review with automated testing of all parameters, headers, URL, cookies, JSON, SOAP and XML inputs.

  • List every place a value from outside your code lands in a page: server templates, components and front-end scripts, including staff and admin screens.
  • Name the context for each one: HTML body, attribute, script, URL or CSS. That decides the fix.
  • Send the marker through each input one at a time, including hidden fields, URL parameters and the fragment after #, and look at every page that shows it.
  • Read the page source and the live elements separately, so you can tell a server-side fault from one in front-end code. Part 3 of the asset gives the checks.
  • Fix at the point of output, then add a regression test like the suite's so the fix stays in place.

Running the encoding test suite on your own machine

The suite is an illustration: five pieces of an invented bakery's order page, built as strings by five small files that use only modules and globals that ship with Node.js, so there is nothing to install.

It was written and run on Node.js 26.0.0, every output in the asset comes from that run, and the same files gave the same results on Node.js 22.14.0. It is for learning and for testing code you own.

Be clear about what it proves. Node.js checks the HTML string the server produces; it does not run a browser, so nothing in the suite is browser output. A passing test shows that, for these inputs, the marker did not change the structure of that string: no new element, no attribute or style closed early, no script block ended early and no javascript: link written into the page.

The browser checks in part 3 of the asset are steps for you to run in your own browser on your own code, not results captured for this page.

  • Run node show.mjs. It prints, for each context, what the unsafe and safe versions produce for the marker and for ordinary input.
  • Run node encoding.test.mjs unsafe. Eight of the twelve tests fail: the marker creates an element in all five contexts, the script block ends early, the name is written into the script, an ordinary search term loses everything from its ampersand onwards, and a javascript: link is written into the page.
  • Run node encoding.test.mjs safe. All thirteen tests pass, including one that only the safe version has: the JSON response carries the marker as data.
  • With no argument the file tests the safe version, so node --test, which by default runs files whose names end in .test.mjs, can run it in a pipeline. The Node.js documentation says that if any test fails, the process exit code is set to 1.

Pointing the tests at your own code

Keep the tests and change what they call. Each render function becomes a call to your own template or component, rendered to a string the way your server sends it. Keep the ordinary inputs as well as the markers: in the unsafe version, the search-term test failed on an ordinary name with an ampersand, which shows the same flaw breaking real data with no attacker involved.

Values that script inserts in the browser are not covered by server strings, so check those with the source-to-sink map and the browser steps.

Where an outside security test fits

The suite checks the places you already know about.

A security test also looks for the ones you do not. In the Clever Ops web application and API penetration test, anything one person writes and another person later views is checked for stored scripting, with a harmless marker in place of a script (WSTG-INPV-02), and paths that cross roles deserve the closest look, such as a customer's name or note shown on an administrator's screen.

Public inputs such as search, enquiry and sign-up fields are checked for stored input later shown to other visitors.

With read-only code access in scope, rich-text handling is read for an HTML sanitiser (ASVS 5.0 requirement 1.3.1). The website security check reviews a site's Content Security Policy against the OWASP Content Security Policy Cheat Sheet. The report gives each finding with redacted evidence, its business impact, a fix and the criteria the retest will use.

A report is evidence for your decisions, not a certificate. If a tender or contract requires a CREST-accredited provider, Clever Ops is not CREST accredited, so we refer that work to a provider that is. If Clever Ops built or hosts your application, the work is a security review rather than an independent test, and the report says who built it and who hosts it.

Frequently asked questions

Cross-site scripting is what happens when a website puts text it did not write, such as a comment or a search term, into a page in a way the browser treats as code. That code then runs in the visitor's browser, where MDN says it can do anything the website's own code could do, such as changing the page or sending requests as the user.

Reflected XSS comes back in the response to a crafted request, such as a link. Stored XSS is saved first and shown later to whoever views the page, staff included. DOM-based XSS happens when script in the page takes data from a source, such as the address bar, and passes it to a sink such as innerHTML. OWASP notes that the labels overlap: stored and reflected describe how the attack reaches a victim, while server-side and client-side, where DOM-based XSS sits, describe where the data is mishandled.

Use the protection that matches where the data lands: HTML entity encoding in the page body, attribute encoding inside quoted attributes, no untrusted data inside scripts, URL encoding for values in links and an http and https allow-list for whole addresses, and strict validation for CSS values. In browser code, use textContent rather than innerHTML, and where users must write HTML, use a maintained sanitiser. Add a Content Security Policy as a second layer.

It helps, and it leaves gaps that your code controls. OWASP's cheat sheet says applications built with modern web frameworks have fewer XSS bugs, because the frameworks steer developers towards good security practices and help mitigate XSS through templating, auto-escaping and more, then lists React's dangerouslySetInnerHTML without sanitised HTML, and unvalidated URL values, among the ways problems return. React's own reference says dangerouslySetInnerHTML makes it trivial to introduce an XSS vulnerability unless the markup comes from a completely trusted source.

No. OWASP's CSP cheat sheet calls a strong policy an effective second layer, especially against XSS, and says it should not be relied on as the only defensive mechanism. MDN says setting a CSP is not an alternative to sanitising input. Fix the output handling first, then use a strict, nonce- or hash-based policy as the backstop.

It stops script reading the cookie, through document.cookie for example, but MDN notes that the cookie is still sent with requests JavaScript starts, such as fetch(). Injected script can still act as the user. OWASP says cookie attributes try to limit the impact of XSS but do not prevent the malicious content from running.

On a copy you own, put a harmless marker into each input, including hidden fields, URL parameters and the part of the address after #, then check every page that shows it, staff screens included, for whether it became markup. OWASP's WSTG-INPV-01, WSTG-INPV-02 and WSTG-CLNT-01 describe where to look and what to check, with script payloads where this page uses a marker, and the suite on this page turns the checks into tests. Test only systems you own or are authorised in writing to test.

Scope the right test for your application

Tell us what you have built, who uses it and when it needs to launch. You will get a plain-English recommendation: a website audit, a web application test or a referral to a specialist.