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 2 of 3 React 19+

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.

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?

Auth state from the server, with a route guard React 19+

Preview

Press Run to see the page.

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