What is Cross-Site Scripting (XSS), and how do you prevent it?
Quick Answer
XSS is injecting attacker-controlled script into a page so it runs in other users' browsers — stealing cookies/tokens, keylogging, acting as the user. Prevent it by encoding output for the context (HTML, attribute, JS, URL), avoiding innerHTML with untrusted data (use textContent), sanitising any HTML you must render, and adding a Content Security Policy.
XSS is when an attacker gets their JavaScript to run in someone else's browser on your site — maybe they put a <script> in a comment field that's stored and served to everyone, or it's reflected from a URL parameter. Once their code runs as the victim, it can steal their session or act as them. The defence is context-aware output encoding — the framework does this automatically, so the risk is where you bypass it with innerHTML or Html.Raw. If I genuinely need to render user HTML, I sanitise it with DOMPurify. And a Content Security Policy limits the damage if something gets through.
- Types: stored (persisted in the DB and served to everyone), reflected (echoed from the request), DOM-based (client-side JS writes untrusted data into the DOM).
- Frameworks (React, Angular, Razor) auto-encode by default — the danger is the escape hatches (
dangerouslySetInnerHTML,[innerHTML],Html.Raw). - Sanitise rich HTML with a vetted library (DOMPurify); don't roll your own.
- CSP limits which scripts can run, mitigating impact even if injection slips through.