loading...

What is your preferred way to handle authentication in SPA?

bravemaster619 profile image bravemaster619 ・2 min read

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 Cookie, sessionStorage or localStorage.

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 Redirect component.

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:

  • Cookie
  • sessionStorage
  • localStorage

Handle redirect after successful login with:

  • vanilla Javascript
  • Redirect component

Manage login state with:

  • Redux (react-redux, vuex, rxjs etc.)
  • Call a helper function whenever necessary

Verify provided token with:

  • Call /me (or something like that) whenever necessary
  • Trust it first and handle 403 later

Discussion

pic
Editor guide