@codewithagents/openapi-react-query
v3.12.2
Published
Generate typed React Query v5 hooks from OpenAPI 3.1 specs
Maintainers
Readme
@codewithagents/openapi-react-query
Generate typed React Query v5 hooks from an OpenAPI 3.1 spec. Run once, get a fully typed useQuery hook per GET endpoint and a useMutation hook per write operation. No hand-written boilerplate.
- One hook per operation: a
useQueryvariant for every GET and auseMutationfor every write. Types are derived directly from the generated client, no duplication. queryOptions()factories: a plainxxxQueryOptions()factory alongside everyuseQueryhook, enablingqueryClient.prefetchQuery()in Next.js App Router server components and<HydrationBoundary>SSR patterns.- Smart detail hooks: path-param hooks disable automatically when the param is
nullorundefined. Noenabled: !!idat every call site. - Key factories included: structured cache keys per resource (
all(),list(params),detail(id)) for consistent invalidation. - Auto-invalidate on mutation: set
auto_invalidate: trueand mutation hooks invalidate related queries on success, with nouseQueryClientboilerplate required. - Suspense variants: set
suspense: trueto generateuseSuspense*hooks alongside every query hook. - Prettier-clean output: every generated file passes
prettier --checkout of the box.
This package consumes the typed fetch client emitted by openapi-zod-ts: it has a runtime dependency on it, so openapi-zod-ts must run first. The generated hooks derive their data and variable types directly from that client output. It sits alongside the other generators in the toolchain, @codewithagents/openapi-server (service interface plus optional hono | express | fastify | none router) and @codewithagents/openapi-msw (seeded MSW v2 handlers), plus the @codewithagents/api-errors runtime helper. See the petstore-fastify demo for the canonical full-stack example that wires these together.
Install
npm install -D @codewithagents/openapi-react-query openapi-zod-ts
npm install @tanstack/react-query@tanstack/react-query ^5 is a peer dependency, and React Query v5 requires React 18 or later. openapi-zod-ts is a runtime dependency of this generator and must produce its client output first (see Generate).
Configure
See the full configuration reference in the docs for all options including overrides and the --config CLI flag.
Create openapi-react-query.config.json in your project root:
{
"input_openapi": "./openapi.json",
"output": "./src/api",
"stale_time": 30000,
"gc_time": 300000,
"suspense": false,
"auto_invalidate": false,
"infinite_query": "auto"
}| Field | Required | Default | Description |
|---|---|---|---|
| input_openapi | Yes | n/a | OpenAPI 3.x spec (JSON or YAML) |
| output | Yes | n/a | Directory to write generated files (same as openapi-zod-ts output) |
| stale_time | No | 0 | staleTime in ms applied to all useQuery hooks |
| gc_time | No | 300000 | gcTime in ms applied to all useQuery hooks |
| suspense | No | false | When true, generates a useSuspense* variant alongside every query hook |
| auto_invalidate | No | false | When true, mutation hooks auto-invalidate related queries on success |
| infinite_query | No | 'auto' | boolean \| 'auto'. Generates a useXxxInfinite hook for paginated list operations. 'auto' detects paginated GETs; true forces generation, false disables it |
| overrides | No | none | Per-resource cache timing (see Per-resource cache timing) |
Generate
Run both generators, openapi-zod-ts first:
npx openapi-zod-ts
npx openapi-react-queryOr add to package.json:
{
"scripts": {
"generate": "openapi-zod-ts && openapi-react-query"
}
}What gets generated
Given a spec with a /tasks resource, hooks.ts contains:
Key factory: one per resource, used for cache invalidation:
// Key factory (id stays string here; the hook widens it to allow undefined/null)
export const taskKeys = {
all: () => ['tasks'] as const,
list: (params?) => ['tasks', 'list', params] as const,
detail: (id: string) => ['tasks', id] as const,
}queryOptions factories: one per GET operation, for use in RSC / server-side prefetching:
// Plain function, no hooks, safe to call in any context (RSC, loaders, tests)
export function listTasksQueryOptions(params?, options?) {
return queryOptions({
queryKey: taskKeys.list(params),
queryFn: () => listTasks(params),
staleTime: 30000,
gcTime: 300000,
...options,
})
}
export function getTaskQueryOptions(id: string, options?) {
return queryOptions({
queryKey: taskKeys.detail(id),
queryFn: () => getTask(id),
staleTime: 30000,
gcTime: 300000,
...options,
})
}Query hooks: one per GET operation, consuming the factory above:
export function useListTasks(params?, options?) {
return useQuery({
queryKey: taskKeys.list(params),
queryFn: () => listTasks(params),
staleTime: 30000,
gcTime: 300000,
...options, // override any option per call site
})
}
// Detail hook: id widened to allow undefined/null, auto-disabled until id is set
export function useGetTask(
id: string | undefined | null,
options?,
) {
return useQuery({
queryKey: taskKeys.detail(id!),
queryFn: () => getTask(id!),
enabled: id != null && (options?.enabled ?? true),
...options,
})
}Detail hooks (those with a path parameter) automatically disable when the parameter is null or undefined. No more enabled: !!id at every call site.
Mutation hooks: one per POST/PUT/PATCH/DELETE:
export function useCreateTask(options?) {
return useMutation({ mutationFn: (vars) => createTask(vars), ...options })
}
export function useUpdateTask(options?) {
return useMutation({ mutationFn: ({ id, body }) => updateTask(id, body), ...options })
}All types are derived from the generated client, no duplication:
- Data type:
Awaited<ReturnType<typeof listTasks>> - Variables type:
Parameters<typeof createTask>[0]
Next.js App Router SSR prefetch
The generated queryOptions factories work in React Server Components (RSC) without any client-boundary workarounds. Prefetch on the server, then pass the dehydrated cache to the client:
// app/tasks/page.tsx (React Server Component)
import { dehydrate, HydrationBoundary, QueryClient } from '@tanstack/react-query'
import { listTasksQueryOptions } from '@/src/api/hooks'
import { TaskList } from './TaskList'
export default async function TasksPage() {
const queryClient = new QueryClient()
await queryClient.prefetchQuery(listTasksQueryOptions())
// or with params: listTasksQueryOptions({ status: 'open' })
return (
<HydrationBoundary state={dehydrate(queryClient)}>
<TaskList />
</HydrationBoundary>
)
}// app/tasks/TaskList.tsx ('use client')
'use client'
import { useListTasks } from '@/src/api/hooks'
export function TaskList() {
// Cache is already populated from the server; renders without a loading state
const { data } = useListTasks()
return <ul>{data?.map(t => <li key={t.id}>{t.title}</li>)}</ul>
}For detail pages, pass the id as a plain string (the factory does not widen to string | undefined | null):
// app/tasks/[id]/page.tsx (React Server Component)
import { dehydrate, HydrationBoundary, QueryClient } from '@tanstack/react-query'
import { getTaskQueryOptions } from '@/src/api/hooks'
import { TaskDetail } from './TaskDetail'
export default async function TaskPage({ params }: { params: { id: string } }) {
const queryClient = new QueryClient()
await queryClient.prefetchQuery(getTaskQueryOptions(params.id))
return (
<HydrationBoundary state={dehydrate(queryClient)}>
<TaskDetail id={params.id} />
</HydrationBoundary>
)
}The queryOptions factories also work with useSuspenseQuery at the call site:
const { data } = useSuspenseQuery(getTaskQueryOptions(id))Suspense variants
When suspense: true in config, a useSuspense* hook is generated alongside every query hook:
// Regular hook (always generated)
const { data, isLoading } = useGetTask(id)
// Suspense variant (generated when suspense: true)
// data is never undefined: wrap parent in <Suspense fallback={...}>
const { data } = useSuspenseGetTask(id)Works with React 18 <Suspense> boundaries and Next.js App Router loading states.
Auto-invalidate on mutation success
When auto_invalidate: true in config, mutation hooks automatically invalidate related cache entries on success. No useQueryClient boilerplate at the call site:
// With auto_invalidate: true, invalidation is generated inside the hook
const create = useCreateTask()
create.mutate({ title: 'New task' })
// taskKeys.all() is automatically invalidated on success
const update = useUpdateTask()
update.mutate({ id: '123', body: { title: 'Updated' } })
// taskKeys.all() AND taskKeys.detail('123') are invalidated on successInvalidation scope:
POST→ invalidatesresourceKeys.all()PUT/PATCH→ invalidatesresourceKeys.all()+resourceKeys.detail(id)DELETE→ invalidatesresourceKeys.all()
Your onSuccess callback (if provided in options) is called after invalidation.
Per-resource cache timing
Use overrides in config to set different staleTime / gcTime per resource:
{
"input_openapi": "./openapi.json",
"output": "./src/api",
"stale_time": 30000,
"gc_time": 300000,
"overrides": {
"platforms": { "stale_time": 86400000 },
"settings": { "stale_time": 5000, "gc_time": 60000 }
}
}The override key is the resource name as it appears in the API path (e.g. platforms for /api/v1/platforms). Non-overridden resources use the global stale_time / gc_time.
Use it
import { useListTasks, useCreateTask } from './src/api/hooks'
function TaskList() {
const { data, isLoading } = useListTasks({ status: 'open' })
// With auto_invalidate: true, useCreateTask invalidates taskKeys.all() automatically
const create = useCreateTask()
if (isLoading) return <Spinner />
return (
<>
{data?.map(task => <Task key={task.id} task={task} />)}
<button onClick={() => create.mutate({ title: 'New task' })}>Add</button>
</>
)
}Multiple specs
Use --config to point at different config files per vendor:
npx openapi-zod-ts --config ./config/payments.config.json
npx openapi-react-query --config ./config/payments.config.jsonRelative paths in each config resolve from the config file's directory.
Testing
The generator also produces a test-utils.ts file alongside hooks.ts. It exports createTestQueryClient() and createWrapper() to eliminate test boilerplate. See Testing your hooks in the docs for copy-pasteable Vitest examples using MSW.
To mock the HTTP layer those tests hit, @codewithagents/openapi-msw generates seeded MSW v2 handlers from the same OpenAPI spec, so the request mocks stay in sync with the client the hooks call.
Troubleshooting
See the Troubleshooting section in the docs for common issues: cache not invalidating, detail hooks firing with nullish ids, and hooks not working in React Server Components.
License
MIT
