Command Palette

Search for a command to run...

Hectal
Phase 21: Security in React Apps
React · Exercise 4 of 5 PreviousNext
Intermediate

Guard a page with server auth state

The app starts on /account. AuthProvider asks the fake server who is logged in (api.me(), which takes 200 ms) and exposes { status, user, login }, where status is "loading", "authenticated" or "anonymous".

Write RequireAuth: while status is "loading", render <p id="checking">Checking your session…</p>; when "anonymous", redirect to /login and remember the page the user wanted (in the navigation state); when "authenticated", render its children.

Update Login so that once the user is authenticated it sends them back to the page they wanted (or / if none). Don't store anything in localStorage: the session is the server's (an httpOnly cookie in a real app).

What Check tests

  1. An anonymous visitor doesn't see the account page
  2. They are sent to the login page
  3. The guard shows a checking state while loading
  4. After logging in they return to the account page
  5. Nothing was stored in localStorage

Stuck? One hint at a time

The solution unlocks after your first Check. Try first: that is where the learning happens.

Runs in your browser. Your code is saved here.

Your page

Press Run to see the page.

Console

Nothing logged yet.