Skip to main content
19

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, innerHTML and eval with 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 HttpOnly so scripts can't read them.

Preventing CSRF:

  • SameSite=Lax (the browser default) or Strict cookies 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-Origin for that origin.
  • "Non-simple" requests (JSON body, custom headers, PUT) trigger a preflight OPTIONS request first.
  • CORS doesn't stop curl or 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.com

Common follow-ups

  • Should you store a JWT in localStorage? Any XSS can steal it from there. An HttpOnly cookie limits the damage but brings CSRF back into play, which SameSite handles.
  • 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."

Was this helpful?