0

I have a react router structure like this:

<HashRouter basename='/'>
    <Switch>
        <Route exact path='/'>
            <Component1 />
        </Route>
        <Route path='/2'>
            <Component2 />
        </Route>
        <Route path='/3'>
            <Component3 />
        </Route>
        <Route path='/not-authorized'>
            <NotAuthed />
        </Route>
    </Switch>
</HashRouter>

what I want to happen is, whenever I go to any of these routes, I want to run some logic to determine if the user is authorized to see them. If not, they should always get re-directed to /not-authorized. So if I navigate directly (via browser address bar OR via client-side redirect) to / or to /2 etc... I should always run the logic to determine if I should be redirected to /not-authorized. But if I am authorized, I should go to the appropriate route, so if I was attempting to go to /2 it should correctly bring to me /2 if I'm authorized.

Basically my question is; is there a built-in way (prop that I can pass to the Switch) for react router to do this or do I need to manually add logic to check auth on each route's component and redirect away if not authed?

duxfox--
  • 8,314
  • 13
  • 50
  • 112
  • 2
    Will this help? https://reactrouter.com/web/example/auth-workflow – Dennis Martinez Feb 25 '21 at 19:12
  • This is a very common scenario and it is usually handled by creating a `PrivateRoute` component which you use instead of `Route`. Internally, the `PrivateRoute` loads the `Route` if authenticated or `Redirect` otherwise. – Linda Paiste Feb 25 '21 at 19:12

1 Answers1

0

I'd go with something like:

<HashRouter basename='/'>
    <Switch>
        <Route exact path='/'>
            { condition ? <Component1 /> : <ComponentForUnauthorized/> }
        </Route>
        <Route path='/2'>
             { condition ? <Component2 /> : <ComponentForUnauthorized/> }
        </Route>
        <Route path='/3'>
           { condition ? <Component3 /> : <ComponentForUnauthorized/> }
        </Route>
    </Switch>
</HashRouter>

Or even based on another answer React router with conditions

  <HashRouter basename='/'>
    <Switch>
      <Route exact path="/" component={()=>isAuthorised ? <Component1/> <Unauthorised/>}/>
    </Switch>
  </HashRouter>

However, there is also an official way given in router official docs, with redirect, which is I believe is even better: https://reactrouter.com/web/api/Redirect

  <HashRouter basename='/'>
    <Switch>
      <Route exact path="/">
        {loggedIn ? <Redirect to="/dashboard" /> : <PublicHomePage />}
      </Route>
    </Switch>
  </HashRouter>