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.
In this guide
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 itHide the instructions
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
Part 1: The context-aware encoding test suite604 lines
Part 2: DOM source-to-sink map60 lines
Part 3: Browser checks before and after the fix50 lines
Whole template738 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.
================================================================
PART 1: THE CONTEXT-AWARE ENCODING TEST SUITE
================================================================
WHAT IT PROVES, AND WHAT IT DOES NOT
Node.js builds each context's HTML as a string, and the tests read that string. No browser runs, so nothing in Part 1 is browser output. A passing test shows that, for these inputs, the marker did not change the structure of the string a server would send: no new element, no attribute or style closed early, no script block ended early and no javascript: link written into the page. Part 3 covers the browser.
The encoders are kept small so that each property can be seen and tested. OWASP's XSS Prevention Cheat Sheet says to start with your framework's default output encoding protection, and to use an output encoding library where you are not using a framework or need to cover gaps in it. Use those in real code, and keep tests like these pointed at the output.
WHAT IT NEEDS
Node.js, with nothing to install. The files use node:test and node:assert, plus URL, encodeURIComponent and JSON, which are built into Node.js.
Written and run on Node.js 26.0.0. Every output below comes from that run. The same files gave the same results on Node.js 22.14.0. Test timings will differ on your machine.
THE INPUTS
Marker: "></script><i data-xss="marker">
Link marker: javascript:void(document.title='xss-marker')
Ordinary text: O'Brien & Sons
If the marker ever became markup, the only element it would create is an empty i element whose data-xss attribute is the word marker. If the link marker were ever followed, it would set the page title to xss-marker. Neither one reads cookies, sends data anywhere or loads anything.
THE FIVE CONTEXTS
1 HTML body: text between two tags. Here, an order note on the staff screen.
Unsafe: joined in as it is.
Safe: HTML entity encoding of & < > " and '. In browser script, textContent.
Source: OWASP XSS Prevention Cheat Sheet, Output Encoding for HTML Contexts.
2 HTML attribute: a value inside a quoted attribute. Here, the customer's name filled into a form field.
Unsafe: joined in as it is.
Safe: attribute encoding, with the template always supplying the double quotes. In browser script, setAttribute() with a fixed, ordinary attribute name.
Source: the same cheat sheet, Output Encoding for HTML Attribute Contexts.
3 JavaScript: data a script needs. Here, the customer's name for a greeting.
Unsafe: joined into a quoted string inside a script block.
Not enough: JSON.stringify(), which keeps the string's quotes intact but lets a closing script tag through.
Safe: no customer data in the script at all. The page fetches the name as JSON, served as application/json, and shows it with textContent.
Sources: the same cheat sheet, Output Encoding for JavaScript Contexts; OWASP DOM based XSS Prevention Cheat Sheet, Rule #6 and Guideline #10.
4a URL, a value inside a link your code builds. Here, a search term in the query string.
Unsafe: joined in as it is.
Safe: encodeURIComponent(), then attribute encoding.
Source: the same cheat sheet, Output Encoding for URL Contexts and its Common Mistake note.
4b URL, a whole address someone else supplied. Here, the website field on a customer profile.
Unsafe: attribute-encoded, but the scheme is not checked.
Safe: parse it with URL, allow only http: and https:, use # for anything else, then attribute-encode.
Sources: the same cheat sheet's rules summary for an untrusted URL in a src or href attribute, which lists allowing only http and https URLs and an attribute encoder; ASVS 5.0 requirement 1.2.2, which asks that only safe URL protocols are permitted, for example disallowing javascript: or data:.
5 CSS: a value inside a style. Here, a progress bar's width.
Unsafe: joined in as it is.
Safe: a fixed property name and strict validation of the value, a whole number from 0 to 100 followed by %, falling back to 0%. In browser script, element.style.setProperty() with a fixed property name.
Source: the same cheat sheet, Output Encoding for CSS Contexts and its rules summary.
SET-UP
Make an empty folder, save the five files below into it under the names shown, and open a terminal in that folder.
==== File 1 of 5: encoders.mjs ====
// encoders.mjs: the small encoders and checks the safe versions use.
// Illustration only. In real code, use the escaping your template engine or
// framework documents for each context, or a maintained encoding library.
// The five characters OWASP's XSS Prevention Cheat Sheet lists for HTML
// entity encoding, with the entity it gives for each.
const HTML_ENTITIES = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": ''',
}
// HTML body: text placed between two tags.
export function encodeForHtml(text) {
let encoded = ''
for (const character of text) {
encoded += HTML_ENTITIES[character] || character
}
return encoded
}
// HTML attribute: the same five characters. It is only correct for a value
// the template wraps in double quotes, so every template here supplies them.
export function encodeForQuotedAttribute(text) {
return encodeForHtml(text)
}
// URL: a whole address someone else supplied, such as a website field.
// Parse it, then allow only http and https. Anything else becomes '#'.
const ALLOWED_LINK_PROTOCOLS = ['http:', 'https:']
export function toAllowedLinkHref(input) {
let url
try {
url = new URL(input)
} catch {
return '#'
}
if (!ALLOWED_LINK_PROTOCOLS.includes(url.protocol)) return '#'
return url.href
}
// CSS: a width for a progress bar. The property name is fixed in the
// template, and the value must be a whole number from 0 to 100 followed by
// a percent sign. Anything else falls back to 0%.
const PERCENT_PATTERN = /^(100|[1-9]?[0-9])%$/
export function toAllowedWidth(input) {
if (PERCENT_PATTERN.test(input)) return input
return '0%'
}
==== File 2 of 5: render.mjs ====
// render.mjs: five pieces of an invented bakery's order page, built as HTML
// strings. Each context has an unsafe version that joins the value in as it
// is, and a safe version that uses the protection for that context.
// Illustration only: nothing here runs in a browser.
import {
encodeForHtml,
encodeForQuotedAttribute,
toAllowedLinkHref,
toAllowedWidth,
} from './encoders.mjs'
// Context 1, HTML body: the customer's order note on the staff screen.
export function renderNoteUnsafe(note) {
return '<p class="note">' + note + '</p>'
}
export function renderNoteSafe(note) {
return '<p class="note">' + encodeForHtml(note) + '</p>'
}
// Context 2, HTML attribute: the customer's name filled into a form field.
export function renderNameFieldUnsafe(name) {
return '<input name="name" value="' + name + '">'
}
export function renderNameFieldSafe(name) {
return '<input name="name" value="' + encodeForQuotedAttribute(name) + '">'
}
// Context 3, JavaScript: a script that greets the customer by name.
export function renderGreetingUnsafe(name) {
return '<script>const customerName = "' + name + '";</script>'
}
// JSON.stringify produces valid JSON, which keeps the string's own quotes
// intact. It is not an encoder for a script block inside HTML: a closing
// script tag passes straight through.
export function renderGreetingJsonOnly(name) {
return '<script>const customerName = ' + JSON.stringify(name) + ';</script>'
}
// The safe version keeps the name out of the script. The page and its script
// never change; the script fetches the name as JSON and shows it as text.
const GREETING_PAGE =
'<p id="greeting"></p>' +
'<script>fetch("/order.json").then((response) => response.json())' +
'.then((order) => { document.getElementById("greeting").textContent = order.customerName })</script>'
// The name is not used here: it reaches the browser only through renderOrderJson.
export function renderGreetingSafe(name) {
return GREETING_PAGE
}
// The JSON response the safe page fetches, served as application/json.
export function renderOrderJson(name) {
return {
contentType: 'application/json',
body: JSON.stringify({ customerName: name }),
}
}
// Context 4a, URL: a search term inside a link the page builds.
export function renderSearchLinkUnsafe(term) {
return '<a href="/search?q=' + term + '">Search again</a>'
}
export function renderSearchLinkSafe(term) {
const href = '/search?q=' + encodeURIComponent(term)
return '<a href="' + encodeForQuotedAttribute(href) + '">Search again</a>'
}
// Context 4b, URL: a whole address the customer supplied as their website.
// The unsafe version does encode for the attribute. It does not check the scheme.
export function renderWebsiteLinkUnsafe(website) {
return '<a href="' + encodeForQuotedAttribute(website) + '">Website</a>'
}
export function renderWebsiteLinkSafe(website) {
return '<a href="' + encodeForQuotedAttribute(toAllowedLinkHref(website)) + '">Website</a>'
}
// Context 5, CSS: a progress bar whose width comes from the request.
export function renderProgressUnsafe(width) {
return '<div class="progress" style="width: ' + width + '"></div>'
}
// toAllowedWidth only returns digits and a percent sign, so the value
// cannot close the style attribute or add a declaration.
export function renderProgressSafe(width) {
return '<div class="progress" style="width: ' + toAllowedWidth(width) + '"></div>'
}
==== File 3 of 5: inspect.mjs ====
// inspect.mjs: string checks the tests use to judge each output.
// They read the HTML string the server would send. They do not run a browser.
// The marker: if it ever became markup, the only element it would make is an
// empty one carrying a data attribute set to a fixed word.
export const MARKER = '"></script><i data-xss="marker">'
export const MARKER_ELEMENT = '<i data-xss='
// The link marker: if a browser ever followed it, it would set the page
// title to a fixed word and do nothing else.
export const LINK_MARKER = "javascript:void(document.title='xss-marker')"
// Ordinary input that a correct fix must keep exactly as typed.
export const ORDINARY_TEXT = "O'Brien & Sons"
// The markup's skeleton: every <, > and " in order. A value that stays data
// cannot add to it, because the encoders turn those characters into entities.
export function readSkeleton(html) {
let skeleton = ''
for (const character of html) {
if (character === '<' || character === '>' || character === '"') skeleton += character
}
return skeleton
}
export function countOccurrences(text, search) {
return text.split(search).length - 1
}
// Reverses the five entities the encoders produce. & goes last, so an
// encoded entity is decoded once, not twice.
const ENTITY_TEXT = {
'<': '<',
'>': '>',
'"': '"',
''': "'",
'&': '&',
}
export function decodeHtml(text) {
let decoded = text
for (const entity of Object.keys(ENTITY_TEXT)) {
decoded = decoded.replaceAll(entity, ENTITY_TEXT[entity])
}
return decoded
}
// The text between the end of an opening tag and the next closing tag.
export function readTextBetween(html, openingTag, closingTag) {
const start = html.indexOf(openingTag) + openingTag.length
const end = html.indexOf(closingTag, start)
return html.slice(start, end)
}
// The value of a double-quoted attribute, read up to the next double quote,
// the character that closes it.
export function readAttribute(html, attributeName) {
const opening = attributeName + '="'
const start = html.indexOf(opening) + opening.length
const end = html.indexOf('"', start)
return decodeHtml(html.slice(start, end))
}
==== File 4 of 5: show.mjs ====
// show.mjs: prints what each context's unsafe and safe versions produce for
// the marker and for ordinary input. Nothing is sent anywhere or run.
import * as render from './render.mjs'
import { LINK_MARKER, MARKER, ORDINARY_TEXT } from './inspect.mjs'
function printCase(label, input, outputs) {
console.log(' Input (' + label + '): ' + input)
for (const [name, output] of outputs) {
console.log(' ' + (name + ':').padEnd(10) + ' ' + output)
}
}
console.log('1 HTML body')
for (const [label, input] of [['marker', MARKER], ['ordinary', ORDINARY_TEXT]]) {
printCase(label, input, [['Unsafe', render.renderNoteUnsafe(input)], ['Safe', render.renderNoteSafe(input)]])
}
console.log('2 HTML attribute')
for (const [label, input] of [['marker', MARKER], ['ordinary', ORDINARY_TEXT]]) {
printCase(label, input, [['Unsafe', render.renderNameFieldUnsafe(input)], ['Safe', render.renderNameFieldSafe(input)]])
}
console.log('3 JavaScript')
printCase('marker', MARKER, [
['Unsafe', render.renderGreetingUnsafe(MARKER)],
['JSON only', render.renderGreetingJsonOnly(MARKER)],
['Safe', render.renderGreetingSafe(MARKER)],
])
const response = render.renderOrderJson(MARKER)
console.log(' JSON response for the safe page, Content-Type ' + response.contentType + ':')
console.log(' ' + response.body)
console.log('4a URL, a search term inside a link')
for (const [label, input] of [['marker', MARKER], ['ordinary', ORDINARY_TEXT]]) {
printCase(label, input, [['Unsafe', render.renderSearchLinkUnsafe(input)], ['Safe', render.renderSearchLinkSafe(input)]])
}
console.log('4b URL, a whole address from the customer')
for (const [label, input] of [['link', LINK_MARKER], ['ordinary', 'https://example.com/menu']]) {
printCase(label, input, [['Unsafe', render.renderWebsiteLinkUnsafe(input)], ['Safe', render.renderWebsiteLinkSafe(input)]])
}
console.log('5 CSS')
for (const [label, input] of [['marker', MARKER], ['ordinary', '40%']]) {
printCase(label, input, [['Unsafe', render.renderProgressUnsafe(input)], ['Safe', render.renderProgressSafe(input)]])
}
==== File 5 of 5: encoding.test.mjs ====
// encoding.test.mjs: does the marker stay data in all five contexts?
// Run: node encoding.test.mjs unsafe (expect failures)
// node encoding.test.mjs safe (expect every test to pass)
// With no argument it tests the safe version, which is what node --test runs.
import assert from 'node:assert/strict'
import { test } from 'node:test'
import * as render from './render.mjs'
import {
LINK_MARKER,
MARKER,
MARKER_ELEMENT,
ORDINARY_TEXT,
countOccurrences,
decodeHtml,
readAttribute,
readSkeleton,
readTextBetween,
} from './inspect.mjs'
const versions = {
unsafe: {
note: render.renderNoteUnsafe,
nameField: render.renderNameFieldUnsafe,
greeting: render.renderGreetingUnsafe,
searchLink: render.renderSearchLinkUnsafe,
websiteLink: render.renderWebsiteLinkUnsafe,
progress: render.renderProgressUnsafe,
},
safe: {
note: render.renderNoteSafe,
nameField: render.renderNameFieldSafe,
greeting: render.renderGreetingSafe,
searchLink: render.renderSearchLinkSafe,
websiteLink: render.renderWebsiteLinkSafe,
progress: render.renderProgressSafe,
},
}
const version = process.argv[2] || 'safe'
const build = versions[version]
if (!build) throw new Error('Unknown version: ' + version)
// The marker must leave the markup exactly as an empty value does, and must
// not appear as an element.
function assertMarkerStaysData(renderContext) {
const withMarker = renderContext(MARKER)
const withEmptyValue = renderContext('')
assert.ok(!withMarker.includes(MARKER_ELEMENT), 'the marker became an element: ' + withMarker)
assert.equal(readSkeleton(withMarker), readSkeleton(withEmptyValue), 'the marker changed the markup')
}
test(version + ': 1 HTML body: the marker stays text', () => {
assertMarkerStaysData(build.note)
})
test(version + ': 1 HTML body: ordinary text reads back unchanged', () => {
const html = build.note(ORDINARY_TEXT)
const text = decodeHtml(readTextBetween(html, '<p class="note">', '</p>'))
assert.equal(text, ORDINARY_TEXT)
})
test(version + ': 2 HTML attribute: the marker stays inside the value', () => {
assertMarkerStaysData(build.nameField)
})
test(version + ': 2 HTML attribute: ordinary text reads back unchanged', () => {
const html = build.nameField(ORDINARY_TEXT)
assert.equal(readAttribute(html, 'value'), ORDINARY_TEXT)
})
test(version + ': 3 JavaScript: the marker cannot end the script block', () => {
const html = build.greeting(MARKER)
assert.equal(countOccurrences(html, '</script'), 1, 'the script block ends early: ' + html)
assertMarkerStaysData(build.greeting)
})
test(version + ': 3 JavaScript: the script text is the same for every name', () => {
assert.equal(build.greeting(MARKER), build.greeting(ORDINARY_TEXT), 'the name is written into the script')
})
// Only the safe version has a JSON response, so this test runs only for it.
if (version === 'safe') {
test('safe: 3 JavaScript: the JSON response carries the marker as data', () => {
const response = render.renderOrderJson(MARKER)
assert.equal(response.contentType, 'application/json')
assert.equal(JSON.parse(response.body).customerName, MARKER)
})
}
test(version + ': 4a URL: the marker stays inside the link', () => {
assertMarkerStaysData(build.searchLink)
})
test(version + ': 4a URL: an ordinary search term reads back unchanged', () => {
const href = readAttribute(build.searchLink(ORDINARY_TEXT), 'href')
const searchTerm = new URL(href, 'https://bakery.example').searchParams.get('q')
assert.equal(searchTerm, ORDINARY_TEXT)
})
test(version + ': 4b URL: a javascript: link is not written into the page', () => {
const href = readAttribute(build.websiteLink(LINK_MARKER), 'href')
assert.ok(href === '#' || href.startsWith('https:') || href.startsWith('http:'), 'the link is: ' + href)
})
test(version + ': 4b URL: an ordinary https address is kept', () => {
const href = readAttribute(build.websiteLink('https://example.com/menu'), 'href')
assert.equal(href, 'https://example.com/menu')
})
test(version + ': 5 CSS: the marker stays inside the style value', () => {
assertMarkerStaysData(build.progress)
})
test(version + ': 5 CSS: an ordinary width is kept', () => {
const html = build.progress('40%')
assert.equal(readAttribute(html, 'style'), 'width: 40%')
})
STEP 1: see what each version produces
Command: node show.mjs
1 HTML body
Input (marker): "></script><i data-xss="marker">
Unsafe: <p class="note">"></script><i data-xss="marker"></p>
Safe: <p class="note">"></script><i data-xss="marker"></p>
Input (ordinary): O'Brien & Sons
Unsafe: <p class="note">O'Brien & Sons</p>
Safe: <p class="note">O'Brien & Sons</p>
2 HTML attribute
Input (marker): "></script><i data-xss="marker">
Unsafe: <input name="name" value=""></script><i data-xss="marker">">
Safe: <input name="name" value=""></script><i data-xss="marker">">
Input (ordinary): O'Brien & Sons
Unsafe: <input name="name" value="O'Brien & Sons">
Safe: <input name="name" value="O'Brien & Sons">
3 JavaScript
Input (marker): "></script><i data-xss="marker">
Unsafe: <script>const customerName = ""></script><i data-xss="marker">";</script>
JSON only: <script>const customerName = "\"></script><i data-xss=\"marker\">";</script>
Safe: <p id="greeting"></p><script>fetch("/order.json").then((response) => response.json()).then((order) => { document.getElementById("greeting").textContent = order.customerName })</script>
JSON response for the safe page, Content-Type application/json:
{"customerName":"\"></script><i data-xss=\"marker\">"}
4a URL, a search term inside a link
Input (marker): "></script><i data-xss="marker">
Unsafe: <a href="/search?q="></script><i data-xss="marker">">Search again</a>
Safe: <a href="/search?q=%22%3E%3C%2Fscript%3E%3Ci%20data-xss%3D%22marker%22%3E">Search again</a>
Input (ordinary): O'Brien & Sons
Unsafe: <a href="/search?q=O'Brien & Sons">Search again</a>
Safe: <a href="/search?q=O'Brien%20%26%20Sons">Search again</a>
4b URL, a whole address from the customer
Input (link): javascript:void(document.title='xss-marker')
Unsafe: <a href="javascript:void(document.title='xss-marker')">Website</a>
Safe: <a href="#">Website</a>
Input (ordinary): https://example.com/menu
Unsafe: <a href="https://example.com/menu">Website</a>
Safe: <a href="https://example.com/menu">Website</a>
5 CSS
Input (marker): "></script><i data-xss="marker">
Unsafe: <div class="progress" style="width: "></script><i data-xss="marker">"></div>
Safe: <div class="progress" style="width: 0%"></div>
Input (ordinary): 40%
Unsafe: <div class="progress" style="width: 40%"></div>
Safe: <div class="progress" style="width: 40%"></div>
Reading the output:
1 and 2 In the unsafe strings the paragraph or the attribute closes early, and the marker's element follows as markup. The safe versions turn every <, >, " and ' into an entity, so the marker stays inside the paragraph or the value.
3 In the unsafe string the marker's closing script tag comes before the script's own, so the script block ends there. JSON.stringify() puts backslashes before the quotes, and the marker's closing script tag is still in the string. The safe page is identical for every name; the name travels in the JSON response as a JSON string.
4a The unsafe link breaks out of the href, and with the ordinary name the & starts a second query parameter. The safe link percent-encodes the value. encodeURIComponent() leaves the apostrophe alone, and the attribute encoder turns it into '.
4b The attribute encoding is correct, and the href still begins with javascript:. Encoding cannot help here, because the danger is the scheme. The safe version replaces it with #.
5 In the unsafe string the style attribute closes early and the element follows. The safe version rejects the marker and uses 0%, and keeps 40%.
STEP 2: run the tests against the unsafe version
Command: node encoding.test.mjs unsafe
✖ unsafe: 1 HTML body: the marker stays text (0.968333ms)
✔ unsafe: 1 HTML body: ordinary text reads back unchanged (0.107209ms)
✖ unsafe: 2 HTML attribute: the marker stays inside the value (0.06075ms)
✔ unsafe: 2 HTML attribute: ordinary text reads back unchanged (0.064791ms)
✖ unsafe: 3 JavaScript: the marker cannot end the script block (0.31475ms)
✖ unsafe: 3 JavaScript: the script text is the same for every name (0.162042ms)
✖ unsafe: 4a URL: the marker stays inside the link (0.054667ms)
✖ unsafe: 4a URL: an ordinary search term reads back unchanged (0.559625ms)
✖ unsafe: 4b URL: a javascript: link is not written into the page (0.142917ms)
✔ unsafe: 4b URL: an ordinary https address is kept (0.09425ms)
✖ unsafe: 5 CSS: the marker stays inside the style value (0.066958ms)
✔ unsafe: 5 CSS: an ordinary width is kept (0.0475ms)
ℹ tests 12
ℹ suites 0
ℹ pass 4
ℹ fail 8
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 6.536667
✖ failing tests:
test at encoding.test.mjs:52:1
✖ unsafe: 1 HTML body: the marker stays text (0.968333ms)
AssertionError [ERR_ASSERTION]: the marker became an element: <p class="note">"></script><i data-xss="marker"></p>
(stack trace and error properties removed here)
test at encoding.test.mjs:62:1
✖ unsafe: 2 HTML attribute: the marker stays inside the value (0.06075ms)
AssertionError [ERR_ASSERTION]: the marker became an element: <input name="name" value=""></script><i data-xss="marker">">
(stack trace and error properties removed here)
test at encoding.test.mjs:71:1
✖ unsafe: 3 JavaScript: the marker cannot end the script block (0.31475ms)
AssertionError [ERR_ASSERTION]: the script block ends early: <script>const customerName = ""></script><i data-xss="marker">";</script>
2 !== 1
(stack trace and error properties removed here)
test at encoding.test.mjs:77:1
✖ unsafe: 3 JavaScript: the script text is the same for every name (0.162042ms)
AssertionError [ERR_ASSERTION]: the name is written into the script
+ actual - expected
+ '<script>const customerName = ""></script><i data-xss="marker">";</script>'
- `<script>const customerName = "O'Brien & Sons";</script>`
(stack trace and error properties removed here)
test at encoding.test.mjs:90:1
✖ unsafe: 4a URL: the marker stays inside the link (0.054667ms)
AssertionError [ERR_ASSERTION]: the marker became an element: <a href="/search?q="></script><i data-xss="marker">">Search again</a>
(stack trace and error properties removed here)
test at encoding.test.mjs:94:1
✖ unsafe: 4a URL: an ordinary search term reads back unchanged (0.559625ms)
AssertionError [ERR_ASSERTION]: Expected values to be strictly equal:
+ actual - expected
+ "O'Brien "
- "O'Brien & Sons"
^
(stack trace and error properties removed here)
test at encoding.test.mjs:100:1
✖ unsafe: 4b URL: a javascript: link is not written into the page (0.142917ms)
AssertionError [ERR_ASSERTION]: the link is: javascript:void(document.title='xss-marker')
(stack trace and error properties removed here)
test at encoding.test.mjs:110:1
✖ unsafe: 5 CSS: the marker stays inside the style value (0.066958ms)
AssertionError [ERR_ASSERTION]: the marker became an element: <div class="progress" style="width: "></script><i data-xss="marker">"></div>
(stack trace and error properties removed here)
The process exits with code 1, so a pipeline step that runs these tests fails. Eight of the twelve tests fail. The four that pass all use ordinary input. One ordinary-input test fails as well: the search term O'Brien & Sons loses everything from the & onwards, with no attacker involved.
STEP 3: run them against the safe version
Command: node encoding.test.mjs safe
✔ safe: 1 HTML body: the marker stays text (0.765667ms)
✔ safe: 1 HTML body: ordinary text reads back unchanged (0.08425ms)
✔ safe: 2 HTML attribute: the marker stays inside the value (0.057333ms)
✔ safe: 2 HTML attribute: ordinary text reads back unchanged (0.049875ms)
✔ safe: 3 JavaScript: the marker cannot end the script block (0.068ms)
✔ safe: 3 JavaScript: the script text is the same for every name (0.044292ms)
✔ safe: 3 JavaScript: the JSON response carries the marker as data (0.063041ms)
✔ safe: 4a URL: the marker stays inside the link (0.527333ms)
✔ safe: 4a URL: an ordinary search term reads back unchanged (0.355417ms)
✔ safe: 4b URL: a javascript: link is not written into the page (0.128792ms)
✔ safe: 4b URL: an ordinary https address is kept (0.065209ms)
✔ safe: 5 CSS: the marker stays inside the style value (0.113084ms)
✔ safe: 5 CSS: an ordinary width is kept (0.057792ms)
ℹ tests 13
ℹ suites 0
ℹ pass 13
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 6.72575
The process exits with code 0. With no argument the file tests the safe version, so node --test finds it by its .test.mjs name and runs the same thirteen tests.
STEP 4: point the tests at your own code
1. Replace each render function with a call to your own template or component, rendered to a string the way your server sends it.
2. Keep the marker test and the ordinary-input test for every context your pages use, and add a case for each place a value is shown, staff and admin screens included.
3. Run them in the pipeline that deploys your site.
4. Strings rendered on the server do not cover values that script in the browser inserts. Use Part 2 to find those, and Part 3 to check them.
================================================================
PART 2: DOM SOURCE-TO-SINK MAP
================================================================
A source is where script in the page reads data an attacker can influence. A sink is an API that turns a string into markup or code. Follow each source in your front-end code to the sink it reaches, then replace the sink.
SOURCES
S1 The page address: location.href, document.URL and the query string.
Anyone who sends a link chooses it.
Source: WSTG-CLNT-01, Testing for DOM-Based Cross Site Scripting.
S2 The fragment after #: location.hash.
It is not sent to the server, so server-side checks do not see it.
Sources: WSTG-CLNT-01; OWASP DOM based XSS Prevention Cheat Sheet, variant analysis example.
S3 Messages from other windows: the data of a postMessage message.
Discard messages from an untrusted origin or with invalid syntax.
Source: ASVS 5.0 requirement 3.5.5.
S4 Data your own API returns, including values other users stored.
Stored data is still untrusted when it comes back.
Sources: OWASP XSS Prevention Cheat Sheet, XSS Defense Philosophy; MITRE CWE-79, stored XSS (Type 2).
S5 Form field values read back through .value.
Encoding applied by the server is reversed when the value is read.
Source: OWASP DOM based XSS Prevention Cheat Sheet, Encoding Misconceptions.
SINKS, AND WHAT TO USE INSTEAD
K1 element.innerHTML, element.outerHTML
Parses the string as HTML.
Instead: textContent for text. When markup has to render, a maintained sanitiser such as DOMPurify, or Element.setHTML() where the browser supports it.
Sources: MDN, Element: innerHTML property; MDN, Node: textContent property; OWASP DOM based XSS Prevention Cheat Sheet, Guideline #4; OWASP XSS Prevention Cheat Sheet, Safe Sinks and its HTML sanitisation section; MDN, HTML Sanitizer API (limited availability).
K2 element.insertAdjacentHTML()
Parses its input as HTML and does no sanitising.
Instead: insertAdjacentText(), or textContent.
Source: MDN, Element: insertAdjacentHTML() method.
K3 document.write(), document.writeln()
Parses its input as HTML. MDN marks write() deprecated and strongly discourages it.
Instead: build elements with createElement() and fill them with textContent.
Sources: MDN, Document: write() method; OWASP DOM based XSS Prevention Cheat Sheet, Guidelines #3 and #4 and Rule #6; MDN, Node: textContent property.
K4 eval(), new Function(), and setTimeout() or setInterval() given a string
Runs the string as JavaScript.
Instead: pass a function to setTimeout() and setInterval(), parse JSON with JSON.parse(), and do not run untrusted text as code.
Sources: MDN, eval(); MDN, Window: setTimeout() method; MDN, Window: setInterval() method; OWASP DOM based XSS Prevention Cheat Sheet, Guidelines #9 and #10; ASVS 5.0 requirement 1.3.2.
K5 setAttribute() with an event-handler name such as onclick, or with srcdoc
The value is run as code or parsed as HTML.
Instead: addEventListener() with a trusted function, and attribute names fixed in the code.
Sources: MDN, Element: setAttribute() method; OWASP XSS Prevention Cheat Sheet, Output Encoding for HTML Attribute Contexts.
K6 A link or navigation built from input: an a element's href, an iframe's src, an assignment to window.location
A javascript: URL runs its code when the browser navigates to it.
Instead: parse the address with URL() and allow only http: and https:.
Sources: MDN, javascript: URLs; MDN, URL() constructor; MDN, URL: protocol property; OWASP XSS Prevention Cheat Sheet, rules summary for an untrusted URL in a src or href attribute, for allowing only http and https URLs; ASVS 5.0 requirement 1.2.2, for permitting only safe URL protocols, for example disallowing javascript: or data:.
K7 A script element's src, text or textContent, and innerText set on a script element
Loads or runs the value as script.
Instead: fixed script addresses, and no untrusted data in script content.
Sources: MDN, Trusted Types API, injection sinks; OWASP DOM based XSS Prevention Cheat Sheet, Usually Safe Methods.
K8 Style text built from input, in a style attribute or a style sheet
Input may alter the intended CSS syntax.
Instead: element.style.setProperty() with a fixed property name and a value from an allow-list for that property.
Source: OWASP XSS Prevention Cheat Sheet, Output Encoding for CSS Contexts.
K9 React's dangerouslySetInnerHTML
Overrides the element's innerHTML.
Instead, as this page's own advice: pass the value as ordinary children rather than as HTML. Where markup must render, use only trusted and sanitised data, and create the {__html} object as close as possible to where the HTML is generated, as React's reference recommends.
Sources for the risk and for the {__html} placement: React DOM reference, Common components; OWASP XSS Prevention Cheat Sheet, Framework Security.
K10 object[key] or window[key] with a key taken from input
Can let an attacker subvert the object's internal and external attributes.
Instead: add a level of indirection, such as checking the key against the names you expect.
Source: OWASP DOM based XSS Prevention Cheat Sheet, Guidelines #6 and #8.
================================================================
PART 3: BROWSER CHECKS BEFORE AND AFTER THE FIX
================================================================
These are steps for you to run in your own browser, on your own code. They are not results captured for this page. Use a local or staging copy with test accounts and test records, never real customers' data.
BEFORE YOU START
- List each place you will test: the field, URL parameter or stored record, and every page that displays it, staff and admin screens included.
- Open the browser's developer tools on the page that displays the value. You need the element view, the console and the network view.
B1 Did the value become an element? Contexts 1, 2, 3, 4a and 5.
Put the marker into the input, save or submit it, and open the page that shows it. In the console, run:
document.querySelectorAll('[data-xss]').length
Before the fix: 1 or more means the marker became markup.
After the fix: 0. Where the value is displayed, it shows as the characters you typed.
B2 Server or browser?
Open the page source, which is what the server sent, and search it for data-xss.
If the source shows the marker encoded (">< and so on) and B1 still finds an element, script in the page turned it into markup. Find the sink with Part 2.
If the source shows the marker raw, the server template needs the fix for its context.
B3 Did the script block end early? Context 3.
In the page source, find the script that held the value.
Before the fix: the page source shows the marker's closing script tag inside the script, ahead of the script's own closing tag.
After the fix: no script block holds customer data. In the network view, the value arrives in a response whose Content-Type is application/json.
B4 Is there a javascript: link on the page? Context 4b.
Put the link marker into the website field, save it, and open the page that shows the link. Do not click it. In the console, run:
document.querySelectorAll('a[href^="javascript:" i]').length
MDN says the case sensitivity of attribute values in a selector depends on the document language, and that the i before the closing bracket makes the comparison case-insensitive for ASCII characters. Also read the link's href in the element view.
Before the fix: 1 or more.
After the fix: 0, and the link's href is # or the http or https address.
B5 DOM-based XSS through the fragment. Sources S1 and S2.
Add # and then the marker to the end of the page address, load it, and repeat B1. The fragment is not sent to the server, so a positive result here points at script in the page.
B6 Content Security Policy, reported before it is enforced.
Send the policy in a Content-Security-Policy-Report-Only header on the staging copy, reload, and read the violation reports in the console before you enforce it.
Keep B1 to B5 as the test of the fix. OWASP's CSP cheat sheet says a policy does not prevent an application from containing vulnerabilities, but it can make those vulnerabilities significantly more difficult for an attacker to exploit.
B7 Trusted Types, reported before it is enforced.
Add require-trusted-types-for 'script' to the report-only policy and use the pages that take input. Read the reports in the console: each points to code that passes a plain string to an injection sink. Replace it using Part 2. MDN says Trusted Types might not work in older browsers, so run this check in a current one.
RECORD THE RESULT
For each check, write down the input, the page, the result before and after the fix, and the browser and version you used.
EXPECTED RESULTS AT A GLANCE
B1 Contexts 1, 2, 3, 4a, 5 Before: count of 1 or more After: 0, value shown as typed
B2 All contexts Before: marker raw in the source After: marker encoded, or absent (context 3)
B3 Context 3 Before: block ends at the marker After: no customer data in any script block
B4 Context 4b Before: count of 1 or more After: 0, href is # or an http or https address
B5 DOM-based Before: count of 1 or more After: 0
B6 CSP, second layer Before: reports in the console After: policy enforced, and B1 to B5 still need the fix
B7 Trusted Types Before: reports in the console After: no reports from your own codeWhat 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.
Text between two tags, such as an order note in a paragraph. The cheat sheet's rule is HTML entity encoding, and it lists five characters: & becomes &, < becomes <, > becomes >, " becomes " and ' becomes '. When script in the browser does the inserting, it says to assign the text to the textContent property of an ordinary element, such as a div, which creates a text node without parsing HTML, and to pass the original text rather than encoding it first.
A value inside an attribute, such as a name filled into a form field. The cheat sheet says to surround the value with double or single quotes and use the framework's or library's attribute encoder, to keep element and attribute names fixed, and that attributes holding URLs, CSS, HTML or JavaScript need the controls for those contexts as well.
In the browser, setAttribute("title", value) assigns the value directly without HTML-encoding it, so the cheat sheet says not to encode it first, and to keep the attribute name fixed, because event-handler attributes and srcdoc can interpret their values as code or HTML.
Data a script needs, such as the customer's name for a greeting. The cheat sheet says not to insert untrusted code, identifiers or expressions at all. Where a server template has to put string data inside an inline script, it asks for a maintained encoder documented for both the JavaScript string and the enclosing HTML script, rather than escaping quotes yourself.
The DOM based XSS cheat sheet warns that JSON.stringify() is not an output-encoding function: JSON embedded in an inline script needs an encoder that also protects the enclosing HTML script context, including literal </script sequences.
It prefers a separate response with Content-Type: application/json that the page parses with JSON.parse(). The suite takes that route: the page and its script never change, and the name arrives as JSON and is shown with textContent.
Two different jobs share this context. When your code builds a link and a value goes inside it, such as a search term in a query string, the XSS cheat sheet says to URL-encode the value, with encodeURIComponent() in JavaScript, and then apply HTML attribute encoding, because the URL sits in an href attribute.
MDN's encodeURIComponent() reference lists the characters it leaves alone, and the apostrophe is one of them, which is one reason the attribute step still matters.
When someone else supplies the whole address, such as the website field on a profile, encoding is not enough. MDN explains that a javascript: URL in an a element's href executes its code when the browser attempts to navigate to it.
The XSS cheat sheet's sample defence for an untrusted URL in an href or src attribute lists canonicalising the input, URL validation, safe URL verification, allowing only http and https URLs, and an attribute encoder.
ASVS 5.0 requirement 1.2.2 asks for two things: when URLs are built dynamically, untrusted data is encoded according to its context, and only safe URL protocols are permitted, for example by disallowing javascript: or data:.
A value inside a style, such as a progress bar's width. The XSS cheat sheet says not to interpolate untrusted data directly into CSS source, including selectors, property names or declaration blocks, and that placing data inside a property value does not by itself make arbitrary input safe.
When dynamic styling is needed, it says to use a CSSOM API such as element.style.setProperty() with a fixed property name and a value constrained by an allow-list for that property. For a CSS value in a style attribute, its rules summary lists strict structural validation, CSS hex encoding and good design of CSS features.
The suite accepts only a whole number from 0 to 100 followed by a percent sign, and falls back to 0% for anything else.
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.
A Content Security Policy, delivered in a response header, tells the browser which resources, JavaScript above all, the page may load. OWASP's CSP cheat sheet says the ways it defends against XSS include restricting inline scripts, scripts loaded from arbitrary servers and text-to-JavaScript functions such as eval, and calls a strong policy an effective second layer of protection, especially against XSS.
The same cheat sheet says CSP should not be relied on as the only defensive mechanism against XSS, and the XSS cheat sheet adds that it is easy to make mistakes in the implementation, so it should not be the primary defence. MDN's CSP guide says setting a CSP is not an alternative to sanitising input.
For XSS, MDN describes the recommended practice as a strict CSP, built on nonce- or hash-based fetch directives, and its nonce-based example also sets object-src 'none' and base-uri 'none'. It warns against 'unsafe-inline', which it says defeats much of the purpose of having a CSP.
ASVS 5.0 requirement 3.4.3, at Level 2, asks for a policy that includes object-src 'none' and base-uri 'none' and defines either an allow-list or nonces or hashes, and at Level 3 for a per-response policy with nonces or hashes.
Two practical notes. MDN's CSP guide says a nonce must be different for every HTTP response and must not be predictable, which in Next.js means dynamic rendering: the Next.js CSP guide says static pages are generated at build time, when no request or response headers exist, so no nonce can be injected.
And a policy can be trialled with the Content-Security-Policy-Report-Only header, which OWASP's CSP cheat sheet says is not enforced, while violation reports are still printed to the console.
A Content-Security-Policy header can also carry the frame-ancestors directive against framing attacks such as clickjacking, which has its own guide in this library.
The HttpOnly cookie attribute keeps a cookie away from script. MDN's Set-Cookie reference says it forbids JavaScript from accessing the cookie, for example through document.cookie, and also that an HttpOnly cookie is still sent with requests JavaScript starts, such as fetch().
So it keeps a session cookie out of an injected script's hands, but the script can still send requests that carry the cookie. The XSS cheat sheet says cookie attributes try to limit the impact of an XSS attack but do not prevent the malicious content from running or address the root cause, and CWE-79 rates HttpOnly on the session cookie as defence in depth.
ASVS 5.0 requirement 3.3.4, at Level 2, asks that a cookie not meant to be accessible to client-side scripts, such as a session token, has the HttpOnly attribute set. Cookie attributes as a whole, Secure and SameSite included, are covered in the cookie security guide.
Trusted Types targets DOM-based XSS. With the require-trusted-types-for 'script' directive in a CSP, MDN says injection sink functions such as the innerHTML setter reject strings and accept only typed values created by Trusted Type policies, and that passing a string throws a TypeError. That turns a string reaching a covered sink into an error you can see.
MDN marks the Trusted Types API as Baseline 2026, newly available: since February 2026 it works across the latest devices and browser versions, and it might not work in older devices or browsers.
It does not sanitise anything by itself. MDN says the API supplies no policy or transformation functions of its own, and the XSS cheat sheet says policies must apply suitable validation or sanitisation, that overly permissive policies can undermine the protection, and that a polyfill does not give equivalent native enforcement in browsers without support.
MDN recommends a default policy only while legacy code that passes strings to sinks is moved over to trusted types.
A web application firewall can add a layer in front of the site. The XSS cheat sheet says it cannot reliably prevent all XSS attacks or fix vulnerable code, and may miss DOM-based XSS that happens entirely in the browser. CWE-79 rates a firewall's effectiveness as moderate and suggests one where the code cannot be fixed, as an emergency measure, or for defence in depth.
Cross-site request forgery is a separate problem with its own guide. ASVS 5.0 frames it as making sure a request to sensitive functionality was initiated by the application itself or a trusted party, and was not forged by an attacker.
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.