Module 36: Routing

Lesson 5 of 5 · 15–25 minutes

Protected routes

🏠The everyday picture

A staff-only door: the corridor is public, but this door checks your badge, and sends you to reception if you don't have one.

📘What it really is

function RequireAuth({ children }: { children: React.ReactNode }) {
  const { user } = useAuth();         // your sign-in state (Modules 37 and 44)
  const location = useLocation();
  if (!user) return <Navigate to="/login" replace state={{ from: location }} />;
  return children;
}

🖱️Try it

Add a pretend sign-in: a /login page with a button that sets user in state (stored in localStorage). Protect the dashboard and detail pages with RequireAuth. Check that visiting /enquiries/E101 while signed out goes to login, then returns to that enquiry after signing in. Add a sign-out button.

✅Quick check

A page is protected by RequireAuth. Is its data safe from people who aren't signed in?

Show the answer

No. The frontend can be bypassed; the backend must check every request.

Why remember from when redirecting to login?

Show the answer

So after signing in, people return to the page they were trying to open.

← PreviousNested routes and layouts
ProLearners Assist