title: pre-emptive refresh of expired JWT token
body: <p>All of the solutions I've found while searching react to a 401 response from an API call before triggering logic to refresh the expired token. In my case, I'm using <strong>react-cognito</strong> which puts the expiry time in the redux store under <code>cognito.user.signInUserSession.idToken.payload.exp</code> (integer representing unix time).</p>
  
  <p>I would like to try and implement a scheme where expiry is pre-empted and I'd like to keep this logic separated from my API call code, if practical.</p>
  
  <p>One option I explored is setting a timeout for <code>currentTime - expiryTime - someBuffer</code>, but this may be 50 minutes long or more and I've read that long-running timeouts can often be unreliable, having strange performance especially when the browser tab is not in-focus. </p>
  
  <p>Another option I considered was a saga that runs in a loop, initiated by the <code>LOGGED_IN</code> action and ended by the <code>LOGGED_OUT</code> action, that checks for an almost expired token and refreshes it. On mobile, my understanding is that code execution is paused while the browser is in the background - as such this approach would have an edge case where if the user foregrounds the browser just after token expiry then there's a window of time equal to the loop interval where API calls will 401. The loop interval can be made smaller but the edge condition could never be eliminated.</p>
  
  <p>Is there some scheme that can reliably fire an event/action just before token expiry or, in the case of mobile browsers, fire immediately upon execution-resume if foregrounding happens after the desired refresh time?</p>
  
  <p>Thanks!</p>
  
  <p>David</p>