Part 15 / Topic 7 of 9
A catch-all 404, and a protected route with no loader
Two route-matching edge cases, both solved entirely with Declarative-mode pieces already introduced above. examples/07_not_found_and_protected_route.jsx's catch-all:
// examples/07_not_found_and_protected_route.jsx
<Route path="*" element={<NotFound />} />
A path="*" matches any URL nothing earlier matched - visiting /this-page-does-not-exist really renders the 404 message (examples/07_not_found_and_protected_route.test.jsx). React Router ranks routes by specificity, not by the order they're written in <Routes> - /account always wins over this splat regardless of where either line sits - the splat is written last here only so a human reading top to bottom sees the specific routes before the catch-all, not because the position changes what matches.
A "protected route" is not a separate router feature - it is a plain component, placed as a parent route's element, that renders <Outlet/> when allowed or a <Navigate/> when not:
// examples/07_not_found_and_protected_route.jsx
function RequireAuth({ isSignedIn }) {
const location = useLocation();
if (!isSignedIn) {
const next = encodeURIComponent(location.pathname);
return <Navigate to={`/login?next=${next}`} replace />;
}
return <Outlet />;
}
<Route element={<RequireAuth isSignedIn={isSignedIn} />}>
<Route path="/account" element={<Account />} />
</Route>
A signed-out visit to /account really redirects to /login and shows "Please sign in to continue to /account"; a signed-in visit really renders the account page with no redirect at all (examples/07_not_found_and_protected_route.test.jsx). replace on the <Navigate/> matters: it swaps the history entry instead of adding one, so the browser's back button from /login doesn't bounce the visitor straight back into the redirect loop. The next value is built with encodeURIComponent on location.pathname specifically - never a raw, attacker-suppliable URL - because a login page that blindly redirects to whatever next says is an open redirect: it must accept next only as a same-site path starting with /, never // or a full https:// URL, or a crafted link can send a signed-in user somewhere else entirely after login.
⚠️ This client-side check only shapes the UI - hiding a link and skipping a render. It is not access control. Anything genuinely sensitive behind
/accountmust be enforced again by whatever server actually serves that data; a browser's JavaScript can always be bypassed by whoever controls the browser.
Done here? The practice set for Part 15 — including the solutions — is on the part page.