Should access token be included in query key?
I'm calling a third party api requiring an access token. The precise endpoint I'm hitting is uniquely identified by a resource id, so I include that id in the query key.
Does
getToken()
get called every time the query fetches, or does the query cache the function call with the original token result?5 Replies
fair-rose•3y ago
Is it working okay? What you have looks right, and using a getter function to access the token should ensure against a stale token value.
To the general question of including access token in the query key, I'd avoid that from a security standpoint.
exotic-emerald•3y ago
I'd recommend You set your token on the HTTP layer directly rather than providing it as a prop to each query fn. It feels more natural. If you are using Axios here's how I do it

typical-coralOP•3y ago
I saw someone mention request interceptors in a past thread, but I’m just using fetch within NextJS
Do you know if there’s an equivalent?
Yep it's working fine! I realized I don't want to include it because I don't want the data to be refetched when the token refreshes.
I got insecure in my implementation after reading in the docs you should include in function dependencies in the query key, but it seems I don't really have to do that here.
If I did though, how exactly would that be insecure? The token already is public on the client no?
fair-rose•3y ago
It doesn't necessarily change your security posture, it's more about security hygiene - access tokens may have to be exposed in the client, but we should do so as minimally possible. But yeah, to your point, it's more about best practices than avoiding any specific risk.
On the function dependencies array pattern, whether for query keys or React's useEffect style hooks, I've personally jumped ship on the guidance around including all dependencies. If you only include dependencies that trigger a change, the other values in the function will be read from the same scope at the same time. To be fair, react-query guidance that I've seen doesn't say include all deps like React does about useEffect.
like-gold•3y ago
Yep it's working fine! I realized I don't want to include it because I don't want the data to be refetched when the token refreshes.that's the reason to not include it. It's not a reactive dependency, it's something you want to "send along". So excluding it is fine, as long as you don't closure over it, our lint-rule will not tell you to include it either. if
await getToken()
always reads latest values, you're good 👍