Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ See the [documentation](https://orqc.7nohe.dev) for [CLI options](https://orqc.7

| | This library | @hey-api tanstack-query plugin | Orval | openapi-react-query |
|---|---|---|---|---|
| `queryOptions` / `infiniteQueryOptions` factories (TanStack v5 pattern) | ✅ | ✅ | ❌ | ✅ (`$api.queryOptions`) |
| `queryOptions` / `infiniteQueryOptions` factories (TanStack v5 pattern) | ✅ | ✅ | ✅ (`getXxxQueryOptions`) | ✅ (`$api.queryOptions`) |
| Ready-to-use hooks (`useQuery` / suspense / infinite variants) | ✅ generated per operation | ❌ (options only) | ✅ | ✅ runtime wrapper (method + path strings) |
| SSR helpers (`prefetchQuery` / `prefetchInfiniteQuery` / `ensureQueryData`) | ✅ | ❌ | Partial (`usePrefetch`) | Not provided (use `queryOptions`) |
| Hierarchical query keys for granular invalidation | ✅ | ✅ (tags) | Partial | Not documented |
Expand All @@ -93,7 +93,7 @@ See the [documentation](https://orqc.7nohe.dev) for [CLI options](https://orqc.7
| Packages added by installing the generator¹ | **9** (2.1 MB) | 51 (10.8 MB) | 89 (101.5 MB) | 35 (20.5 MB) |
| Type errors in the generated code, Stripe / GitHub APIs¹ | **0 / 0** | 274 / 0 | 219 / 1 | 0 / 0 |

¹ Measured on 2026-11-13 on an Apple M2 with Node.js 24 (generation time is the median wall-clock time of the CLI), with 4.0.0-beta.4, `@hey-api/openapi-ts` 0.99.0, Orval 8.46.0 and openapi-typescript 7.13.0 + openapi-react-query 0.5.4. Methods, the other specifications and type-checking times are on the [Benchmarks](https://orqc.7nohe.dev/guides/benchmarks/) page; the scripts are in [`benchmarks/`](./benchmarks).
¹ Measured on 2026-11-13 on an Apple M2 with Node.js 24 (generation time is the median wall-clock time of the CLI), with 4.0.0-beta.4, `@hey-api/openapi-ts` 0.99.0, Orval 8.46.0 and openapi-typescript 7.13.0 + openapi-react-query 0.5.4. Methods, the other specifications and type-checking times are on the [Benchmarks](https://orqc.7nohe.dev/guides/benchmarks/) page; the scripts are in [`benchmarks/`](./benchmarks). The [Comparison](https://orqc.7nohe.dev/guides/comparison/) page covers Kubb too, and what each tool generates in more detail.

**Scope**: this library is deliberately React-focused — use the hey-api plugin if you need non-React frameworks. Its [MSW mocks](https://orqc.7nohe.dev/guides/mocking/) answer with fixed values taken from the spec and keep no state; use Orval if you want randomly generated mock data.

Expand Down
13 changes: 9 additions & 4 deletions docs/astro.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -61,13 +61,14 @@ export default defineConfig({
{
label: "Getting started and usage",
description:
"install, first run, the generated layout, using the generated hooks and queryOptions factories, every CLI option, mock data and MSW handlers, CI checks and coding agents",
"install, first run, the generated layout, using the generated hooks and queryOptions factories, every CLI option, mock data and MSW handlers, CI checks, coding agents and the FAQ",
paths: [
"guides/introduction",
"guides/usage",
"guides/cli-options",
"guides/mocking",
"guides/ci-and-agents",
"guides/faq",
],
},
{
Expand All @@ -83,10 +84,10 @@ export default defineConfig({
paths: ["guides/migrating-*"],
},
{
label: "Benchmarks",
label: "Comparison and benchmarks",
description:
"generation time, install size and type errors compared with other generators, and what a coding agent spends",
paths: ["guides/benchmarks"],
"what Orval, Kubb, Hey API and openapi-react-query generate compared with this library, with generation time, install size and type errors, and what a coding agent spends",
paths: ["guides/comparison", "guides/benchmarks"],
},
],
promote: [
Expand All @@ -96,6 +97,8 @@ export default defineConfig({
"guides/cli-options",
"guides/mocking",
"guides/ci-and-agents",
"guides/faq",
"guides/comparison",
],
demote: ["guides/migrating-to-v3", "contributing", "license"],
exclude: ["guides/migrating-to-v3", "contributing", "license"],
Expand Down Expand Up @@ -137,7 +140,9 @@ export default defineConfig({
{ slug: "guides/cli-options" },
{ slug: "guides/mocking" },
{ slug: "guides/ci-and-agents" },
{ slug: "guides/comparison" },
{ slug: "guides/benchmarks" },
{ slug: "guides/faq" },
{ slug: "guides/migrating-to-v3" },
{ slug: "guides/migrating-to-v4" },
{ slug: "guides/migrating-from-openapi-react-query" },
Expand Down
192 changes: 191 additions & 1 deletion docs/src/content/docs/examples/nextjs.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,194 @@ title: Next.js Example
description: A Next.js App Router example that prefetches on the server and hydrates TanStack Query hooks generated from an OpenAPI document.
---

Example of using Next.js can be found in the [`examples/nextjs-app`](https://github.com/7nohe/openapi-react-query-codegen/tree/main/examples/nextjs-app) directory of the repository.
Example of using Next.js can be found in the [`examples/nextjs-app`](https://github.com/7nohe/openapi-react-query-codegen/tree/main/examples/nextjs-app) directory of the repository. It uses the App Router: a Server Component prefetches a query, and a Client Component reads the same data through the generated hook without fetching it again.

## Generate the code

```json
{ "scripts": { "codegen": "orqc -i ./petstore.yaml" } }
```

The command writes the client to `openapi/requests/` and the TanStack Query code to `openapi/queries/`. The default client uses `fetch`, which is what the server needs too.

## Configure the client and the provider

Set the base URL in one module:

```ts
// fetchClient.ts
import { client } from "@/openapi/requests/client.gen";

client.setConfig({
baseUrl: "http://localhost:4010",
});
```

Next.js bundles Server Components and Client Components separately, so each side has its own copy of the generated client. Import this module on both: in the provider below for the browser, and in every Server Component that prefetches. A Server Component that leaves it out sends its request to the server URL written in the specification.

The `QueryClientProvider` needs a Client Component. Create one `QueryClient` per request on the server and keep a single one in the browser:

```tsx
// app/providers.tsx
"use client";

import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import "../fetchClient";
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

function makeQueryClient() {
return new QueryClient({
defaultOptions: {
queries: {
// Above 0, so the browser does not refetch what the server just sent.
staleTime: 60 * 1000,
},
},
});
}

let browserQueryClient: QueryClient | undefined;

function getQueryClient() {
if (typeof window === "undefined") return makeQueryClient();
if (!browserQueryClient) browserQueryClient = makeQueryClient();
return browserQueryClient;
}

export default function Providers({ children }: { children: React.ReactNode }) {
return (
<QueryClientProvider client={getQueryClient()}>
{children}
</QueryClientProvider>
);
}
```

Wrap the application with it in `app/layout.tsx`.

## Prefetch in a Server Component

Every GET operation has a prefetch function in `openapi/queries/prefetch`. Call it in a Server Component, then pass the cache to the browser with `HydrationBoundary`:

```tsx
// app/page.tsx
import {
dehydrate,
HydrationBoundary,
QueryClient,
} from "@tanstack/react-query";
import "../fetchClient";
import { prefetchUseFindPets } from "../openapi/queries/prefetch";
import Pets from "./components/Pets";

export default async function Home() {
const queryClient = new QueryClient();

await prefetchUseFindPets(queryClient, {
query: { tags: [], limit: 10 },
});

return (
<HydrationBoundary state={dehydrate(queryClient)}>
<Pets />
</HydrationBoundary>
);
}
```

## Read the data in a Client Component

```tsx
// app/components/Pets.tsx
"use client";

import { useFindPets } from "@/openapi/queries";

export default function Pets() {
const { data } = useFindPets({
query: { tags: [], limit: 10 },
});

return (
<ul>
{data?.map((pet) => (
<li key={pet.id}>{pet.name}</li>
))}
</ul>
);
}
```

Pass the hook the same options as the prefetch function, and no query key of your own as its second argument. The query key is the operation's key followed by the options, and a key of your own takes the place of the options. Either difference is a different cache entry, and the browser fetches again.

## Infinite queries

A paginated operation also gets a prefetch function for its first page. The Client Component continues from there with `fetchNextPage`:

```tsx
// app/infinite-loader/page.tsx
import {
dehydrate,
HydrationBoundary,
QueryClient,
} from "@tanstack/react-query";
import "../../fetchClient";
import { prefetchUseFindPaginatedPetsInfinite } from "../../openapi/queries/prefetch";
import PaginatedPets from "../components/PaginatedPets";

export default async function InfiniteLoaderPage() {
const queryClient = new QueryClient();

await prefetchUseFindPaginatedPetsInfinite(queryClient, {
query: { limit: 10, tags: [] },
});

return (
<HydrationBoundary state={dehydrate(queryClient)}>
<PaginatedPets />
</HydrationBoundary>
);
}
```

```tsx
// app/components/PaginatedPets.tsx
"use client";

import { useFindPaginatedPetsInfinite } from "@/openapi/queries/infiniteQueries";

export default function PaginatedPets() {
const { data, fetchNextPage } = useFindPaginatedPetsInfinite({
query: { limit: 10, tags: [] },
});

return (
<>
<ul>
{data?.pages.flatMap((page) =>
page?.pets?.map((pet) => <li key={pet.id}>{pet.name}</li>),
)}
</ul>
{data?.pages.at(-1)?.nextPage && (
<button type="button" onClick={() => fetchNextPage()}>
Load more
</button>
)}
</>
);
}
```

An operation is paginated when it has the query parameter named by [`--pageParam`](/guides/cli-options/#--pageparam-value). See [Usage](/guides/usage/#using-the-generated-useinfinitequery-hooks) for the details.

## Run the example

From the root of the repository:

```bash
pnpm install
pnpm build
pnpm --filter nextjs-app generate:api
pnpm --filter nextjs-app dev
```

`dev` starts Next.js and a small mock Petstore server on `http://localhost:4010`.
Loading
Loading