Back to all terms
Securityintermediate

XSS (Cross-Site Scripting) Prevention

Techniques to prevent attackers from injecting malicious scripts into web pages viewed by other users.

Also known as: cross-site scripting, XSS mitigation, script injection prevention

Description

Cross-Site Scripting (XSS) is one of the most prevalent web security vulnerabilities, allowing attackers to inject client-side scripts into web pages. These scripts execute in the context of other users' browsers, enabling session hijacking, credential theft, defacement, and redirection to malicious sites. XSS vulnerabilities arise when applications include untrusted data in web output without proper validation or escaping.

There are three primary types of XSS: Stored XSS, where malicious input is persisted on the server and served to other users; Reflected XSS, where the payload is embedded in a URL or request and reflected back in the response; and DOM-based XSS, where the vulnerability exists entirely in client-side JavaScript that improperly handles user input. Each variant requires specific mitigation strategies.

Prevention involves a layered approach: context-aware output encoding (HTML entity encoding, JavaScript escaping, URL encoding), Content Security Policy headers that restrict script execution sources, input validation with allowlist patterns, use of modern frameworks that auto-escape by default (React, Angular), and avoiding dangerous APIs like innerHTML or document.write. A robust defense combines all of these techniques rather than relying on any single measure.

Prompt Snippet

Implement context-aware output encoding at every rendering boundary: HTML entity encoding for element content, JavaScript string escaping for script contexts, URL-encoding for href/src attributes, and CSS escaping for style contexts. Use a strict Content Security Policy with script-src 'nonce-{random}' to block inline script execution, and avoid using dangerouslySetInnerHTML, v-html, or [innerHTML] bindings. Integrate DOMPurify for any rich-text rendering and validate all user inputs server-side with allowlist patterns before persistence.

Tags

xssinjectionclient-sideoutput-encodingcsp