Vue Query 06 ⚡ Type-Safe queryOptions & Key Factories — Structuring hierarchical query-key factories and reusable queryOptions() helpers
In the early stages of a Vue Query project, developers often pass query keys as simple arrays like ['users'] or ['post', id]. However, as an application scales to include dozens or hundreds of queries, these “magic strings” become a source of fragility. If one part of the app invalidates ['user-list'] but the fetcher is actually using ['users'], the cache will fail to update silently. Furthermore, TypeScript cannot easily track the relationship between a specific key and the data type it returns without a more structured approach.
To solve this, Vue Query (via TanStack Query v5) introduced the queryOptions helper and encourages the use of Key Factories. A Key Factory is a centralized object that generates hierarchical keys, ensuring that invalidating a “parent” key (like ['users']) correctly affects all “child” queries (like ['users', 'list']). The queryOptions utility takes this a step further by bundling the query key, the fetch function, and configuration into a single, type-safe object that can be reused across components, prefetching logic, and router guards.
This chapter details the transition from ad-hoc query management to a structured, industrial-grade architecture. We will explore how to build hierarchical key factories, how to utilize the queryOptions helper to eliminate boilerplate, and how to organize these helpers into “Query Modules” that serve as a single source of truth for your application’s data layer.
Key point: Centralizing query keys in factories and using the queryOptions helper ensures cache consistency across the application while providing end-to-end TypeScript inference for both keys and data.
Why exists
The Magic String Problem. When query keys are scattered across different .vue files as raw arrays, it is impossible to track them. A typo in a single character of a key prevents cache invalidation from working, and these bugs are notoriously difficult to find because they don’t throw runtime errors.
The Invalidation Hierarchy Problem. Often, you want to invalidate every query related to “Users” when a user is deleted. If your keys are structured as ['users', 'list'] and ['users', 'detail', 1], invalidating ['users'] works. A Key Factory enforces this structure, preventing developers from creating flat or inconsistent keys like ['all-users'] and ['user-1'].
The Prefetching Boilerplate Problem. Prefetching data in a router guard or an event handler usually requires duplicating the queryKey and queryFn. If the logic in the component changes but the prefetch logic isn’t updated, the app fetches the wrong data. queryOptions allows you to define this once and use it everywhere.
The Type Drift Problem. In a standard useQuery call, the link between the key and the returned data type is implicit. If the API response changes, you have to manually update types in every component. By using queryOptions, the type of the queryFn is tied to the result, and TypeScript ensures that the data returned is always correctly typed.
The IDE Discoverability Problem. In a large codebase, it’s hard to know which queries are already available. A centralized Key Factory allows developers to use IDE autocomplete to see every available query in the system, significantly speeding up development and preventing the creation of redundant queries.
a. Hierarchical Key Factories
A Key Factory is a simple JavaScript object that organizes keys into levels. The most common pattern is to have a “base” key, then “lists” and “details” categories. This hierarchy is crucial because TanStack Query’s invalidation works by matching prefixes. If you invalidate ['todos'], any key starting with ['todos'] is marked as stale.
// src/api/keys.ts
export const todoKeys = {
all: ['todos'] as const,
lists: () => [...todoKeys.all, 'list'] as const,
list: (filters: string) => [...todoKeys.lists(), { filters }] as const,
details: () => [...todoKeys.all, 'detail'] as const,
detail: (id: number) => [...todoKeys.details(), id] as const,
};
Using as const is a TypeScript best practice here. it tells the compiler that the array is a “tuple” with specific values rather than a general string[]. This allows Vue Query to provide much stricter type checking when you use these keys in useQuery or queryClient.invalidateQueries.
In this structure, calling todoKeys.detail(5) returns ['todos', 'detail', 5]. If you call queryClient.invalidateQueries({ queryKey: todoKeys.all }), it will target every single todo-related query. If you only want to refresh the lists, you target todoKeys.lists().
b. The queryOptions Helper
Introduced in TanStack Query v5, queryOptions is a utility function that accepts an object containing queryKey, queryFn, and other options, and returns that same object with enhanced type metadata. Its primary purpose is to create a reusable configuration that is “portable.”
import { queryOptions } from '@tanstack/vue-query';
import { getTodo } from './api';
export const todoDetailOptions = (id: number) => {
return queryOptions({
queryKey: ['todos', 'detail', id],
queryFn: () => getTodo(id),
staleTime: 1000 * 60 * 5, // 5 minutes
});
};
The magic of queryOptions is that it makes useQuery calls incredibly clean. Instead of passing multiple arguments, you just spread the options. Because the options object contains the key and the function, Vue Query has everything it needs to execute the query.
// Inside a component
const { data } = useQuery(todoDetailOptions(props.id));
This helper also works perfectly with queryClient.fetchQuery and queryClient.prefetchQuery. Because the options object is typed, fetchQuery(todoDetailOptions(5)) will correctly infer that it returns a Promise<Todo>, providing end-to-end type safety from the API definition to the prefetch call.
c. The Module Pattern: Combining Factories and Options
The most robust architecture for Vue Query is the “Query Module.” This is a file that exports both the Key Factory and a collection of queryOptions functions. This centralizes all data-access logic for a specific domain (like “Users” or “Orders”) in one place.
// src/api/todo-queries.ts
import { queryOptions } from '@tanstack/vue-query';
export const todoKeys = {
all: ['todos'] as const,
detail: (id: number) => [...todoKeys.all, 'detail', id] as const,
};
export const todoQueries = {
detail: (id: number) => queryOptions({
queryKey: todoKeys.detail(id),
queryFn: () => fetch(`/api/todos/${id}`).then(res => res.json()),
}),
list: (category: string) => queryOptions({
queryKey: [...todoKeys.all, 'list', { category }],
queryFn: () => fetch(`/api/todos?cat=${category}`).then(res => res.json()),
})
};
In your components, you simply import todoQueries. This makes your components highly declarative. They don’t need to know how to fetch data or what the cache key is; they just declare which query they need.
This pattern also makes testing significantly easier. You can mock the entire todoQueries module or verify that a component is calling the correct query by checking the options object it passes to useQuery.
Complete Example Session
// ============================================
// PART 1: THE HIERARCHICAL KEY FACTORY
// ============================================
export const userKeys = {
all: ['users'] as const,
profiles: () => [...userKeys.all, 'profile'] as const,
profile: (id: string) => [...userKeys.profiles(), id] as const,
settings: (id: string) => [...userKeys.profile(id), 'settings'] as const,
};
// ============================================
// PART 2: THE REUSABLE QUERY OPTIONS
// ============================================
import { queryOptions, useQuery, useQueryClient } from '@tanstack/vue-query';
export const userQueries = {
// Detail query
profile: (id: string) => queryOptions({
queryKey: userKeys.profile(id),
queryFn: async () => {
const res = await fetch(`/api/users/${id}`);
return res.json();
},
staleTime: 60 * 1000,
}),
// Nested settings query
settings: (id: string) => queryOptions({
queryKey: userKeys.settings(id),
queryFn: () => fetch(`/api/users/${id}/settings`).then(r => r.json()),
})
};
// ============================================
// PART 3: USAGE IN COMPONENT
// ============================================
// <script setup>
// const { data: profile } = useQuery(userQueries.profile('user_123'));
// </script>
// ============================================
// PART 4: PREFETCHING IN A ROUTER GUARD
// ============================================
// router.beforeEach(async (to) => {
// const queryClient = useQueryClient();
// await queryClient.prefetchQuery(userQueries.profile(to.params.id));
// });
// ============================================
// PART 5: CACHE INVALIDATION
// ============================================
// const queryClient = useQueryClient();
// // Invalidates ['users', 'profile', 'user_123'] and ['users', 'profile', 'user_123', 'settings']
// queryClient.invalidateQueries({ queryKey: userKeys.profile('user_123') });
The code above demonstrates a complete lifecycle: organizing keys, defining portable options, using them in components/guards, and performing hierarchical invalidation.
Quick Reference
Key Factory Patterns
| Level | Function Name | Return Key Example |
|---|---|---|
| Base | all | ['users'] |
| Context | lists() | ['users', 'list'] |
| Filtered | list(filter) | ['users', 'list', { filter: 'active' }] |
| Identity | detail(id) | ['users', 'detail', 5] |
queryOptions Return Object
| Property | Type | Description |
|---|---|---|
queryKey | QueryKey | The unique cache identifier |
queryFn | QueryFunction | The function that fetches the data |
staleTime | number | Time until data is considered old |
gcTime | number | Time until unused data is deleted |
Invalidation Targets
| Target Key | Will Invalidate |
|---|---|
userKeys.all | All users, lists, and details |
userKeys.lists() | All lists, regardless of filters |
userKeys.profile(1) | Detail for ID 1 and all sub-resources (settings) |
Best Practices
✅ Do This:
// Always use 'as const' for keys to preserve tuple types
const key = ['users', id] as const; // ✅
// Centralize queries in a dedicated query file
export const userQueries = { ... }; // ✅
// Spread queryOptions into useQuery for brevity
const { data } = useQuery(userQueries.detail(id)); // ✅
// Name keys hierarchically (General -> Specific)
['users', 'detail', id] // ✅
❌ Don’t Do This:
// Don't use raw strings in components
useQuery({ queryKey: ['user', id] }); // ❌
// Don't create flat keys that break hierarchy
['user-detail-5'] // ❌
// Don't repeat fetch logic in prefetch calls
queryClient.prefetchQuery({ queryKey: ['u', id], queryFn: f }); // ❌
// Don't pass queryOptions.queryKey separately
useQuery({ queryKey: userQueries.detail(id).queryKey }); // ❌
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Invalidation Failure | Typing keys manually and making a typo | Use the Key Factory methods exclusively |
| Missing Type Inference | Forgetting as const on key definitions | Always append as const to key arrays |
| Circular Dependencies | Factory and Options importing each other | Put them in the same file or a specific queries/ module |
| Stale Prefetch | Prefetch logic uses different config than component | Use the exact same queryOptions helper for both |
| Key Overlap | Different factories using the same base string | Prefix keys with domain names: ['domain', 'resource'] |
Real-World Examples
1. Simple Factory Method
detail: (id: number) => ['posts', 'detail', id] as const
2. Factory with Object Filters
list: (f: Filters) => ['posts', 'list', { ...f }] as const
3. Reusable Detail Options
const postDetail = (id: number) => queryOptions({ queryKey: keys.detail(id), queryFn: () => getPost(id) })
4. Prefetch in Nuxt/Vue Guard
await queryClient.prefetchQuery(userQueries.profile(id))
5. Hierarchy Invalidation
queryClient.invalidateQueries({ queryKey: userKeys.all })
6. Infinite Query Options
const postPages = queryOptions({ queryKey: ['posts', 'infinite'], queryFn: fetchPosts })
7. Using Options in useSuspenseQuery
const { data } = useSuspenseQuery(userQueries.profile(id))
8. Combining Options with enabled
useQuery({ ...userQueries.detail(id), enabled: !!id })
9. Query Client Fetch
const data = await queryClient.ensureQueryData(userQueries.list('all'))
10. Extracting types from options
type UserData = ReturnType<typeof userQueries.profile>['queryFn']
Visual
Hierarchical Key Structure
┌──────────────────────────────────────────────────────────┐
│ KEY FACTORY HIERARCHY │
│ │
│ ['users'] ◄─────────────────── ALL (Root) │
│ │ │
│ ├─ ['users', 'list'] ◄───── LISTS (Group) │
│ │ └─ ['users', 'list', {status: 'active'}] │
│ │ │
│ └─ ['users', 'detail'] ◄──── DETAILS (Group) │
│ └─ ['users', 'detail', 5] ◄── IDENTITY (Item) │
│ └─ ['users', 'detail', 5, 'logs'] │
└──────────────────────────────────────────────────────────┘
The queryOptions Flow
┌──────────────────────────────────────────────────────────┐
│ queryOptions() Helper │
│ │
│ Input Object: Output Object: │
│ { { │
│ queryKey, ───▶ queryKey, │
│ queryFn, queryFn, │
│ staleTime staleTime, │
│ } [Types & Metadata] │
│ } │
└──────────────┬───────────────────────────┬───────────────┘
│ │
▼ ▼
useQuery(options) prefetchQuery(options)
Invalidation Propagation
┌──────────────────────────────────────────────────────────┐
│ ACTION: Invalidate ['users', 'detail'] │
│ │
│ TARGETS: │
│ [MATCH] ['users', 'detail', 1] ✅ │
│ [MATCH] ['users', 'detail', 1, 'logs'] ✅ │
│ [MISS ] ['users', 'list'] ❌ │
└──────────────────────────────────────────────────────────┘
Summary
| Item | Value |
|---|---|
| Key Strategy | Hierarchical Key Factories |
| Reusable Helper | queryOptions() |
| TypeScript | as const for tuple preservation |
| Invalidation | Prefix-based matching |
| Organization | Query Module Pattern |
| Prefetching | Uses same queryOptions as useQuery |
| Maintenance | Low (Single Source of Truth) |
Key takeaways:
- Key Factories eliminate magic strings. By using functions to generate keys, you ensure that every part of your application uses the exact same string structure for the same data .
- Hierarchy enables mass invalidation. Structure your keys from general to specific. Invalidating a parent key automatically cleans up all child queries, keeping the UI in sync .
queryOptionsis the ultimate DRY tool. Define your query key, fetch function, and settings once. Reuse this object foruseQuery,prefetchQuery, andensureQueryData.- TypeScript is built-in. Using
queryOptionsprovides perfect inference. The data returned byuseQueryis automatically typed based on the return value of thequeryFn. - Standardize on “Query Modules”. Group your keys and options by domain (e.g.,
userQueries.ts). This serves as a clear API manifest for your application’s front-end . - Preserve types with
as const. When defining arrays for keys in a factory, useas constto ensure TypeScript treats them as immutable tuples rather than simple string arrays .
Remember: Stop passing raw arrays and functions to your query hooks. Centralize them into factories and queryOptions to transform your data layer into a type-safe, predictable, and maintainable system.
Stop using slow, ad-bloated tool sites! 🤮
🔎 Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)
⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free
🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!