How Can I Fix a Refresh Token Race Condition in My Web App?

0
4
Asked By CuriousCoder42 On

Hey everyone! I'm facing an issue with a race condition in my web application. I store the refresh token in a cookie, and when my app loads, I use a `useEffect` hook to call a `/refresh` endpoint to get a new access token, which is stored only in memory for further requests. The problem arises when I refresh the page multiple times in quick succession, causing several `/refresh` requests to fire off at once. If one of those requests may have already revoked the refresh token, the subsequent ones fail, resulting in a mess. I've tried using Promise deduplication and the async-mutex package, but that hasn't worked out because it seems each refresh might create a new JS context. I'm considering a grace period for revoked tokens or a sliding expiry window, but I'm unsure. Any insights on how to resolve this? Thanks!

1 Answer

Answered By TechTinkerer99 On

Have you thought about debouncing the refresh requests? You could store the API call as a promise and return that instead of firing off a new request every time. It helps manage the multiple calls when refreshing the page.

CuriousCoder42 -

Thanks for the tip! I'm not entirely sure I implemented it correctly, but here’s what I tried:

```javascript
let refreshing: Promise | null = null;
const refresh = async () => {
if (refreshing !== null) {
return refreshing;
}

refreshing = (async () => {
try {
// Refresh logic
} finally {
refreshing = null;
}
})();
return refreshing;
};
```

Is that along the lines of what you meant?

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.