How do you defend against XSS and CSRF? What's the difference?
Web security is interviewed in every frontend loop — and answers that list "use HTTPS" without specifics fail the question.
XSS = attacker injects script into your page. Three types: stored (DB), reflected (URL param), DOM-based (client-side sink).
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.
CSRF = attacker tricks user's browser into making an authenticated request cross-origin. Not about stealing the cookie — about using it unwittingly.
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.
Key distinction: XSS runs code in YOUR page (full compromise); CSRF tricks the user's browser to make requests (limited to endpoints).
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.
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.
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.
Breaks legit cross-site navigation (clicking a link from email to your app logs you out). Lax is the right default for most apps.
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