DEV Community

bravemaster619
bravemaster619

Posted on

1 1

What is your preferred way to handle authentication in SPA?

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

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (1)

Collapse
 
light_eliee profile image
Sagnik Haldar

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.

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more