Generate a TypeScript Client from OpenAPI
On this page
Learning Objective
Make the OpenAPI document the source of truth between server and client, generate a typed TypeScript client from it, detect contract drift automatically in CI, and design the client so that base URLs, credentials and error handling stay consistent and safe.
Concept Explanation
The most expensive class of full-stack bug is the silent mismatch: the server renames a field, the React code still reads the old name, TypeScript is happy because someone typed the response by hand, and the interface shows blanks in production. Contract-first development removes that class by making the API description the single source of truth. The server produces or consumes an OpenAPI document, the client is generated from it, and any incompatible change surfaces as a compile error in the React project or a failing check in the pipeline, long before a user sees it.
There are two workable directions. In a design-first flow you write the OpenAPI document by hand, review it as a proposal with the frontend and backend developers together, and generate server stubs and client code from it. In a code-first flow, which fits a team that owns both sides and uses ASP.NET Core, you write the endpoints, let the framework generate the document, commit the generated file to the repository, and treat it as a reviewable artifact. Either way, the committed document is what a pull request diff shows: a change to the contract appears as a change to that file, visible to reviewers, so nobody breaks the API by accident.
On the .NET side, the Microsoft.Extensions.ApiDescription.Server package can generate the document at build time, so you do not need to run the server to get it. On the React side, openapi-typescript converts the document into TypeScript types for every path, parameter, request body, and response, and openapi-fetch supplies a tiny fetch wrapper that is fully typed against those types. Kiota, Microsoft's generator used for the Microsoft Graph SDKs, is a heavier alternative that emits a full client with models. The lightweight pair is a good default because it adds almost no runtime code and lets you keep using the fetch API you know.
Automation completes the loop. In the pipeline, regenerate the document from the server code and fail the build if it differs from the committed one, so nobody forgets to update the file. Regenerate the TypeScript types and fail if they differ from what is committed, and run the TypeScript compiler, so the React code is proven consistent with the contract. Also treat the client as a security boundary: it should use relative or environment-configured base URLs, never embed secrets, attach credentials in one central place, and handle ProblemDetails errors uniformly. Generated types describe what the server promises, but the server's data still arrives over the network, so critical inputs can be validated at runtime too, which Day 53 covers.
| Step | Tool | Output or check |
|---|---|---|
| Describe the API | Microsoft.AspNetCore.OpenApi | openapi/v1.json |
| Generate at build time | Microsoft.Extensions.ApiDescription.Server | Document written on build |
| Commit the contract | Git | Contract changes visible in code review |
| Generate TS types | openapi-typescript | src/api/schema.d.ts |
| Typed requests | openapi-fetch | createClient of paths |
| Detect drift | CI job running git diff --exit-code | Fails when the committed files are stale |
Worked Example: From the Server Build to a Typed React Call
The csproj settings write the document during build. The npm scripts generate types. The client wrapper centralizes the base URL and error handling, and a component shows fully typed usage. A CI step checks for drift.
<!-- Notes.Api.csproj: emit the OpenAPI document at build time -->
<PropertyGroup>
<OpenApiGenerateDocuments>true</OpenApiGenerateDocuments>
<OpenApiDocumentsDirectory>$(MSBuildProjectDirectory)/../../openapi</OpenApiDocumentsDirectory>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.ApiDescription.Server" Version="10.0.0" PrivateAssets="all" />
</ItemGroup>{
"scripts": {
"api:types": "openapi-typescript ../openapi/Notes.Api.json -o src/api/schema.d.ts",
"api:check": "npm run api:types && git diff --exit-code src/api/schema.d.ts"
},
"dependencies": { "openapi-fetch": "^0.13.0" },
"devDependencies": { "openapi-typescript": "^7.0.0", "typescript": "^5.6.0" }
}// src/api/client.ts: one place for base URL, credentials and error handling.
import createClient, { type Middleware } from 'openapi-fetch';
import type { paths } from './schema';
const errorMiddleware: Middleware = {
async onResponse({ response }) {
if (!response.ok) {
const problem = await response.clone().json().catch(() => ({}));
throw new ApiError(response.status, problem.title ?? 'Request failed', problem.errors, problem.traceId);
}
return response;
},
};
export const api = createClient<paths>({
baseUrl: import.meta.env.VITE_API_BASE_URL ?? '', // empty means same origin, via the dev proxy or BFF
credentials: 'include', // send the session cookie, no tokens in JS
});
api.use(errorMiddleware);
export class ApiError extends Error {
constructor(public status: number, message: string,
public fieldErrors?: Record<string, string[]>, public traceId?: string) { super(message); }
}// Fully typed usage: the path, parameters and response shape all come from the contract.
const { data } = await api.GET('/api/notes/{id}', { params: { path: { id: 42 } } });
console.log(data?.title); // typed as string
// api.GET('/api/notes/{id}', { params: { path: { id: 'x' } } }); // compile error: id must be a number
// data?.titel // compile error: typo caught# CI (GitHub Actions excerpt): fail if the contract or generated types are stale.
- run: dotnet build src/Notes.Api -c Release
- run: git diff --exit-code openapi/
- run: npm ci && npm run api:check && npx tsc --noEmit
working-directory: webIf a backend developer renames body to content in a DTO, the build rewrites openapi/Notes.Api.json, the diff check fails until that file is committed, and once it is, regenerated types make every React usage of body a compile error. The mismatch is discovered in seconds, not in production. Extend the project by adding the pagination and error responses from earlier lessons to the contract.
Real-World Examples
- Microsoft's Kiota is an OpenAPI-driven client generator that the company uses to produce SDKs for Microsoft Graph across several languages, including TypeScript, from the same API description. The approach lets a single contract feed many consumers consistently, and shows that generated clients are a production practice, not just a convenience for small projects.
- The openapi-typescript project is widely adopted in TypeScript codebases as a lightweight route from an OpenAPI description to types, with openapi-fetch and integrations for TanStack Query built on the same generated types. Teams use it precisely to make the compiler check every request and response against the server's published contract.
Review Questions & Answers
The silent mismatch where the server changes a field name, type, or route and the hand-written client types still claim the old shape, so the interface breaks at runtime. With generation, the client types come from the server's contract, so any incompatible change becomes a compile error or a failing CI check instead of a production defect.
Committing it turns the API contract into a reviewable artifact, so any pull request that changes the API shows exactly what changed in the file. It also lets CI compare regenerated output against the committed version to catch forgotten updates, and lets frontend developers work from a stable contract without running the backend.
An empty base URL means requests go to the same origin, through a dev proxy locally and a backend-for-frontend or reverse proxy in production, which avoids cross-origin complexity. Sending the session in an HttpOnly cookie means JavaScript never holds a token that an XSS attack could steal. Both choices are developed fully in Phase 5.
Types are erased when the code is compiled, so nothing checks the actual JSON arriving at runtime. A misbehaving server, a proxy error page, or an old cached response could return an unexpected shape. Runtime validation of critical data with a schema library turns those cases into handled errors, at the cost of a little extra code.