1

good day

I've read many questions like this How to implement authenticated routes in React Router 4? and I have a question: why it is so hard? I am really confused. I mean COULD I use such simple approach as:

export default function PathRouter() {
    return (
        <div>
            {isAuth && <Switch>
                <Route exact path="/devices" component={Devices}/>
                   ...
                <Route path="*" component={NotFoundPage}/>
            </Switch>}

            {!isAuth && <Switch>
                <Route exact path="/login" component={Login}/>
                <Redirect to="/login" />
            </Switch>}

        </div>
    );
}

where isAuth is my variable which checks for presence of token in cookies and / or localstorage. To avoid questions: isAuth could be the function that sends requests to server to check if the token in the cookies is valid.

Could I use that approach or is it wrong? Why do I need private routes? I mean private routes is nothing but a route with an auth constant inside. Or am I wrong?

deathfry
  • 149
  • 11
  • Hm I think it depends on the rest of the architecture in your app. If this is just a simple practice project having variables for auth should be enough. But using private routes is more secure, it is easier to maintain the app if you have PrivateRoute component. – Antonija Šimić Sep 29 '20 at 19:26
  • well, I specially noticed about isAuth variable - it should be the function returning true or false with some deep logic. – deathfry Sep 29 '20 at 19:30
  • You might want to work with 3 layers: one contains all components, one only requests for authenticated/private components, and one only serves public stuff – Matteus Barbosa Sep 29 '20 at 19:58
  • Well in my example everything is readable and clear. If isAuth then layer with secure routes. If !isAuth - unsecure layer...Not a reason IMHO – deathfry Sep 29 '20 at 20:03

0 Answers0