What Is XSS?
XSS (Cross-Site Scripting) is a vulnerability that allows an attacker to inject malicious JavaScript code into a web page viewed by other users. The script runs in the victim's browser with the rights of the target site — a site the victim trusts. It is one of the most widespread vulnerabilities on the web, regularly ranked in the OWASP (Open Worldwide Application Security Project) top 10.
The Three Types of XSS
Stored XSS (Persistent): the malicious script is injected into the site's database — via a blog comment, forum post, or profile field. Each time the page is visited, the script is reloaded and executed for all visitors. This is the most dangerous type because no trap link is needed.
Reflected XSS: the script is inserted into a URL, then returned as-is in the server response. The attacker sends a trap link to the victim; when they click it, the script executes immediately. Classic example: a search engine displaying "You searched for: [term]" without encoding the term.
DOM-based XSS: the manipulation happens entirely client-side, without going through the server. The malicious script modifies the DOM (Document Object Model — the in-memory representation of the HTML page) directly via JavaScript. It is harder to detect because server logs reveal nothing unusual.
Consequences of an XSS Attack
An injected script can:
- Steal session cookies to impersonate the victim.
- Log keystrokes to capture passwords and card numbers.
- Redirect to a phishing site.
- Deface the page or display fake alerts.
- Download malware via drive-by downloads.
Main Protections
HTML output encoding: any data displayed in HTML must be encoded. The character < becomes <, preventing script interpretation. This is the fundamental rule: never trust user input.
Content-Security-Policy (CSP): this HTTP header defines which scripts can run on the page. By forbidding inline scripts (scripts directly in the HTML) and allowing only your trusted domains, CSP neutralizes the majority of XSS attacks even if injection occurs.
Content-Security-Policy: default-src 'self'; script-src 'self' https://cdn.example.com
Input validation and sanitization: validate the expected format server-side (length, allowed characters). For user-generated HTML (rich-text editors), use a sanitization library like DOMPurify on the JavaScript side, which removes dangerous tags and attributes while preserving legitimate formatting.
HTTPOnly attribute on cookies: a cookie marked HttpOnly is not accessible via JavaScript. Even with a successful XSS attack, the attacker cannot steal the session cookie.
Check Your XSS Exposure
An automated security audit analyzes your HTTP headers, detects the absence of CSP, and flags risky configurations. Run a free audit to find out your site's level of protection against XSS attacks.