Almost all SPAs use JWT for authentication. I was answering a question of an Indian student in Stack Overflow. The flow is typical. If a user is logged in it will redirect to dashboard page. Otherwise, the default page will be displayed.
I have implemented this flow for a number of times. So I have my own way and I'm kinda stuck on it. So I asked myself: "Hey, how the other guys (in DEV) are doing this? What is the best practice?"
There are multiple choices and ways to handle JWT authentication in an SPA. Let me recall some of them:
We can store jwt tokens in
For redirect, we can simply use
location.href in vanilla JS. or use
redux to susbscribe login state in
App component and let it redirect after a state change with
To get login state again, we can get token from
localStorage(or other "local" storages). We might also go further to ask a server if this is a valid token. Or simply we assume this is a valid token and handle 403 errors from api calls later.
Some devs like
localStorage and others don't. Some devs prefer
redux to handle login state globally. Some guys would love to call
/me to see if the provided token is a valid one.
I normally use
localStorage to store JWT tokens, use
location.href after a successful login and handle 403 errors in all api calls that require authentication/authorization.
What is your preferred way to handle authentications in SPAs? Please share.
Store JWT token in:
Handle redirect after successful login with:
Manage login state with:
- Redux (react-redux, vuex, rxjs etc.)
- Call a helper function whenever necessary
Verify provided token with:
/me(or something like that) whenever necessary
- Trust it first and handle 403 later
Top comments (1)
The problem with using only redux is if a user refreshes his browser his state by default would revert back to default value of "not logged in". I am currently facing that same dilemma , thinking about levering both redux-store along with the local storage for the Oauth flow.
Any suggestions or thoughts would be appreciated.