how can i protect routes in reactjs?

This is how I did it, basically, you wrap the route and check if the user is authenticated, if he’s not, redirect back to where he should be. This uses react-router v6, you can find more information about it in the authentication section of the official docs. They have a very good example on stackblitz, you should take a look at that.

import { useIsAuthenticated } from "your-auth-package"
import { Navigate, useLocation } from "react-router";

const AuthenticatedRoute = ({ children }) => {
  const isAuthenticated = useIsAuthenticated();
  const location = useLocation();

  // not logged in
  if (!isAuthenticated) {
    console.log("not authenticated");
    return <Navigate to="/" state={{ from: location }} replace />;
  }

  return children;
};
<BrowserRouter>
  <Routes>
    <Route
      path="/dashboard"
      element={
        <AuthenticatedRoute>
          <Dashboard />
        </AuthenticatedRoute>
      }
    />
  </Routes>
</BrowserRouter>

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top