Auth token expiration pattern? #684
-
In a component, I'm fetching data from an API that requires an auth token. That looks like this:
My fetcher is a simple My issue arises when the token expires (every hour, I'm using Firebase auth), and I switch from another tab back to my app (revalidation on focus). SWR makes the call again, but the API returns a 401 since the token is no longer valid. If I refresh the page, the component gets a refreshed token from the auth handler and the call works again. So I'm curious how others handle this pattern. Since the component isn't re-rendering on focus, and my fetcher function doesn't inherently have access to the auth handler, where should I be handling the 401/token refresh? 🙏 |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 9 replies
-
Here is my fetchWithFirebaseUser pattern.
|
Beta Was this translation helpful? Give feedback.
-
I've run into this, and the swr docs do not do this pattern justice. There's a difference between data dependencies influencing the key where the data is stored / how it is fetched, and access tokens. It doesn't really make sense to cache values based on an access token. This part of the docs:
This tries to present an access token problem but the presented solution is also not ideal for the reasons stated in the OP. You ideally fetch a fresh / current token from within the fetch function itself, not outside of it. This is an important concept that gets lost here, might be worth adjusting. Thanks @matamatanot - this was the path I was going down and good to see it validated. |
Beta Was this translation helpful? Give feedback.
-
Hi! I posted a comment auth patterns about Plugin / middleware. #172 (comment) |
Beta Was this translation helpful? Give feedback.
@harvitronix
Here is my fetchWithFirebaseUser pattern.
I hope this will help.