---
name: integrate-backend-client
description: >
  Use the generated backend-mode TypeScript client in server-side code
  (Node >= 18, Bun, Deno): BFFs, services, and SDK packages that wrap an
  API. Covers the single peer dependency (zod), instantiation with
  new Client(baseUrl?, { fetch?, headers? }), per-request headers such as
  refreshing bearer tokens, calling async operation methods with an
  optional { signal, headers } second argument, per-status typed
  ApiResponse<T, S> results that never throw on an HTTP status, fetch
  injection for tests, and file uploads. Load when importing or using a
  generated backend-mode client file.
type: framework
library: openapi-client-generator
library_version: "3.0.0"
requires:
  - generate-client
sources:
  - "bazo/openapi-client-generator:src/modes/backend/index.ts"
  - "bazo/openapi-client-generator:src/modes/backend/operation.ts"
---

This skill builds on generate-client. Read it first for CLI usage.

# Integrate Backend Client

`backend` is the TypeScript client for code that runs on a server. It has no TanStack Query, no
React and no wretch: `zod` is its only runtime dependency and HTTP goes through the platform
`fetch`. Choose it for server-side code; choose `full` for React / React Native apps and
`playwright` for Playwright E2E tests.

## Setup

```bash
npx openapi-client openapi.json src/api/ -n ApiClient -m backend
npm install zod
```

The generated validators are Zod 4 (`z.email()`, `z.iso.datetime()`, `z.int()`), so `zod` must be >= 4.

```typescript
import { ApiClient } from "./api/ApiClient";

const api = new ApiClient("https://api.example.com", {
  headers: { "X-Api-Key": process.env.API_KEY! },
});

const res = await api.getTask({ taskId: "42" });
if (res.status === 200 && res.data) {
  console.log(res.data.title);
}
```

### Constructor

`new ApiClient(baseUrl, options?)`

- `baseUrl` — the API root; a trailing `/` is ignored. When the spec declares `servers`, it
  defaults to the first one (`ApiClient.defaultBaseUrl`, name in `ApiClient.defaultServerName`,
  all of them on `ApiClient.servers`), so `new ApiClient()` works and options can be passed with
  `new ApiClient(undefined, { ... })`. Without `servers` it is required.
- `options: ApiClientOptions` (the interface is named `<ClientName>Options`):
  - `fetch?: (input: string, init: RequestInit) => Promise<Response>` — the fetch to use. Defaults
    to the global `fetch`, looked up on every request (so a stub installed later is honoured).
  - `headers?: HeadersInit | (() => HeadersInit | Promise<HeadersInit>)` — sent on every request.
    A function is called per request.

## Core Patterns

### Operations

Every operation is `async <operationId>(params, requestInit?)`:

- `params` holds path, query and header params (by their generated safe names) plus `body`. It is
  validated with Zod before the request is sent. When nothing in it is required it defaults to
  `{}`, so `api.listTasks()` works; an operation with no params still takes the slot, so
  `requestInit` is always the second argument (`api.healthCheck({}, { signal })`).
- `requestInit?: RequestOptions` — `{ signal?: AbortSignal; headers?: HeadersInit }` for this call.

Path params are percent-encoded for you (pass raw values). Query arrays repeat the key
(`tag=a&tag=b`), or go out once comma-joined when declared `explode: false` (an empty one is left
out); object query values are sent as JSON; `undefined`/`null` params are not sent.

### Responses never throw on a status

```typescript
const res = await api.getTask({ taskId });
switch (res.status) {
  case 200:
    return res.data; // the 200 schema's type (or null — see below)
  case 404:
    throw new NotFound(res.data?.message);
  default:
    throw new Error(`Unexpected ${res.status} from ${res.url}`);
}
```

The result is `ApiResponse<T, S>` — `{ data, status, headers: Headers, url }`, with a literal
`status` for every exactly documented status.

**Every documented body is validated strictly; a mismatch throws `ResponseValidationError` carrying the status.** That holds for successes and errors alike — an exact status (200, 401, 404, 500…), a `4XX`-style range or `default`. A body that does not match its schema (the wrong shape, a key a strict schema does not declare, a proxy's HTML page on a documented status) is a contract violation: the call rejects with a `ResponseValidationError` that has `status`, `headers`, `url`, the raw `body`, and the ZodError (or, for a non-JSON body, the JSON SyntaxError) as `cause`; its message reads `Response to GET /tasks/{taskId} (500) does not match the contract`. A status is matched exact → range → `default` (Go mode's precedence); a status none of them documents resolves `data: null` — there is nothing to validate it against.

```typescript
import { ResponseValidationError } from "./api/ApiClient";

try {
  const res = await api.getTask({ taskId });
  if (res.status === 404) return null; // a documented 404 whose body matched its schema
} catch (error) {
  if (error instanceof ResponseValidationError) {
    log.error(`contract violation: HTTP ${error.status} from ${error.url}`, { body: error.body, cause: error.cause });
  }
  throw error;
}
```

So an error status never throws by itself — a documented one whose body matches comes back as
`{ status, data }` — and the method rejects only on a network error / abort, invalid `params`
(Zod, before the request), or a documented body that breaks its schema.

The return type is the union of one `ApiResponse<T, S>` per exact documented status (success or
error, `data` exactly its schema), plus a catch-all member for the rest:
`ApiResponse<Envelope, number>` per documented range / `default`, and `ApiResponse<null, number>`
while some status is left that nothing documents (i.e. no `default`). Because the catch-all's
`status` is `number`, `res.status === 200` alone can leave `T | null` — check `res.data` too
(`if (res.status === 200 && res.data)`). (TypeScript folds a member whose data is structurally a
subtype of the catch-all's into it — harmless, since the data type is the same shape.)

### Refreshing bearer tokens

```typescript
const api = new ApiClient(baseUrl, {
  headers: async () => ({ Authorization: `Bearer ${await tokenCache.get()}` }),
});
```

Headers are layered, each layer winning over the one before: `options.headers` → the body's
content type → the operation's header params → `requestInit.headers`. A multipart or urlencoded
body always gets the content type `fetch` writes for it (multipart boundary included), even when
a default `Content-Type` is configured.

### Timeouts and cancellation

```typescript
await api.getTask({ taskId }, { signal: AbortSignal.timeout(5_000) });
```

### Testing with an injected fetch

```typescript
const calls: string[] = [];
const api = new ApiClient("http://api.test", {
  fetch: async (input, init) => {
    calls.push(`${init.method} ${input}`);
    return Response.json({ id: "42", title: "Stub" });
  },
});
```

The same option wires a custom agent/dispatcher or instrumentation:
`fetch: (input, init) => fetch(input, { ...init, dispatcher })` (undici).

### Publishing an SDK package

The generated file is self-contained (`import { z } from "zod"` is its only import), so an SDK
package re-exports it and lists `zod` as a dependency or peer dependency:

```typescript
// packages/my-api-client/src/index.ts
export * from "./generated/ApiClient";
```

## File uploads

A `format: binary` field of a multipart body takes `BinaryInput` (`Blob | File`, global in Node
18+, Bun and Deno); the client builds the `FormData`. Field encoding matches every other mode:
scalars are one part, scalar arrays repeat the part, objects and arrays of objects are one JSON
text part, `undefined`/`null` are omitted. A `oneOf`/`anyOf` body sends the fields of the branch
you pass (read from your own value, not the Zod-parsed copy). Urlencoded bodies take a plain object
(arrays become repeated keys). A raw binary body (`application/octet-stream`, `image/*`) takes one
`BinaryInput` sent as-is under its declared content type; a `text/*` string body is sent verbatim.

```typescript
import { readFile } from "node:fs/promises";

const bytes = await readFile("./invoice.pdf");
await api.uploadTaskAttachment({
  taskId: "42",
  body: { file: new File([bytes], "invoice.pdf", { type: "application/pdf" }), description: "Q3" },
});
```

## Common Mistakes

### CRITICAL Using full mode on a server

Wrong:

```bash
npx openapi-client openapi.json src/api/ -n ApiClient -m full
# server code now needs @tanstack/react-query and a QueryClient just to call an endpoint
```

Correct:

```bash
npx openapi-client openapi.json src/api/ -n ApiClient -m backend
```

### HIGH Expecting a throw on 4xx/5xx

Wrong:

```typescript
try {
  const task = (await api.getTask({ taskId })).data;
} catch {
  // never reached for a 404
}
```

Correct: branch on `res.status` (see above). Only network errors, aborts, invalid params and a documented body that breaks its schema (`ResponseValidationError`) reject.

### HIGH Reading `data` after only a status check

Wrong:

```typescript
if (res.status === 200) console.log(res.data.title); // TS: 'res.data' is possibly 'null' (no `default` documented)
```

Correct:

```typescript
if (res.status === 200 && res.data) console.log(res.data.title);
```

### MEDIUM Passing options as the first argument

Wrong:

```typescript
new ApiClient({ headers }); // the first argument is the base URL
```

Correct:

```typescript
new ApiClient(undefined, { headers }); // default server from the spec
new ApiClient("https://api.example.com", { headers });
```

### HIGH Editing the generated file directly

The file is regenerated from the spec. Wrap or extend the class in a separate file instead.

See also: generate-client/SKILL.md — CLI usage for regenerating the client
See also: integrate-full-client/SKILL.md — the React / React Native client
