Where Should Your TanStack Queries Live?

TanStack Query takes care of the parts of data fetching nobody enjoys writing, like caching, deduplication, retries and refetching in the background. It also gives you more than one way to do almost everything. A query can be written inline in a component or wrapped in a composable, its key can be any array you like, and the same data can be read with useQuery or fetchQuery.
Each of those choices is fine alone, but in a large codebase they add up. Put a few people on the same code and you get every style at once, until nobody can say where a query should live or which style to copy.
This post is how we answered that in our codebase, and how the answer changed once real code pushed back. The examples follow a small account service with two endpoints, the signed-in user's info and a user's products, because everyone has written those at some point.
Leaving the Interceptors Behind
The story starts before TanStack Query was in the project. Caching and deduplicating requests used to be our own job, done in axios interceptors we'd written in-house. They worked, but they were tiring to maintain, and they kept us on axios just as we wanted to move to native fetch. Leaving axios would have meant writing all of that again.
TanStack Query took that job off our hands, and it doesn't care which HTTP client sends the request. Adopting it, though, meant moving every request we had, and the product couldn't stop for that. New features had to keep shipping while the code under them changed.
So the move had to be gradual. Axios and the old services stayed where they were, and TanStack Query came in next to them, one endpoint at a time. Old and new code would live side by side for a long while, which turned the question from the start into a very practical one. Where does the new code go?
One Folder per Controller
All our API handlers lived in one folder, so we opened a second one beside it and called it api. Before filling it, I wanted to leave the old folder's biggest problem behind. Its services were grouped by feature, so when two features needed the same request, each wrote it again in its own file. An endpoint is hard to find when you have to guess which feature owns it.
I looked at a lot of ways to organize API code and settled on colocation, grouped by the backend instead of by our features. Every folder under api/services mirrors one controller on the backend. A request to /account/user/info lives in account, and a request to /billing/invoices lives in billing. The URL answers "where should I add this?" before anyone has to ask.
Every service folder has the same files, and its index.ts exports them together as one service.
api/
├── services/
│ ├── account/
│ │ ├── index.ts
│ │ ├── service.ts
│ │ ├── query-keys.ts
│ │ └── composables.ts
│ └── billing/
├── utils/
├── api-client.ts
└── query-client.tsThe First Version
That settled where an endpoint lives. How a query is written came next, and the first answer split it across three files.
service.ts holds the requests themselves, and they know nothing about TanStack Query. Partly that's the migration, since the old code can import a request and call it directly. But I also think an endpoint and a query are different things, and they should stay apart even once the migration is done.
export async function fetchUserInfo({ configOptions = {} } = {}) {
return apiClient.get('/account/user/info', configOptions)
}query-keys.ts gives each request a key. Every key is built by the same small helper, so every key has the same shape, with the service first, then the action, then the params.
export const accountQueryKey = {
fetchUserInfo: () => createQueryKey('account', 'user-info'),
// ['account', 'user-info']
fetchUserProducts: params => createQueryKey('account', 'user-products', params),
// ['account', 'user-products', { userId: 42 }]
}The shape matters because TanStack Query matches keys by their prefix when you invalidate them. Since every key starts the same way, any prefix of a key is a meaningful group, and the same helper covers three levels of invalidation.
const queryClient = useQueryClient()
// everything in the account service
queryClient.invalidateQueries({ queryKey: ['account'] })
// every user's products
queryClient.invalidateQueries({ queryKey: accountQueryKey.fetchUserProducts() })
// one user's products
queryClient.invalidateQueries({ queryKey: accountQueryKey.fetchUserProducts({ userId: 42 }) })composables.ts is where the key and the request finally meet. We didn't want every component importing both and pairing them by hand, because nothing would stop someone from pairing a key with the wrong request. A composable pairs them once and sets the defaults that query should have.
export function useFetchUserInfoQuery({ options = {} } = {}) {
return useQuery({
queryKey: accountQueryKey.fetchUserInfo(),
queryFn: () => accountService.fetchUserInfo(),
...options,
})
}
export function useFetchUserProductsQuery({ params, options = {} }) {
return useQuery({
queryKey: () => accountQueryKey.fetchUserProducts(toValue(params)),
queryFn: () => accountService.fetchUserProducts({ params: toValue(params) }),
enabled: () => Object.values(toValue(params)).every(Boolean),
staleTime: 3 * 60 * 1000,
...options,
})
}From then on, a component called the composable it needed and, most of the time, didn't have to override anything.
Where It Cracked
The first crack came from the migration itself. A lot of data was still loaded from inside our stores, and calling one of these composables there went wrong. A store lives as long as the app does, so a query created inside one is observed for the whole session. It never went inactive and never got cleaned up, long after any screen needed it.
So stores skipped the composables and talked to the query client directly. That worked, but it meant writing the key and the request side by side again, which is exactly the pairing the composables were there to prevent.
const products = await queryClient.ensureQueryData({
queryKey: accountQueryKey.fetchUserProducts(params),
queryFn: () => accountService.fetchUserProducts({ params }),
})There were smaller gaps too. The key for a whole service was a hand-typed ['account'], and a request could still be written in a few slightly different ways, typed or untyped, with its URL put together however the author liked.
Those gaps were easy to live with while people wrote all the code. Then AI agents started writing a good share of it. An agent learns from whatever code sits nearby, so if there are three ways to write an endpoint, it will happily write all three. For an agent to add an endpoint correctly, the codebase had to offer exactly one way to do it.
The Second Version
So the second version had a single goal, that every piece can only be written one way. We kept the colocation and changed what goes inside each folder. The composables are gone, and two new files take their place.
api/
├── services/
│ ├── account/
│ │ ├── index.ts
│ │ ├── service.ts
│ │ ├── query-keys.ts
│ │ ├── query-options.ts
│ │ └── mutation-options.ts
│ └── billing/
├── utils/
├── api-client.ts
└── query-client.tsEach piece from the first version now goes through one function that every definition has to use. Requests are written with defineEndpoint, which takes the request's params and response as types. If an endpoint has required params, its config becomes required too, so a call that forgets them doesn't compile.
export const fetchUserInfo = defineEndpoint<{ response: UserInfo }>(({ signal }) => {
return apiClient('/account/user/info', { signal })
})
export const fetchUserProducts = defineEndpoint<{
params: { userId: number }
response: Array<Product>
}>(({ params, signal }) => {
const url = defineUrl('/account/users/{userId}/products', params)
return apiClient(url, { signal })
})defineUrl fills the path params into the template and throws when a required one is missing, so a request to /account/users/undefined/products never leaves the browser. Every request also passes on the signal TanStack Query hands it, so a query nobody needs anymore cancels its own request. And apiClient runs on fetch now, which is where all of this started.
Query keys come from defineQueryKeys. It takes the service name and its actions, builds the same keys as before, and adds an all() key for the whole service, so the hand-typed ['account'] is gone.
export const accountQueryKeys = defineQueryKeys('account', {
fetchUserInfo: 'fetch-user-info',
fetchUserProducts: 'fetch-user-products',
})
accountQueryKeys.fetchUserProducts({ userId: 42 }) // ['account', 'fetch-user-products', { userId: 42 }]
accountQueryKeys.all() // ['account']The composables became query-options.ts, and this is the biggest change. Each query is now a queryOptions object, the pattern TanStack Query itself recommends. The key, the request and the defaults are still paired in one place, but the result is plain data rather than a composable, so it works inside a component and outside one alike.
export function userInfoQueryOptions() {
return queryOptions({
queryKey: accountQueryKeys.fetchUserInfo(),
queryFn: ({ signal }) => accountService.fetchUserInfo({ signal }),
staleTime: 3 * 60 * 1000,
})
}
export function userProductsQueryOptions(params: MaybeRefOrGetter<{ userId?: number }>) {
return queryOptions({
queryKey: () => accountQueryKeys.fetchUserProducts(toValue(params)),
queryFn: computed(() => {
const { userId } = toValue(params)
if (!userId) return skipToken
return ({ signal }) => accountService.fetchUserProducts({ params: { userId }, signal })
}),
})
}skipToken took over from enabled along the way. The query function now says for itself when it can't run, so while a required param is missing, there's no function around that could send the request. The check and the request sit in one expression instead of two options that have to agree, and TypeScript knows userId is there by the time the request is built.
A component and a store now use the very same object.
// in a component
const { data: products } = useQuery(userProductsQueryOptions(() => ({ userId: userId.value })))
// in a store
const products = await queryClient.ensureQueryData(userProductsQueryOptions({ userId }))That closes the crack from the first version. The store no longer writes the key and the request side by side, because nobody does anymore.
Mutations follow the same idea in mutation-options.ts. A mutation also knows which queries it makes stale, so updating the user's contact info refreshes the user info wherever it's shown.
export function updateContactInfoMutationOptions() {
return mutationOptions({
mutationFn: (params: ContactInfo) => accountService.updateContactInfo({ params }),
onSuccess: (_data, _variables, _result, context) => {
context.client.invalidateQueries({ queryKey: accountQueryKeys.fetchUserInfo() })
},
})
}What We Took Away
The goal was never to take TanStack Query's flexibility away. Any option can still be set where a query is used, by spreading the query options and adding to them. What we took away is the choice of how to define one. An endpoint goes in service.ts, its key in query-keys.ts, and its defaults in query-options.ts, the same way in every folder.
That's what makes it work for people and agents alike. Anyone adding an endpoint can copy a neighbor and get it right.
It isn't finished, though. The step I keep coming back to is defining a whole service in one call.
export const accountService = defineService('account', {
fetchUserInfo: ({ signal }) => {
return apiClient('/account/user/info', { signal })
},
fetchUserProducts: ({ params, signal }) => {
const url = defineUrl('/account/users/{userId}/products', params)
return apiClient(url, { signal })
},
})It's tidy, but we still like importing each endpoint on its own, so for now it stays an idea.
I don't think this is the answer for every codebase. It's the one our own mess led us to, and yours may well lead somewhere else. If it does, I'd honestly love to hear where your queries ended up. And when ours crack again, I'll be back here with the fix.