Frontend Interview Questions

XSS and CSRF Defense: What to Actually Do

How do you defend against XSS and CSRF? What's the difference?

Why Interviewers Ask This

Web security is interviewed in every frontend loop — and answers that list "use HTTPS" without specifics fail the question.

How to Answer

  1. 1

    XSS = attacker injects script into your page. Three types: stored (DB), reflected (URL param), DOM-based (client-side sink).

  2. 2

    XSS defense: escape on output (framework templates do this by default), CSP header to block inline scripts, DOMPurify for user-authored HTML, httpOnly cookies so tokens aren't stealable.

  3. 3

    CSRF = attacker tricks user's browser into making an authenticated request cross-origin. Not about stealing the cookie — about using it unwittingly.

  4. 4

    CSRF defense: SameSite=Lax/Strict on session cookies, CSRF token in a header the attacker can't set cross-origin, check Origin/Referer for state-changing requests.

  5. 5

    Key distinction: XSS runs code in YOUR page (full compromise); CSRF tricks the user's browser to make requests (limited to endpoints).

Sample Answer

XSS is code injection into your page; CSRF is your browser being tricked into sending an authed request elsewhere. For XSS: default-escape in React/Vue templates catches 90%, a strict Content-Security-Policy catches what slips through, and never use dangerouslySetInnerHTML unless the input is DOMPurify-sanitized. httpOnly on auth cookies means even a successful XSS can't read the token. For CSRF: SameSite=Lax on session cookies is the 2026 baseline, plus a CSRF token in X-CSRF-Token header for state-changing endpoints — attacker can't read your cookies cross-origin so they can't echo the token back. The hierarchy matters: XSS is worse because it owns your page; CSRF is limited to what an endpoint exposes.

Pro Tips

  • Content-Security-Policy with `strict-dynamic` plus nonce is the gold standard.

  • GET requests should never mutate state — eliminates most CSRF vectors on reads.

  • HireMe AI (即答侠) pairs each defense with the attack it blocks — interviewers want causal reasoning, not a list.

Frequently Asked Questions

CORS prevents CSRF, right?

No — CORS controls cross-origin reads, not writes. A cross-origin form POST has always been allowed; CORS only restricts whether the attacker can read the response.

Is SameSite=Strict always better?

Breaks legit cross-site navigation (clicking a link from email to your app logs you out). Lax is the right default for most apps.

Worried About Going Blank in Your Interview?

HireMe AI listens to your interview in real-time, detects questions, and generates instant answer suggestions — so you never freeze up again.

Try HireMe AI Free