How to Delay Queries Until Access Token is Available in TanStack Query?
I’m using next-auth to store accessToken in the session. When I reload the page, useSession initially has a status of loading, and the accessToken becomes available after a short delay. During this time, queries made with useQuery (from TanStack Query) are sent with an empty accessToken, resulting in 401 Unauthorized errors from the backend.
What I’ve tried so far:
Adding enabled: !!accessToken to every useQuery. This works but was rejected by my team lead.
Setting a global queryFn in QueryClient. However, this would require removing all individual queryFn implementations, which isn’t feasible.
Using QueriesObserver for intercepting queries, but the logs didn’t provide actionable data for handling fetches.
Is there any way to delay queries globally until the accessToken is available? Or does TanStack Query have a beforeAction-like mechanism to manage this? Any advice would be appreciated!
5 Replies
afraid-scarlet•11mo ago
Could you delay it at the fetch/axios level instead? Maybe with interceptors
metropolitan-bronze•11mo ago
await getSession in the queryFn?
unwilling-turquoise•11mo ago
Agree with this. A retry like shown here with
ky might fit your needs: https://github.com/sindresorhus/ky?tab=readme-ov-file#hooksafterresponseGitHub
GitHub - sindresorhus/ky: 🌳 Tiny & elegant JavaScript HTTP client b...
🌳 Tiny & elegant JavaScript HTTP client based on the Fetch API - sindresorhus/ky
unwilling-turquoise•11mo ago
(Axios works too, just showing ky since I prefer it)
Another option depending on your application could be protected routes
unwilling-turquoise•11mo ago