Post

Episode 7: Route Protection (Private Routes)

Protect the Cart page so that only logged in users can access it. If they are not logged in, they will be redirected to the Login page.

Episode 7: Route Protection (Private Routes)

In this episode, you’ll:

  • Create a PrivateRoute component
  • Restrict access to the Cart page
  • Redirect unauthorized users to Login

1. Create PrivateRoute Component

In src/components/PrivateRoute.jsx:

1
2
3
4
5
6
7
8
import { Navigate } from "react-router-dom";

const PrivateRoute = ({ children }) => {
  const user = JSON.parse(localStorage.getItem("user"));
  return user ? children : <Navigate to="/login" />;
};

export default PrivateRoute;

2. Use PrivateRoute in App.js

Update the Cart route in App.js:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import PrivateRoute from "./components/PrivateRoute";

// ...

<Routes>
  <Route path="/" element={<Home />} />
  <Route
    path="/cart"
    element={
      <PrivateRoute>
        <Cart />
      </PrivateRoute>
    }
  />
  <Route path="/login" element={<Login />} />
</Routes>

3. Test the Protection

Try these steps:

  • Visit /cart as a logged-out user => should redirect to /login
  • Log in => /cart is now accessible
This post is licensed under CC BY 4.0 by the author.