XSS is a broad class of web application vulnerabilities where an attacker injects attacker-controlled script (usually JavaScript) into pages viewed by other users. That script runs in the victim’s browser with the site’s origin privileges and can steal cookies/session tokens, perform actions on behalf of the user, or modify page content.
Types of XSS
-
Reflected (non-persistent)
Malicious input is embedded in a URL or request and immediately reflected in the server response (e.g., search results, error message). Usually exploited via a crafted link. -
Stored (persistent)
Attacker input is saved server-side (comments, profile fields, message boards) and served to other users later — more dangerous because it can affect many victims. -
DOM-based
The vulnerability exists in client-side code: JavaScript reads user-controlled data (URL fragment, query, or window.location) and writes it into the DOM unsafely. No server-side reflection necessary.
Core defenses (high level, prioritized)
-
Output encoding/escaping — Always encode user data for the context where it’s inserted: HTML body, attribute, URL, JavaScript, or CSS contexts. Use established libraries.
-
HTML body: escape
<,>,&,"and'(as required). -
HTML attribute: additionally encode quotes and handle attribute contexts.
-
JavaScript context: use safe APIs instead of string concatenation.
-
-
Use safe templating frameworks / avoid raw
innerHTML
Frameworks and templating engines that auto-escape (React, Angular, Twig, Mustache) reduce risk. When you must insert HTML, sanitize it with a well-maintained sanitizer (DOMPurify for browser). -
Content Security Policy (CSP)
A strong CSP (e.g., disallow inline scripts, specify script-src) mitigates impact by blocking inline/external scripts. CSP is defense-in-depth, not a replacement for escaping. -
HTTP-only & Secure cookies
HttpOnlyprevents client JavaScript from reading cookie values;Secureensures cookies sent only over HTTPS. -
Input validation (as secondary)
Validate input shape and length (whitelisting where appropriate). But do not rely on input validation alone for XSS prevention — escaping on output is primary. -
Avoid dangerous APIs
Avoideval,new Function(),innerHTMLwith untrusted strings,document.write,setTimeout(string), etc.
