Routing with React Router
React Router Protected Routes
A protected route checks authentication before rendering and redirects to the login page otherwise. It is implemented as a wrapper component or a layout route, not as a router feature.
What is Router Protected Routes in React?
A protected route checks authentication before rendering and redirects to the login page otherwise. It is implemented as a wrapper component or a layout route, not as a router feature.
Why Router Protected Routes matters
Client-side guards improve the experience, but they are not security. The API must authorise every request independently, because anyone can edit the JavaScript in their browser.
Router Protected Routes example
import { Navigate, Outlet, useLocation } from 'react-router-dom';
function RequireAuth() {
const { user, loading } = useAuth();
const location = useLocation();
if (loading) return <Spinner />;
if (!user) return <Navigate to="/login" state={{ from: location }} replace />;
return <Outlet />;
}
<Route element={<RequireAuth />}>
<Route path="/dashboard" element={<Dashboard />} />
<Route path="/applications" element={<Applications />} />
</Route>How this works
Every route nested inside RequireAuth is guarded by one component. Storing the attempted location in state lets the login page send the user back where they were going.
Key points to remember
- Handle the loading state, or a refresh flashes the login page before auth resolves.
- Use replace so the guarded URL does not sit in history.
- Enforce the same rules on the server — client checks are cosmetic.
Common mistakes with Router Protected Routes
- Redirecting while auth is still loading, which logs users out on every refresh.
- Treating a client-side guard as real access control.
React Router Protected Routes— Interview Questions & FAQs
Are protected routes secure?+
No. They only hide UI. Anyone can bypass client-side checks with devtools, so every protected API endpoint must verify the session or token on the server.
