0
Challenge · 45Routing & Data

Protected Routes

Coreused in ~75% of apps

In a SPA every route is just a URL anyone can type. Without a guard, a logged-out user reaches /dashboard the moment they guess the path.

Core idea. A protected route is a guard component that, before rendering a route's element, checks auth: if you're in it renders the page (children or an <Outlet/>); if not it returns <Navigate to="/login" replace /> — remembering where you wanted to go so you can be sent back after login.
Playground, this isn't a screenshot
myapp.com/

<Home />

Public page — anyone can open this, logged in or not.

You are logged out. Click a locked page and watch the guard redirect you.
route needs auth redirected to /login sent back to intended page
↑ play a little first, then dig in