TanStack Query codegen without OpenAPI: a query key factory and queryOptions generator for the TypeScript API functions you already have
Playground · Architecture · npm · Changelog · 한국어
React Query Helper is a TanStack Query (React Query) v5 code generator: it reads your existing TypeScript API functions and writes the query keys and queryOptions, infiniteQueryOptions and mutationOptions factories for them. No OpenAPI or Swagger spec needed, and your fetch or axios layer stays as it is. When the API changes, watch regenerates the files and generate --check catches stale output in CI.
Try it in the browser → Paste an API function and see the generated keys and options. Nothing to install.
Version notice: This README describes 2.x. Check the npm badge above for the published version. If you use 1.x, read the 1.3.0 docs and migration guide. To try changes not yet published, install from source.
TanStack Query already provides queryOptions for reusable, type-safe query definitions. But you still connect each API function to those options by hand:
export const userOptions = (id: string) =>
queryOptions({ queryKey: ["users", id], queryFn: () => getUser(id) });Across hundreds of API functions and several developers, key naming, the link between functions and options, and keeping them in sync when arguments change become repetitive work. React Query Helper fixes that connection in a generator. TanStack Query still handles caching, retries and fetching; this tool generates only the code that connects your API to it.
- Your API layer stays. Generated files go to
outputDirand only import your API functions, so existingfetchor axios wrappers with auth headers, interceptors, error handling and response transforms, and your business logic, stay as they are. Orval, Kubb and Hey API generate the API functions themselves from an OpenAPI spec, so hand-written API functions are replaced by generated ones (you can plug in your own fetch instance). - No spec required. The input is the TypeScript functions you already have, including projects whose OpenAPI or Swagger spec is missing or out of date.
- One key convention, automatically.
getUserinlibs/users/api.tsbecomes["users", "api", "getUser"], so developers stop inventing their own key names.@lukemorales/query-key-factoryneeds the key structure declared by hand; this tool also generates the option factories. - No repeated type declarations. Arguments, return values and
selectresults are inferred from the original function. - Generated code is ordinary TypeScript. Real
.tsfiles, not runtime API discovery, so they show up in code review and you can jump to definitions in your IDE. There is no extra cache or query engine. - API and query layer stay in sync.
watchregenerates on API changes, andgenerate --checkcatches stale generated files in CI. - Adapts to your project. Choose artifacts per function (
artifactsByName), or replace the analyzer (customAnalyzerPath) and template (customTemplatePath).
- An existing
fetchor axios API layer with auth and error handling - A backend without an OpenAPI spec, or with one that does not match reality
- Many API functions and several developers who need one query key convention
- Teams standardizing TanStack Query usage without rewriting existing code
generate: for each top-level function insourceDir, writes a key constant and query, infinite query and mutation option factories to*Options.ts.- The function-name prefix picks the artifacts:
get,list,fetchand similar get query and infinite query;create,update,deleteand similar get a mutation; other names get query and mutation.artifactsByNameandenabledArtifactsset them explicitly. - Infinite query options take their paging rules from
withOptions(initialPageParam,getNextPageParam); without them only the first page loads. - Mutations of functions with two or more arguments get a variables object type and
mapVariablesToArgs. withOptionsoverridesstaleTime,selectand others, with argument, return andselectresult types inferred.generate --checkwrites nothing and exits with code 1 when output is missing, changed or stale.watchregenerates when sources, the config or listed local plugins change.- An ownership header on the first line marks generated files; unmarked existing files are never overwritten.
- Choose artifacts with JSDoc, such as
/** @rqh mutation */next to the function. TodayartifactsByNamein the config does this. - Infinite queries on request, generated only for functions that paginate. Today
enabledArtifactsorartifactsByNameturn them off. - Keys that survive file moves, with a namespace independent of the file path so refactoring does not change cache keys.
- Wider analysis: re-export barrels, class and object methods, functions returned by higher-order functions.
- Beyond React: TanStack Query for Vue, Solid and Svelte.
- Optional OpenAPI input, generating new spec-based APIs and existing functions from one config.
npm install @uiwwsw/react-query-helper@^2 @tanstack/react-query react
npx @uiwwsw/react-query-helper initGenerated code imports this package, so install it as a regular dependency (do not use -D).
// rqh.config.ts
import type { AutoQueryConfig } from "@uiwwsw/react-query-helper/config";
export default {
sourceDir: "./libs",
outputDir: "./src/options",
template: { artifactStrategy: "smart" },
} satisfies AutoQueryConfig;// libs/users/api.ts
export const getUser = async (id: string) => ({ id, name: "Ada" });Running npx @uiwwsw/react-query-helper generate writes src/options/users/apiOptions.ts.
// Generated by @uiwwsw/react-query-helper. DO NOT EDIT.
// Source root: "../../libs"
import { getUser } from "../../../libs/users/api";
import {
queryOption as __rqh_query,
infiniteOption as __rqh_infinite,
} from "@uiwwsw/react-query-helper";
export const getUserKey = ["users", "api", "getUser"] as const;
export const getUserQueryOption = __rqh_query(getUserKey, getUser);
export const getUserInfiniteQueryOption = __rqh_infinite(getUserKey, getUser);Do not edit the generated file; change the source API instead. Usage:
// src/UserName.tsx
import { useQuery } from "@tanstack/react-query";
import { getUserQueryOption } from "./options/users/apiOptions";
export function UserName({ id }: { id: string }) {
const user = useQuery(
getUserQueryOption.withOptions(
{ staleTime: 60_000, select: (data) => data.name },
id,
),
);
if (user.isPending) return <p>Loading...</p>;
if (user.isError) return <p>{user.error.message}</p>;
return <p>{user.data}</p>;
}// With your existing QueryClient instance, client
await client.prefetchQuery(getUserQueryOption("u1"));
const cached = client.getQueryData(getUserQueryOption("u1").queryKey);
// { id: string; name: string } | undefinedAPI arguments become part of the cache key. Do not pass tokens or authorization headers as arguments.
- Configuration and usage reference: CLI, configuration, generation rules, runtime options, infinite queries, migrating from 1.x
- Sections moved from the README: full feature list, step-by-step install, recipe table, compatibility, dependencies, demo
- Architecture and dependencies: module layout, comparison with similar tools
- Repository review · Changelog · Demo
