QUICK START:HTMLCSSJavaScriptTypeScriptPythonSQLReactNext.jsNode.jsDSASystem DesignDevOpsCybersecurityAI / ML
Intermediate 18 min readModule: Module 8: Cross-Site Scripting (XSS) & Mitigation

Cross-Site Scripting (XSS): Stored, Reflected & DOM

Defend web apps against malicious JavaScript execution using HTML escaping, sanitized inputs, and DOMPurify.

What You Will Learn in This Lesson

  • The 3 types of XSS: Stored, Reflected, and DOM-based
  • How attackers steal session cookies using document.cookie in XSS payloads
  • Why dangerouslySetInnerHTML requires DOMPurify sanitization in React

Introduction & Core Concept

Cross-Site Scripting (XSS) attacks occur when an attacker injects malicious client-side executable JavaScript scripts into web pages viewed by other users.
WHY DOES THIS MATTER IN THE REAL WORLD?

Malicious JavaScript executing in a victim's browser can steal session tokens, log keystrokes, or perform actions on behalf of the user.

Safe React Escaping vs dangerouslySetInnerHTML

javascript
javascript
1
2
3
4
5
6
7
8
// SAFE: React automatically escapes HTML entities in JSX
function SafeComment({ text }) {
return <p>{text}</p>; // '<script>...' is rendered harmlessly as plain text
}
// If raw HTML is required, ALWAYS sanitize with DOMPurify first:
// import DOMPurify from 'dompurify';
// <div dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(userHTML) }} />

Line-by-Line Technical Breakdown

1Mark authentication session cookies as HttpOnly so client JavaScript cannot access them via document.cookie.

Try It Yourself (Interactive Editor)

Modify the code in real-time and click Run to test live browser output and console logs.

Intelligent Code Runner & Live Sandbox[JAVASCRIPT]
JAVASCRIPT SOURCE EDITOR
Interactive Live Code

Industry Best Practices & Professional Standards

  • Set HttpOnly flags on authentication cookies and sanitize all raw HTML inputs.

Lesson Summary & Core Takeaways

  • Context-aware output escaping and input sanitization neutralize XSS attacks.