Although not being exactly sure if this is a react specific question:
We are developing and application using react/redux stack with server side rendering. After user logs in we receive two cookies one for identity and one for session in the browser (with an expiration date). The problem is when the user refreshes the page the state is getting reset and we lose our session information ( we basically set some variables in the state to indicate the user is logged in ).
The question is how to manage this situation and keep the user logged in even when the page is refreshed. I am thinking of keeping server side rendering completely out of the picture and just check on the client side for a non-expired session id cookie when the page is initially rendered and set some variables in the state if the session is still alive, and vice-versa otherwise.
Does this look like a secure approach? Is there a better way to do it?
I had a similar problem. I don't see anything wrong personally with checking the cookies and re-registering on the UI the session if you can. The server is still being guarded by the proper cookies.
In my case however I wasn't able to check the cookies via JS, as they were set as http-only
. In the end I had to go for the following solution:
When the user first logs in successfully create a 'sessionStorage' instance to indicate that there is an active session:
window.sessionStorage.setItem(sessionKey, stringifiedUserToken);
If the page gets refreshed then check for this session item and re-register the active session:
const activeSession = window.sessionStorage.getItem(sessionKey);
if (activeSession) {
// fire register user session action
}
If the user logs out then kill the session storage token.
All the server interaction still requires the cookie which will be passed along, so this is purely a front-end concern.
Session storage will clear at the end of the browser session, so this naive approach may not work for "permanent" sessions. It does have great browser support though: http://caniuse.com/#search=sessionStorage
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With