Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to alert when Session (JWT) has expired in React/Redux

What approaches are there to alert user about expired session in React/Redux application?

The server authenticates user with JWT token, and React really doesn't know the existence of such token, browser handles it automatically. In case of fetching and posting Redux either sets data or error in state.

Is the typical way to passively check the response when trying to access API endpoint, use the expires field to set client side timeout, actively assure validity of session or some other technique? I'm especially concerned about the unsaved changes user makes and would like to inform user about ended session as soon as possible.

like image 470
Tuomas Toivonen Avatar asked Oct 19 '22 05:10

Tuomas Toivonen


1 Answers

My current approach is to store the jwt in the localStorage, when the application starts, I am loading the token, trying to load user data with the token, if it fails, just redirect to /login

Then I am using the jwt only in the api module, not in the store at all.

My Api module knows based on requests, when to use the token and when not

If the api module recognizes a failed authentication, it also removes the token from the localStorage.. so next time it cannot be loaded.

My api module, which is also separated from redux, knows when to use jwt, and when not.

To make this work more abstract I've created a middleware, which reacts on every action if the payload is an error and the value Not Authenticated

this is the error I am trowing in the api module, if the server response fails because of auth. The actionCreator just dispatches the error in catch and the middleware reacts on it.

So actually its up to you how to do it, all the code I am talking about is ~100 LOC or so.. just some methods which are handling this things.

like image 105
webdeb Avatar answered Oct 20 '22 23:10

webdeb