🚧 404 & Protected Routes in React
Let's handle missing routes with a custom 404 page, and secure sensitive pages using protected routing.
❌ 1. Handling 404 (Not Found)
Use a wildcard path *
to show a custom page for unknown URLs.
// NotFound.jsx
export default function NotFound() {
return <h2>404 - Page Not Found</h2>;
}
// App.jsx
<Routes>
<Route path="/" element={<Home />} />
<Route path="*" element={<NotFound />} />
</Routes>
🔒 2. Creating Protected Routes
Use a wrapper component to restrict access based on authentication.
// ProtectedRoute.jsx
import { Navigate } from 'react-router-dom';
function ProtectedRoute({ children }) {
const isLoggedIn = true; // Replace with real auth check
return isLoggedIn ? children : <Navigate to="/login" />;
}
🔗 3. Use It in Your Routes
<Routes>
<Route path="/dashboard" element={
<ProtectedRoute>
<Dashboard />
</ProtectedRoute>
} />
</Routes>
This ensures only logged-in users can view protected pages like dashboards, profiles, or admin panels.