// Web security · Interactive lab

Break it safely.
Then fix it.

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.

⚠️
Safe by design. The victim’s browser is a sandboxed frame with no access to this page, your cookies or the internet; payloads only change the fake board. Only test websites you own or have written permission to test.
01Inject

The attacker posts code instead of a normal comment.

02Store

The site saves it in its database, unchanged.

03Serve

Every visitor who opens the page receives that code as part of the HTML.

04Execute

The visitor’s browser runs it, as if the site itself wrote it.

1 · Attackerposts a comment
2 · Databasestored as-is

This is what the server saves. Notice it keeps the raw text; the danger is in how it’s displayed later.

3 · Victim’s browservisitor: alice
https://kigali-blog.example/post/42#comments
Post a comment to see how it renders.
Security log
// Results

Which defence stops what?

Each column is a setting in the lab. Each row is a payload from the list. Try them and compare with this table.

PayloadNoneOutput encodingSanitizerCSP

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).

// The fix in code

One line makes the difference.

✗ Vulnerable
// renders the stored comment as HTML
comments.forEach(c => {
  board.innerHTML +=
    `<p>${c.name}: ${c.text}</p>`;
});
✓ Fixed
// 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'
// Prevention checklist

How real sites stay safe

Encode output

Treat user content as text, not HTML. Use textContent or your framework’s default escaping (React, Vue and Angular do this by default).

Sanitize rich text

If users really need formatting, run it through a proven allowlist sanitizer such as DOMPurify. Never write your own regex filter.

Content-Security-Policy

Block inline scripts and unknown sources, so that one missed bug can’t run code.

Validate input

Check length, type and format on the server. This reduces attack surface but is not a replacement for encoding.

Protect cookies

Set session cookies to HttpOnly, Secure and SameSite, so scripts can’t read them.

Avoid dangerous APIs

Watch for innerHTML, dangerouslySetInnerHTML, v-html and eval. Use them only with sanitized data.