XSS (Cross-Site Scripting) Prevention
Techniques to prevent attackers from injecting malicious scripts into web pages viewed by other users.
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
Related Terms
Content Security Policy (CSP)
An HTTP response header that allows fine-grained control over which resources a browser is allowed to load and execute for a page.
Output Encoding
The process of converting untrusted data into a safe representation before rendering it in a specific output context.
Input Validation & Sanitization
The practice of verifying and cleaning all user-supplied data before processing to prevent injection attacks and data corruption.
Security Headers
HTTP response headers that instruct browsers to enable security mechanisms, reducing the attack surface of web applications.