Typed TypeScript clients
Generate a typed TypeScript client and TanStack Query hooks from the OpenAPI document, and keep the frontend in step with the server.
Your frontend calls the API through functions generated from the
OpenAPI document, so a renamed field or a new required parameter
is a TypeScript error before it is a bug. The document is composed from the
route table, which makes the generated client as current as the server it
describes. You need OpenApiModule wired in and a frontend with Node; this
recipe uses Hey API and its
TanStack Query plugin.
-
Commit the document. Every development run writes it once at boot — the profile opens
<PREFIX>_OPENAPI__EMIT— toopenapi.jsonbeside the app’sCargo.toml, or to<PREFIX>_OPENAPI__EMIT_PATH, which a relative path resolves against the same directory. The boot logs the file it wrote:INFO nest_rs::openapi: wrote OpenAPI document path=/home/dev/publish/apps/api/openapi.json bytes=76335A pull request now shows every change to the API contract as a diff of that file.
-
Generate the client. Hey API is pre-1.0 and asks to be pinned exactly:
Terminal window $ npm install -D -E @hey-api/openapi-ts@0.99.0$ npm install @tanstack/react-query$ npx openapi-ts -i ../apps/api/openapi.json -o src/api \-p @hey-api/client-fetch -p @hey-api/typescript -p @hey-api/sdk -p @tanstack/react-query[Job 1] ✓ src/api · 5 filesEach operation becomes a function named after its
operationId(posts_list→postsList) and a set of query helpers (postsListOptions), each schema a type. -
Call it. Errors are typed too: every error status the framework answers is an RFC 9457 problem document, so
erroris aProblemDetails:web/src/posts.ts import { useQuery } from '@tanstack/react-query';import { client } from './api/client.gen';import { postsCreate, postsList } from './api/sdk.gen';import { postsListOptions } from './api/@tanstack/react-query.gen';import type { Post } from './api/types.gen';client.setConfig({ baseUrl: 'https://api.example.com', auth: () => currentToken() });const nextCursor = (link: string | null | undefined): string | null => {const target = link?.match(/<([^>]+)>;\s*rel="next"/)?.[1];return target ? new URL(target, 'https://api.example.com').searchParams.get('after') : null;};export async function page(after?: string): Promise<{ posts: Post[]; next: string | null }> {const { data, error, response } = await postsList({ query: { first: 20, after } });if (error) throw new Error(`${error.status} ${error.title}`);return { posts: data, next: nextCursor(response?.headers.get('link')) };}export async function draft(title: string, body: string): Promise<Post> {const { data, error } = await postsCreate({ body: { title, body } });if (error) throw new Error(error.detail ?? error.title);return data;}export const usePosts = () => useQuery(postsListOptions({ query: { first: 20 } }));authis called only for the operations the document markssecurity— the routes a guard can answer401on — never for a#[public]one. The next page is the RFC 8288Linka list answers with,rel="next", absent on the last page. -
Allow the frontend’s origin. A browser app on another origin needs CORS:
<PREFIX>_HTTP__CORS_ORIGINS=https://app.example.com. The headers the framework sends —Link,Location,Retry-After— are exposed to it without being listed (HTTP configuration).
What fails if you get it wrong
Section titled “What fails if you get it wrong”A response typed unknown. The document reads a handler’s payload off
its return type — Json<T>, a Created or Paginated of one, a Result of
either, an alias included. A handler building its own Response states none:
declare it with #[api(response = T)] (OpenAPI operations).
Two operations under one name. An operationId is
<controller>_<handler> and must be unique; when two operations map to one,
the boot logs two operations share one operationId with both addresses.
Rename one handler — and since generated names follow the id, renaming a
handler is a breaking change for the frontend that calls it.
The next page reads null in the browser. The request reached the server
from another origin without CORS: no <PREFIX>_HTTP__CORS_ORIGINS names it,
so the browser hides every response header the safelist does not cover.
Going further
Section titled “Going further”- OpenAPI — what the document derives, and what it leaves to you.
- Pagination — the cursor the
Linkcarries. - Security — the guards that decide which operations carry
security.