XSS vs CSRF, and what CORS actually does
MediumSecurityXSSCSRFCORS
What's the difference between XSS and CSRF, how do you prevent each, and what does CORS actually do?
TL;DR
XSS (cross-site scripting) is an attacker getting their script to run on your site, so it can do anything the user can, like read data or act as them. CSRF (cross-site request forgery) is another site making the user's browser send a request to your site with the user's cookies attached. CORS isn't a protection for your server: it's how a server tells the browser which other origins may read its responses, relaxing the same-origin policy.
Key points
Preventing XSS:
- Escape output by default. React escapes JSX text; avoid
dangerouslySetInnerHTML,innerHTMLandevalwith user data. - Sanitize HTML you must render (DOMPurify).
- Add a Content Security Policy (
script-src 'self'plus nonces) so injected scripts don't run. - Put session cookies in
HttpOnlyso scripts can't read them.
Preventing CSRF:
SameSite=Lax(the browser default) orStrictcookies stop most cross-site cookie sending.- Use CSRF tokens for cookie-authenticated forms, and never change state on
GET. - APIs authenticated with a header (
Authorization: Bearer) aren't exposed to CSRF, because browsers don't add that header automatically.
CORS:
- The browser blocks reading a cross-origin response unless the server returns
Access-Control-Allow-Originfor that origin. - "Non-simple" requests (JSON body, custom headers,
PUT) trigger a preflightOPTIONSrequest first. - CORS doesn't stop
curlor server-to-server calls. It's not authentication.
Example
http
Set-Cookie: session=abc; HttpOnly; Secure; SameSite=Lax
Content-Security-Policy: default-src 'self'; script-src 'self' 'nonce-r4nd0m'
Access-Control-Allow-Origin: https://app.example.comCommon follow-ups
- Should you store a JWT in
localStorage? Any XSS can steal it from there. AnHttpOnlycookie limits the damage but brings CSRF back into play, whichSameSitehandles. - Is
Access-Control-Allow-Origin: *with credentials allowed? No. Browsers reject it; you must echo a specific origin.
What interviewers look for
Tip
Separate the three clearly: XSS runs code, CSRF borrows cookies, CORS controls who can read responses. Then name the main defense for each.
- Red flag: "we enabled CORS so we're protected from CSRF."