XSS (Cross-Site Scripting)
A critical web vulnerability where untrusted input injects malicious JavaScript into a trusted page, executing inside the victim's browser origin
Table of Contents
Structure Diagram
What is XSS (Cross-Site Scripting)?
A critical web vulnerability where untrusted input injects malicious JavaScript into a trusted page, executing inside the victim's browser origin. It is a core concept in Auth & Security within Web Dev.
Core Principles
Cross-Site Scripting (XSS) occurs when an application renders untrusted user input into HTML or DOM sinks without proper encoding or sanitization, allowing an attacker's JavaScript to run inside the victim's browser under the trusted site's origin.
It comes in three forms: Stored XSS (persisted in a database), Reflected XSS (echoed from a URL/query), and DOM-based XSS (introduced by unsafe client-side sinks like innerHTML). Once executed, attacker scripts can steal tokens from localStorage, hijack sessions, or impersonate the user.
Practical Takeaways
- Rely on framework auto-escaping: Modern templates (React JSX, Vue) escape text nodes by default. Avoid
dangerouslySetInnerHTML,v-html,innerHTML, andeval. - Sanitize rich HTML with allowlists: Whenever user HTML or Markdown is required, sanitize it with DOMPurify (never regex) and reject
javascript:URLs inhref/srcattributes. - Defense in depth: Store auth credentials in
HttpOnlycookies rather thanlocalStorage, and enforce a strict CSP to block unauthorized inline scripts.
Notable Examples
- UGC comments and Markdown editors: Combining
DOMPurifywith nonce-based CSP headers to neutralize embedded payloads. - Safe redirect handling: Validating
nextredirect URLs againsthttps:/relative-path allowlists to blockjavascript:URI execution.