https://remoteindian.com/ logo
#random
Title
# random
e

echoing-computer-87366

08/28/2021, 11:25 AM
I have implemented session based authentication (httpOnly cookie) using passportjs and on frontend I have used react router for navigation. Now I have created
/auth
endpoint which basically makes a GET request to check if current logged in user session is valid or not. Sessions are stored in mongodb. Now for each private route user navigates to I am making call to
/auth
endpoint to validate logged in user. Can this solution be improved any suggestions?
c

clever-vr-95479

08/28/2021, 1:00 PM
You don't need the endpoint - When you make any request and user session is expired send 401 Unauthorised from server. If you are using axios to make request then intercept it and you can redirect the user/logout the user.
e

echoing-computer-87366

08/28/2021, 2:29 PM
But consider this case if user is logged in successfully and then if he refreshes browser or manually changes url in browser during that time session cookie will be present in browser but redux state will reset so Before navigating to private route I will have to check if current logged in user session is valid or not
c

clever-vr-95479

08/28/2021, 3:14 PM
For that you have to use browser storage like local storage to store user and session details. Redux can get those details from there.
e

echoing-computer-87366

08/28/2021, 5:07 PM
I am already using httpOnly cookie which is saved in browser
session is stored in cookie
@clever-vr-95479 /chat and /profile are 2 private routes so in private route code I dont have to hit any /auth endpoint instead of that I will add auth middleware to both of these route and if not authneticated then send isLoggedIn -> false and if authenticated then send isLoggedIn true with the actual response is that correct ? in this way we can avoid using of any additional endpoint to check if user is logged in or not and both chat and profile component in react would be connected to redux store which holds isLoggedIn variable is this correct?
see code here: https://pastebin.com/sdLuPmp3 of private route
c
3 Views