ProtectedRoute Route Guards
Last updated: 2026-11-02
ProtectedRoute Route Guards
A route guard checks permissions before the page opens: wrap a route in ProtectedRoute, and when the visitor is not signed in it redirects to /login while remembering the page they came from, so they can be sent back after signing in. React ships no built-in guard, so you build one from conditional rendering plus Navigate or useNavigate, and the guard stays a plain component you can test on its own.
| Group | Routing & State Mgmt |
|---|---|
| Kind | Pattern |
ℹ️ Info The editor transpiles JSX to JavaScript and renders the real UI in a sandbox; components mount automatically — no manual render call needed.
📝 Syntax
import { Navigate, Outlet } from 'react-router-dom'
function ProtectedRoute({ isAuth }) {
if (!isAuth) {
// Not signed in: redirect to the login page and remember where we came from
return <Navigate to="/login" replace state={{ from: location.pathname }} />
}
return <Outlet /> // Signed in: render the child routes
}
// Usage:
// <Route element={<ProtectedRoute isAuth={user} />}>
// <Route path="/admin" element={<Admin />} />
// </Route>
⚙️ Parameters
| isAuth (custom) | The permission check: a boolean, an array of roles or an async state - whatever your session provides. |
|---|---|
| redirect (custom) | Where a rejected visitor goes: a redirect address or a notice UI, designed per project. |
Returns:No return value; this is a coding pattern rather than a callable API.
▶ Example
The example runs out of the box: it auto-renders when expanded, and edits take effect instantly.
Output:
Clicking "Admin" while signed out is blocked and lands on the login page; clicking "Sign in and come back" enters the admin panel - the guard flow of a Navigate redirect plus a return after signing in (simulated demo).