How cross site scripting happens
Cross site scripting occurs when attacker controlled data is inserted into a page and the browser treats it as code. The classic mistake is writing untrusted input straight into the document so a script tag or event handler runs. The fix is to keep data as data.
- Reflected injection echoes input from the request into the page.
- Stored injection persists malicious data in a database.
- DOM based injection happens entirely in client script.
Encoding for context
The defense is to encode output for the exact context where it lands, because HTML, attribute, and JavaScript contexts each escape differently. Frameworks that bind text rather than HTML do this automatically, which is why you avoid raw inner HTML assignment.
- Insert untrusted text through safe text bindings.
- Avoid inner HTML and document write with user data.
- Encode per context when you must build markup by hand.
Combine encoding with a content security policy so a missed spot still cannot execute arbitrary code.
Key idea
Keep untrusted input as data by encoding output for its context and using safe text bindings instead of raw HTML insertion.