SmartCodingTips

πŸ”’ 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