Refresh token, wait for refresh on frontend with axios

329 views Asked by At

Is there a way to block all api calls while I wait for the refresh endpoint to return? I know axios has interceptors, but how would I delay all subsequent calls after the access token has expired? Otherwise the user would just get some error messages if it clicks something while the access token is still being refreshed. Seems more complicated than I first thought, am I missing something, is there some library that can already manage this?

I guess I could create a queue and cancel all calls while refresh is still ongoing, and then re-run those requests from the queue, but is there a more elegant/already implemented way?

Not to mention, I should also consider more than one tab could be open with the same session, so probably a BroadcastChannel is needed too. It gets pretty complex...

1

There are 1 answers

3
Matt Morgan On

FWIW I think this is an example of an XY Problem. This answer doesn't say how to do what you asked to do, but rather suggests that you take a different approach to solving the underlying problem.

I would think this is something you'd need to handle on the server side. It doesn't seem appropriate to try to handle it on the client.

Any requests that get sent with a stale token would get routed through the token refresh workflow on the backend. The process of refreshing the token should be idempotent, so multiple successive or concurrent requests to refresh with the old token should return the same new token (or error, if the request is denied.)

If an earlier call had already started the process of refreshing the token, the resolution of these responses would be waiting on the new token to be available (or generated again using the same idempotent method, as mentioned above.)

On the other hand, if the user makes a request that doesn't require a session, that request handling would skip the token validation/refresh logic and just send the appropriate response.