Learn JavaScript
❯ browser_dom.web_security

Web Security: XSS, CSP & Trusted Types in JavaScript

$concept

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.

$how it works
1

Sinks execute strings

innerHTML, eval, setTimeout("..."), javascript: URLs — untrusted data reaching these runs as your origin's code.

2

Safe APIs by default

textContent, createElement, addEventListener — structure without parsing, behavior without strings.

3

CSP whitelists sources

Content-Security-Policy headers restrict executable origins — injected payloads arrive dead even when insertion succeeds.

4

Frameworks help, DOM doesn't

React/Vue escape by default; raw DOM trusts you completely — match caution to the layer you're in.

$example
// UNSAFE: el.innerHTML = userInput; (executes markup)
// SAFE:
el.textContent = "<img src=x>";
console.log(el.textContent);
Output
<img src=x>
1The commented line shows the vulnerability pattern — markup parsed and executed.
2textContent inserts the same characters as inert text — angle brackets displayed, never parsed.
3Identical input, opposite outcomes — sink choice is the entire security boundary.
$use cases
Auditing innerHTML/eval/setTimeout-string sinks in review
Deploying CSP headers as injection backstops
textContent-only handling of user content in raw DOM
Trusted Types enforcement where browsers support it

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in JavaScript yourself — building beats watching.