Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can I use this scenario to handle protected routes in React?

I use session-storage to save login data like token etc.

Is it best practice to use this scenario for redirecting un-authorized users?

useEffect(() => {
    if (token === null) {
      navigate('/users/login');
    }
}, []);

because I’ve 2 kind of pages in app.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

some pages should load with token and some not

>Solution :

I would rather implement a component that does this check for you, as suggested here, so you don’t have to check for the token in every component:

// In case authentication is required, wrap the component to be rendered inside PrivateRoute
<Route
    path="/protectedPage"
    element={
      <PrivateRoute>
         <ProtectedPage/>
      </PrivateRoute>
    }
/>
// In case no authentication is required, just render the element as it is
<Route
    path="/unprotectedPage"
    element={
       <UnprotectedPage/>
    }
/>
// In case you don't want to show the page to an authenticated user
<Route
    path="/protectedPage"
    element={
      <PrivateRoute redirectIfAlreadyAuthenticated={true}>
         <Login/>
      </PrivateRoute>
    }
/>

function PrivateRoute({ children, redirectIfAlreadyAuthenticated=false }) {
  if(redirectIfAlreadyAuthenticated)
    return token? <Navigate to="/" /> : children;
  else
    return token? children : <Navigate to="/users/login" />;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading