Jeff Tian
Jeff Tian

Reputation: 5903

What is the best Practice to detect if user has signed in or not in Single Page Application?

The Single Page Application is a pure client side javascript project, say webpack, and the application has a header that will always appear in the right top corner:

enter image description here

That is, if a user has logged in, then show the user's avatar. If user has not logged in yet, show the login button.

The question is how can the pure client side know if the user has logged in or not?

My current implementation is show "login button" firstly, and then the page sends a XHR request to the server try to get the user information.

If the request succeeded, then parse the user's avatar url and replace the "login button" with the avatar, otherwise.

If the request failed with 401 http status code, then the client side know the user has not logged in yet, so keep the "login button".

But the caveats here is: There would be many 401 requests as most of the time, the page is opened by the anonymous users, which will show a red error message in the console.

Can anyone share some thoughts here?

Upvotes: 0

Views: 1130

Answers (1)

lionbigcat
lionbigcat

Reputation: 993

"how can the pure client side know if the user has logged in or not?"

I use jsonwebtoken on my SPA. When a user logs in, I store the JWT token on the browser localstorage.

To check if the user is logged in, I check the expiration date of the token stored in the browser. If the user is logged in, then send a fetch request to the server to get the user info.

"There would be many 401 requests as most of the time"

I believe your problem here is more to do with catching HTTP error requests. If the user is not logged in after your client-side checks, why send a request to the server? Handle it with your SPA -> e.g. reroute to a login page.

Upvotes: 1

Related Questions