React Router and NavigationLesson 5.3
Protected routes and authentication in React Router
protected route pattern, Navigate component, useLocation for redirect, auth context integration, role-based access, lazy loading routes
Protecting Routes with Auth Guards
Protected routes redirect unauthenticated users before rendering sensitive content. The pattern uses a wrapper component that checks auth status and redirects if needed.
ProtectedRoute Component
import { Navigate, useLocation } from 'react-router-dom';
import { useAuth } from './AuthContext';
function ProtectedRoute({ children }) {
const { user } = useAuth();
const location = useLocation();
if (!user) {
// Save the attempted URL so we can redirect back after login
return <Navigate to="/login" state={{ from: location }} replace />;
}
return children;
}
// App.jsx routes
<Route
path="/dashboard"
element={
<ProtectedRoute>
<Dashboard />
</ProtectedRoute>
}
/>Redirect Back After Login
import { useNavigate, useLocation } from 'react-router-dom';
function LoginPage() {
const navigate = useNavigate();
const location = useLocation();
const from = location.state?.from?.pathname || '/';
function handleLogin() {
// authenticate user...
navigate(from, { replace: true });
}
}Using replace: true removes the login page from browser history so the back button doesn't return to it.
