Home > Net >  How to approach conditional rendering SPA page?
How to approach conditional rendering SPA page?

Time:09-17

Basically, I have SPA app with JWT authentication. Now my question is, there is a page that has follow button, so on the first load of page, I need to know if user is logged in or not, so I can disable/enable button.

Approach 1: Before page load send access token and if it is successful render like user is logged in, if it fails render like user is logged out

Approach 2: When user is logged in, keep that state in LocalStorage and just check local storage and render page from that

Is it correct to just keep state of logged in user in LocalStorage? I think that is where you should store ID token (if you use them) that only has user profile information?

Of course I will check access token on each request and from response I can change state in LocalStorage. Problem is that on initial load of page, should I check access token server-side before rendering?

If I keep state in LocalStorage than that user will be logged in on that device basically indefinitely, until he clicks "log out" or tokens fail?

Can anybody see potential problems with keeping state in LocalStorage?

CodePudding user response:

It's OK to keep this information in the local storage. I mean, you can keep a variable there, that will just tell you "this user is logged in as userX". You can then safely utilize this information to display information on your page (e.g. Hi userX!). Even if someone manages to steal that information, it doesn't give them much information.

As you said, you will have to check the credentials on every request anyway (access token, session cookie, etc.), so it's not an issue to have this non-sensitive data in the local storage.

You can of course go with approach 1, but in my opinion, it's just adding unnecessary traffic.

If it bugs you that it will seem that the user is logged in for ever, then you can also persist some TTL in the local storage, and after that TTL treat the user as logged out.

  • Related