Suraj Malviya
Suraj Malviya

Reputation: 3783

Implement token refresh in react native with redux saga

I am having a redux-saga middleware to facilitate async store operations and all the API calls are made through sagas. Now implementing OAuth2, I want check if my token is expired then refresh it with refresh token before API call happens. The problem is I am not able to find a solution to intercept the saga to do it. My expiresAt value is in store state which should be used to make decision whether the access token is expired.

What I want to build

An interceptor that would run before each saga and allows to access redux state and also to trigger redux actions. So that I can access expiresAt from store to compare it with current datetime and then if token is expired, trigger refresh api to refresh it and subsequently dispatch store actions and then the real saga can work with updated token.

Approaches found till now:

  1. using effectMiddleWares: This doesn't expose redux state nor allows saga effects to be executed inside since its not generator (worker)
  2. Using wild card action: Have tried to work with this but this doesn't ensure that the worker saga designated to be spawned off for the action triggered waits for this wild card saga to get executed first.
  3. Using global state to store expiresAt and putting logic of token refresh in network layer i.e. past sagas: I am not getting myself convinced with this.

Any help is appreciated. Also, if I am not thinking in right direction with the problem at hand, please let me know about the right way to do it. May be without saga.

Upvotes: 2

Views: 821

Answers (1)

Fyodor Yemelyanenko
Fyodor Yemelyanenko

Reputation: 11848

I may suggest to use separate generator function which will refresh token in background. The process will look like:

  1. Token is accrued by some saga, say login. It will dispatch LOGIN_SUCCESS action to store token in Redux.
  2. Another saga, say refreshToken will listen for LOGIN_SUCCESS actions and start timer. When timer expires, it will either refresh token or dispatch action for saga that will do token refresh.
  3. After successful token refresh, LOGIN_SUCCESS will be dispatched that will bring us to step 2.

As a result, token will always be refreshed and a user will not experience delay when performing operations.

As additional check you may implement private routes to automatically logoff user in case token refresh failure.

Upvotes: 2

Related Questions