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

What are the approaches to notifying a user about an expired session in a React / Redux application?

The server authenticates the user using the JWT token, and React really does not know about the existence of such a token, the browser processes it automatically. In the case of downloading and publishing, Redux either sets the data or the error state is in state.

Is a typical way to passively check the response when trying to access the API endpoint, use the expires field to set the timeout on the client side, actively confirm the authenticity of the session or some other technique? I am particularly concerned about unsaved user changes and would like to inform the user as soon as possible about the completed session.

+5
source share
1 answer

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

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

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

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

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

To make this work more abstract, I created middleware that responds to every action if the payload is error and the value is Not Authenticated

this is an error that I pick up in the api module if the server response fails due to auth. actionCreator simply sends an error to catch , and the middleware responds to it.

So, actually it is up to you how to do this, all the code I'm talking about is ~ 100 LOC or so .. just some methods that handle these things.

+3
source

All Articles