XSS (Cross-Site Scripting) injects malicious JavaScript into web pages viewed by other users. An attacker submits a comment containing <script>steal(document.cookie)</script> — when other users view the page, the script runs in their browser, stealing sessions, credentials, or data.

How XSS Works

Stored XSS: attacker posts malicious script in a comment — every user who views the comment runs the attacker's code. Reflected XSS: attacker crafts a URL with script in query parameters that gets rendered. DOM XSS: client-side JavaScript unsafely processes user input.

Prevention: escape all user output (React does this by default), use Content-Security-Policy headers, sanitize HTML input with DOMPurify, never use innerHTML with user data.

Key Concepts

  • Stored XSS — Malicious script saved in the database and served to all users who view the page
  • Reflected XSS — Script injected via URL parameters and reflected back in the response
  • Content-Security-Policy — HTTP header that restricts what scripts can run — the strongest XSS defense
  • Output Encoding — Escape HTML entities in user-generated content — &lt;script&gt; instead of <script>

Frequently Asked Questions

Does React prevent XSS?

React escapes JSX output by default. But dangerouslySetInnerHTML, href='javascript:', and server-side rendering with unsanitized data can still create XSS vulnerabilities.

What's the best XSS prevention?

Content-Security-Policy header + output encoding + input validation. Never trust user input — sanitize on both input and output.