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
- Some pages should only be shown to signed-in people, or people with a role like
admin. A protected route checks first, and redirects if not:
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;
}
- After signing in, send people back to where they were going, using
state.from. -
The most important rule: hiding a page in the frontend is not security. Anyone can read your frontend code and call your API directly. The backend must check identity and permissions on every request (Modules 44 and 48). Protected routes are only for a good experience.
-
Show appropriate options: hide an "Delete" button from people who can't delete, but still enforce it on the server.
🖱️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.
