0

¿How I can do protected routes in react?

I want to create a login with react that send a request to the server and if the data is correct response with a token or something like that to react know if the user can or not get that route. I applying hooks with react. I am between beginner and intermediate in react. Thanks.

22nd Apr 2020, 3:53 AM
Jonathan Alvarado
Jonathan Alvarado - avatar
3 ответов
+ 3
Your frontend react would simply expose all the codes on browser, you would not want to store the protected page on react side. Use server script to control the protected route, only response with protected content if client response with the right token id, otherwise would redirect it to public main or login page.
22nd Apr 2020, 4:16 AM
Calviղ
Calviղ - avatar
+ 2
If you've setup passport.js properly, authentication token (user id) would be automatically serialized to client and deserialized it on server, once the login is authenticated. You only need react component to check the existence of the serialized object, eg user object with user id If serialized object exists, redirect page by requesting protected page from server using window.location = '/userProfile’; Else send to public page, eg login page, by render <Login /> component.
22nd Apr 2020, 7:42 AM
Calviղ
Calviղ - avatar
0
Calviղ that's what I want, I my backend I setup the token with passport and jwt when the login is successful but I don't find how the frontend can know when is authenticated by the server.
22nd Apr 2020, 4:36 AM
Jonathan Alvarado
Jonathan Alvarado - avatar