Authentication, Tanstack Query, React Router
As part of an application I'm building we're looking at using tanstack query in combination with a few other libraries to handle authentication and our API layer.
The problem is that if an authentication error is thrown in a query because a refresh token couldn't be refreshed or something similar, there's no way to catch that without making all queries
throwOnError
and handling the auth error from the router.
Any ideas or answers would be very much appreciated.10 Replies
genetic-orange•2y ago
Easiest is probably just handling that separately from react query.
I use axios, with axios-auth-refresh to intercept 401s and perform refresh before retrying them. My axios-auth-refresh refresh method just clears the user session from the browser if it itself gets an error response. Router picks that up and navigates accordingly
React query can then call axios get/post either directly or through wrappers and any 401 is handled by axios-auth-refresh before any response even reaches react query.
conventional-tanOP•2y ago
What happens when there's an error refreshing the token or if the refresh token is expired?
genetic-orange•2y ago
Catch it in the refresh handler. Then do whatever it is you have to do to log your user out. Then the query errors but it doesn't matter because you probably navigated to the login screen and cleared the queryclient cache already
conventional-tanOP•2y ago
Awesome, I'll give it a go today. Though I'll probably use oauth4webapi and my own fetch client instead of axios
genetic-orange•2y ago
I think the key thing is having your 401s caught and refresh performed before the queryFn returns a result. If you're depending on a "refresh" query on a timer or something it will probably be difficult
foreign-sapphire•2y ago
I can say I did something similar. Using
ky
not axios
with a afterResponse
hookconventional-tanOP•2y ago
Awesome, I ended up including an async getToken() function that handles getting a refresh token if the currently cached token isn't fresh.
vicious-gold•2y ago
a guide or snapshot of how you accomplished this?
conventional-tanOP•2y ago
I'll upload the file that I created to make this work
conventional-tanOP•2y ago