XSS vs CSRF — What's the Difference?

XSS (Cross-Site Scripting) injects malicious script that runs within a vulnerable site's own trusted context; CSRF (Cross-Site Request Forgery) tricks a vict...

Published November 24, 2026

XSS injects malicious scripts that run inside your site in the victim's browser; CSRF tricks the victim's browser into sending an unwanted request to your site using their existing login. XSS abuses the user's trust in a site, CSRF abuses the site's trust in the user's browser.

The concept

XSS needs a flaw that outputs untrusted data unescaped; once running, the script can read page data and make any request, defeating CSRF tokens.

CSRF needs authentication via automatically sent credentials (cookies) and state-changing endpoints without anti-forgery tokens.

Side by side

XSS CSRF
attacker runs script in your page request from another site
fix escape output, CSP tokens, SameSite cookies

Practical examples

XSS defence

el.textContent = userInput   // not innerHTML

CSRF defence

<form method="POST"><input type="hidden" name="_token" value="{{ csrf_token() }}"> ...</form>

Cookie flags help both

Set-Cookie: sid=abc; HttpOnly; Secure; SameSite=Lax

Common mistakes

  • Thinking CSRF tokens stop XSS.
  • Allowing GET requests to change data.
  • Relying on a single defence.

Key takeaways

  • XSS = script in your page, CSRF = forged request.
  • Escape/CSP vs tokens/SameSite.
  • XSS can bypass CSRF protection.

FAQ

Which is worse?

XSS is generally more powerful since it runs code as the user.

Do SPAs with JWTs avoid CSRF?

Header-based tokens do, but they raise XSS-theft risk if stored badly.

More General articles