close

How to implement authenticated routes in React Router 4?

Hello Guys, How are you all? Hope You all Are Fine. Today we are going to learn How to implement authenticated routes in React Router 4? in javascript. So Here I am Explain to you all the possible methods here.

Without wasting your time, Let’s start This Article.

How to implement authenticated routes in React Router 4 ?

  1. How to implement authenticated routes in React Router 4 ?

    to implement authenticated routes in React Router 4 <PrivateRoute exact path="/private" authed={true} redirectTo="/login" component={Title} text="This is a private route"/>
    And you can also make Public routes that only unauthed user can access
    <PublicRoute exact path="/public" authed={false} redirectTo="/admin" component={Title} text="This route is for unauthed users"/>

  2. How to implement authenticated routes in React Router 4 ?

    to implement authenticated routes in React Router 4 <PrivateRoute exact path="/private" authed={true} redirectTo="/login" component={Title} text="This is a private route"/>
    And you can also make Public routes that only unauthed user can access
    <PublicRoute exact path="/public" authed={false} redirectTo="/admin" component={Title} text="This route is for unauthed users"/>

Method 1

I know it’s been a while but I’ve been working on an npm package for private and public routes.

Here’s how to make a private route:

<PrivateRoute exact path="/private" authed={true} redirectTo="/login" component={Title} text="This is a private route"/>

And you can also make Public routes that only unauthed user can access

<PublicRoute exact path="/public" authed={false} redirectTo="/admin" component={Title} text="This route is for unauthed users"/>

I hope it helps!

Method 2

Here is the simple clean protected route

const ProtectedRoute 
  = ({ isAllowed, ...props }) => 
     isAllowed 
     ? <Route {...props}/> 
     : <Redirect to="/authentificate"/>;
const _App = ({ lastTab, isTokenVerified })=> 
    <Switch>
      <Route exact path="/authentificate" component={Login}/>
      <ProtectedRoute 
         isAllowed={isTokenVerified} 
         exact 
         path="/secrets" 
         component={Secrets}/>
      <ProtectedRoute 
         isAllowed={isTokenVerified} 
         exact 
         path="/polices" 
         component={Polices}/>
      <ProtectedRoute 
         isAllowed={isTokenVerified} 
         exact 
         path="/grants" component={Grants}/>
      <Redirect from="/" to={lastTab}/>
    </Switch>

isTokenVerified is a method call to check the authorization token basically it returns boolean.

Summery

It’s all About this article. Hope all method helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which method worked for you? Thank You.

Leave a Comment