Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 21.4 — Secrets, Tokens and Auth in the Browser
React · Example 3 of 3

SameSite, Origin and CSRF tokens, as a model

With SameSite=None the evil form's POST carries the cookie, and only the server's Origin check (and the CSRF token behind it) stops it. With Lax the cookie isn't even sent. The evil link still arrives logged in under Lax, which is fine as long as GET requests never change anything. Real browsers decide "same site" by the registrable domain, which this model simplifies.

Everything shipped to the browser can be read by anyone, so secrets stay on servers; VITE_ and NEXT_PUBLIC_ variables are public by design. Store login sessions where scripts can't read them (httpOnly cookies), defend cookies against CSRF with SameSite, Origin checks and tokens, and treat auth state in React as a display hint the server always re-checks.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write an apiFetch wrapper that sends cookies, adds a CSRF header for non-GET requests and calls onUnauthorized() on a 401.

02

Write the Set-Cookie header a login endpoint should send for a session id, and explain each attribute.

03

A React app calls a weather API with a secret key from import.meta.env.VITE_WEATHER_KEY. Describe the fix in code.

Explain it without notes

01

Why can't a React app keep a secret, and what do the VITE_ and NEXT_PUBLIC_ prefixes mean?

02

Compare storing an auth token in localStorage, in memory and in an httpOnly cookie.

03

What is CSRF and how do you defend a cookie-based app against it?

04

How should a React app represent auth state, and what must never depend on it?

SameSite, Origin and CSRF tokens, as a model

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

None | our app: POST with token   | cookie sent | 200 changed
None | evil form: POST            | cookie sent | 403 wrong Origin
None | evil link: GET             | cookie sent | 200 read only
Lax  | our app: POST with token   | cookie sent | 200 changed
Lax  | evil form: POST            | no cookie   | 401 not logged in
Lax  | evil link: GET             | cookie sent | 200 read only