Sobes.tech
Middle

How to create a protected route in a React application?

sobes.tech AI

Answer from AI

A Protected Route in React is usually implemented by checking user authentication before rendering the route component. If the user is not authenticated, they are redirected to the login page or another public page.

Example using React Router v6:

import { Navigate, Outlet } from 'react-router-dom';

const ProtectedRoute = ({ isAuthenticated }) => {
  return isAuthenticated ? <Outlet /> : <Navigate to="/login" replace />;
};

// Usage in routes
// <Route element={<ProtectedRoute isAuthenticated={userLoggedIn} />}>
//   <Route path="/dashboard" element={<Dashboard />} />
// </Route>

Here, ProtectedRoute checks if the user is authenticated (isAuthenticated). If yes, it renders nested routes via <Outlet />, if not, it redirects to the login page.

Thus, access to protected pages of the application can be centrally controlled.

How to create a protected route in a React… - sobes.tech