Auth state from the server, with a route guard
The app starts on /orders, shows "Checking your session…" while loading, then the guard redirects to /login and remembers /orders. After login it goes back there. This guard only decides what to show: the real /api/orders endpoint must still check the cookie itself, because anyone can skip this JavaScript.
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.
Write an apiFetch wrapper that sends cookies, adds a CSRF header for non-GET requests and calls onUnauthorized() on a 401.
Write the Set-Cookie header a login endpoint should send for a session id, and explain each attribute.
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
Why can't a React app keep a secret, and what do the VITE_ and NEXT_PUBLIC_ prefixes mean?
Compare storing an auth token in localStorage, in memory and in an httpOnly cookie.
What is CSRF and how do you defend a cookie-based app against it?
How should a React app represent auth state, and what must never depend on it?
Preview
Console
Nothing logged yet.Expected console output
auth status: loading
auth status: anonymous
page shows: Log in as Asha
auth status: authenticated
page shows: Orders for AshaLog out