Stored Cross-Site Scripting (XSS) happens when a website saves untrusted input, like a comment, and later shows it to other people without handling it safely. Their browsers then run the attacker’s code. Try it below on a fake comment board, then switch on the defences.
The attacker posts code instead of a normal comment.
The site saves it in its database, unchanged.
Every visitor who opens the page receives that code as part of the HTML.
The visitor’s browser runs it, as if the site itself wrote it.
This is what the server saves. Notice it keeps the raw text; the danger is in how it’s displayed later.
Each column is a setting in the lab. Each row is a payload from the list. Try them and compare with this table.
| Payload | None | Output encoding | Sanitizer | CSP |
|---|
Key lesson: CSP blocks the scripts, but the page can still be defaced with injected HTML and CSS. Encode or sanitize first, and add CSP as a second layer (defence in depth).
// renders the stored comment as HTML comments.forEach(c => { board.innerHTML += `<p>${c.name}: ${c.text}</p>`; });
// renders it as plain text comments.forEach(c => { const p = document.createElement('p'); p.textContent = `${c.name}: ${c.text}`; board.append(p); }); // + server header (second layer): Content-Security-Policy: script-src 'self'
Treat user content as text, not HTML. Use textContent or your framework’s default escaping (React, Vue and Angular do this by default).
If users really need formatting, run it through a proven allowlist sanitizer such as DOMPurify. Never write your own regex filter.
Block inline scripts and unknown sources, so that one missed bug can’t run code.
Check length, type and format on the server. This reduces attack surface but is not a replacement for encoding.
Set session cookies to HttpOnly, Secure and SameSite, so scripts can’t read them.
Watch for innerHTML, dangerouslySetInnerHTML, v-html and eval. Use them only with sanitized data.