π Protected Routes in React
Protected routes allow you to restrict access to certain pages unless the user is authenticated. In React, this can be implemented using a wrapper component and routing logic.
π§ 1. Setup Authentication Context
import { createContext, useContext, useState } from 'react';
const AuthContext = createContext();
export const AuthProvider = ({ children }) => {
const [isAuthenticated, setIsAuthenticated] = useState(false);
return (
<AuthContext.Provider value={{ isAuthenticated, setIsAuthenticated }}>
{children}
</AuthContext.Provider>
);
};
export const useAuth = () => useContext(AuthContext);
π‘οΈ 2. Create a ProtectedRoute Component
import { Navigate } from 'react-router-dom';
import { useAuth } from './AuthContext';
function ProtectedRoute({ children }) {
const { isAuthenticated } = useAuth();
if (!isAuthenticated) {
return <Navigate to="/login" replace />;
}
return children;
}
πΊοΈ 3. Using ProtectedRoute in App
import { Routes, Route } from 'react-router-dom';
import Dashboard from './pages/Dashboard';
import Login from './pages/Login';
import ProtectedRoute from './ProtectedRoute';
function App() {
return (
<Routes>
<Route path="/login" element={<Login />} />
<Route
path="/dashboard"
element={
<ProtectedRoute>
<Dashboard />
</ProtectedRoute>
}
/>
</Routes>
);
}
π 4. Updating Auth State on Login
import { useAuth } from './AuthContext';
function Login() {
const { setIsAuthenticated } = useAuth();
const handleLogin = () => {
// Simulate successful login
setIsAuthenticated(true);
};
return <button onClick={handleLogin}>Login</button>;
}
π Summary
- Use context to track authentication
- Create a
ProtectedRoute
wrapper to control access - Redirect unauthenticated users to a login page
- Secure sensitive pages from unauthorized access