← Back to the Build Your Homepage series
πŸ”’
EPISODE 02
SameSite cookies Β· tokens Β· JWT Β· session

CSRF & Authentication

Protect authenticated endpoints from CSRF. Use SameSite cookies, CSRF tokens, and understand the trade-offs between session cookies and JWT tokens.

CSRFauthJWTSameSitecookies
Duration
⏱ About 2 hours
Level
πŸ“Š Intermediate
Prerequisite
🎯 node-04
OUTCOME
An auth system that resists CSRF and common token misuse

What you'll learn

  • 1Explain CSRF in one sentence
  • 2Block CSRF with SameSite=Lax/Strict cookies
  • 3Use CSRF tokens when SameSite is not enough
  • 4Compare session cookies vs JWT (and pick session for new apps)

1. What is CSRF?

An attacker tricks a logged-in user's browser into firing a request to your site, riding on their cookies. The user did not intend it.

html
<!-- attacker.com -->
<img src="https://yourbank.com/transfer?to=evil&amount=1000">

2. SameSite Cookies (First Line of Defense)

text
Set-Cookie: session=abc; HttpOnly; Secure; SameSite=Lax; Path=/
  • Lax β€” cookie not sent on cross-site POST (good default)
  • Strict β€” cookie not sent on any cross-site request
  • None β€” only with Secure; needed for embedded contexts

3. CSRF Tokens

Render a per-session random token in your form. The server requires it on submit. The attacker's site cannot read it (Same-Origin Policy).

javascript
// Express + csurf
import csurf from "csurf";
app.use(csurf({ cookie: true }));
app.get("/form", (req, res) => {
  res.render("form", { csrfToken: req.csrfToken() });
});
app.post("/transfer", (req, res) => { /* csurf validates automatically */ });

4. Session Cookies vs JWT

Session cookieJWT (Authorization header)
StorageServer-side (Redis/DB)Client-side (token contains data)
RevokeEasy (delete the row)Hard β€” must check blocklist
SizeTinyLarge (whole user info)
XSSHttpOnly cookie cannot be stolenlocalStorage tokens can be stolen
Best forMost web appsStateless APIs, mobile clients
πŸ’‘

Default to session cookies for traditional web apps. JWT shines when you cannot rely on cookies (mobile, B2B APIs).

Example code / lecture materials

All lecture materials and example code are openly available on GitHub.

View on GitHub β†—