Back to 20 Concepts
sessions-cookies • Advanced
Cross-Site Scripting (XSS) Defenses & Content Security Policy (CSP)
XSS injects malicious JavaScript into trusted web pages (Stored, Reflected, DOM-based). Defenses require strict Context-Aware Output Encoding and Content Security Policy (CSP) headers restricting script-src execution.
Intuitive Mental Model
The Restaurant Food Quality Inspector: CSP is a strict checklist at the restaurant door forbidding any foreign ingredients (untrusted scripts) from entering the kitchen, ensuring only pre-approved chefs (trusted domains) can cook.
Architecture Blueprint & CodeProduction Standard
// Content-Security-Policy (CSP) HTTP Header: // Content-Security-Policy: default-src 'self'; script-src 'self' 'nonce-rAnd0m123' https://trusted-cdn.com; object-src 'none'; // Nonce-based Script Execution (Next.js): // <script nonce="rAnd0m123" src="/main.js"></script>
Key Architectural Takeaways
- •CSP script-src Nonces: Browser executes inline scripts only if they contain a cryptographically random matching nonce.
- •DOMPurify Sanitization: Strips dangerous HTML event handlers (onload, onerror) before inserting user content into innerHTML.
Common Architectural Pitfall
Using dangerous innerHTML or React dangerouslySetInnerHTML without sanitizing user input through DOMPurify.
Production Best Practice
Use textContent, React JSX auto-escaping, or DOMPurify.sanitize().