Web Security: XSS, CSP & Trusted Types in JavaScript
Cross-site scripting (attacker JavaScript running in your origin) is the web's cardinal vulnerability, and the defenses layer: never sink untrusted data into HTML sinks (innerHTML, document.write, eval, setTimeout strings) — use textContent and safe APIs; Content-Security-Policy headers whitelist script sources so injected code can't execute even when injected; Trusted Types (enforcing policies on sinks) makes bypasses structurally impossible in supporting browsers.
CORS, SameSite cookies, and HTTPS complete the picture, but XSS prevention starts in your code: treat every sink as guilty until proven safe, escape by construction (frameworks do this by default — raw DOM does not), and let CSP be the backstop, never the plan.
Sinks execute strings
innerHTML, eval, setTimeout("..."), javascript: URLs — untrusted data reaching these runs as your origin's code.
Safe APIs by default
textContent, createElement, addEventListener — structure without parsing, behavior without strings.
CSP whitelists sources
Content-Security-Policy headers restrict executable origins — injected payloads arrive dead even when insertion succeeds.
Frameworks help, DOM doesn't
React/Vue escape by default; raw DOM trusts you completely — match caution to the layer you're in.
// UNSAFE: el.innerHTML = userInput; (executes markup)// SAFE:el.textContent = "<img src=x>";console.log(el.textContent);Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in JavaScript yourself — building beats watching.