Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

142
Views
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.

some pages should load with token and some not

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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" />;
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!