Private Route
Imagine that building an app where users can access personal data, like account details or sensitive information. Want to make sure only authenticated users can view these pages, and unauthenticated users should be redirected to a login page. This is where PrivateRoute comes in.
- Security: Protects sensitive routes by ensuring only authenticated users can access them.
- Simplified Code: Can keep route protection logic centralized in one place, making your code cleaner and easier to maintain
- Create a PrivateRoute component that checks if user.isLoggedIn.
- If not logged in, it redirects to /login, carrying along the original target URL.
- If logged in, it renders an <Outlet /> so the protected child routes appear.
The PrivateRoute Component
// src/routes/PrivateRoute.jsx
import { Navigate, useLocation, Outlet } from “react-router-dom”;export default function PrivateRoute({ isLoggedIn }) {
const location = useLocation();if (!isLoggedIn) {
// Not logged in? Send to /login and remember where they wanted to go
return <Navigate to=”/login” state={{ from: location }} replace />;
}// Logged in? Render the requested child route
return <Outlet />;
}
We call useLocation() to capture the current URL (e.g. /account).
Get Danushanthi Konesalingam’s stories in your inbox
Join Medium for free to get updates from this writer.
If isLoggedIn is false, we <Navigate> to /login, passing { from: location } so we can come back later.
If isLoggedIn is true, we render <Outlet />, which will show whatever child route is active.
App.jsx component
import PrivateRoute from “./routes/PrivateRoute”;
function App({ user }) {
return (
<BrowserRouter>
<Routes>
{/* Public pages */}
<Route path=”/” element={<Home />} />
<Route path=”/login” element={<Login />} />{/* Protected section: all routes here require login */}
<Route element={<PrivateRoute isLoggedIn={user.isLoggedIn} />}>
<Route path=”/account” element={<AccountDetails />} />
<Route path=”/settings” element={<ProfileSettings />} />
</Route>
</Routes>
</BrowserRouter>
);
}export default App;




