Headline: The most reliable way I have found to keep a Next.js frontend in sync with a NestJS REST API is to treat the OpenAPI spec as the contract: the @nestjs/swagger CLI plugin generates the spec at build time, openapi-typescript turns it into TypeScript types, and openapi-fetch makes every call type-checked. A CI step that regenerates both files and runs git diff --exit-code turns an unannounced contract change into a failed build instead of a production bug.

For a long time my Next.js apps talked to NestJS backends through types I copied by hand, or at best through a shared types package in the monorepo. Both drifted. A renamed field compiled fine on the frontend and rendered undefined in production. These are my notes from replacing that with generated types, including the places where generated types still lie.

Key takeaways

  • OpenAPI is a language-neutral description of an HTTP API, and NestJS can emit it from the controllers and DTOs you already have, so the contract costs almost no extra code.
  • The @nestjs/swagger CLI plugin only runs inside nest build. A spec generated through tsx or esbuild silently loses DTO properties.
  • openapi-typescript generates types only, and openapi-fetch is a thin typed wrapper over fetch, so the runtime cost on the frontend is close to zero.
  • Generated types are only as honest as the spec. Response-wrapping interceptors, generic DTOs, and @Exclude()d fields are where the NestJS spec and the wire usually disagree.
  • The CI drift check is the part that prevents bugs: regenerate the spec and the types on every pull request, then fail on any uncommitted diff.

Why do shared TypeScript types between NestJS and Next.js drift?

Shared TypeScript types drift because they describe what the backend code intends, not what goes over the wire. A NestJS DTO with createdAt: Date arrives in the browser as an ISO 8601 string, because JSON has no date type. A global interceptor that wraps every response in { data } changes the shape without touching the DTO. And a shared types package only helps TypeScript clients in the same repository; a React Native app in another repo gets nothing.

An OpenAPI spec is a JSON or YAML document that lists every path, parameter, request body, and response schema of an HTTP API. Generating frontend types from the spec moves the source of truth one step closer to the wire, and it gives non-TypeScript clients the same contract.

How do I get an accurate OpenAPI spec out of NestJS?

An accurate NestJS spec starts with the @nestjs/swagger CLI plugin, a TypeScript compiler transformer that adds @ApiProperty() metadata to every property in files ending in .dto.ts or .entity.ts, and response metadata based on each controller method's return type. Without the plugin, every DTO property needs a hand-written @ApiProperty(), and the ones you forget do not exist in the spec.

// nest-cli.json { "compilerOptions": { "plugins": [{ "name": "@nestjs/swagger", "options": { "introspectComments": true } }] } } 

I export the spec from a small script that compiles with the rest of the app, instead of downloading it from a running server:

// src/export-openapi.ts — run with: nest build && node dist/export-openapi.js import { writeFileSync } from 'node:fs'; import { NestFactory } from '@nestjs/core'; import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger'; import { AppModule } from './app.module'; async function main() { const app = await NestFactory.create(AppModule, { logger: false }); const config = new DocumentBuilder() .setTitle('API') .setVersion('1.0') .addBearerAuth() .build(); const document = SwaggerModule.createDocument(app, config); writeFileSync('openapi.json', JSON.stringify(document, null, 2) + '\n'); await app.close(); } void main(); 

Three details mattered. First, the Swagger plugin is a TypeScript transformer, so it runs in nest build but not under tsx or esbuild, which strip types without running transformers; my first spec came out of tsx with empty DTO schemas. Second, NestFactory.create() instantiates providers, so an async provider that opens a database connection will try to connect; in CI I point the export step at the same throwaway Postgres the tests use. Third, I commit openapi.json, so a reviewer sees every contract change as a diff next to the code that caused it.

How do I generate types and a typed fetch client for Next.js?

openapi-typescript converts an OpenAPI 3.x document into one .d.ts file that exports a paths type, and openapi-fetch uses that type to check the URL, path parameters, query, body, and response of every call. Neither tool emits runtime code per endpoint, which is why I prefer them over generators that produce a client class per controller.

npx openapi-typescript ../api/openapi.json -o src/lib/api/schema.d.ts 

In the Next.js App Router I create the client per request. A module-level client with an auth middleware is shared by every request the server handles, and that is exactly how one user's token ends up on another user's call.

// src/lib/api/server.ts import 'server-only'; import { cookies } from 'next/headers'; import createClient from 'openapi-fetch'; import type { paths } from './schema'; export async function getApi() { const token = (await cookies()).get('session')?.value; return createClient<paths>({ baseUrl: process.env.API_URL, headers: token ? { Authorization: `Bearer ${token}` } : {}, }); } // app/orders/[id]/page.tsx const api = await getApi(); const { data, error } = await api.GET('/orders/{id}', { params: { path: { id } }, }); if (error) notFound(); return <OrderSummary order={data} />; 

A typo in '/orders/{id}', a missing path parameter, or a field the DTO no longer has is now a compile error. Once the controller declares its error responses, data and error narrow like a discriminated union. After I regenerate the types, renaming a field in a NestJS DTO breaks next build wherever the frontend reads it, which is the whole point.

Where do generated OpenAPI types still lie?

Generated types are only as honest as the spec, and the NestJS spec is built from decorators and class metadata, not from the bytes the API actually returns. These are the gaps I hit:

  • Response-wrapping interceptors. A global TransformInterceptor that returns { data, meta } changes every response, but the spec still describes the bare DTO. I either drop the wrapper or describe it in the spec with a wrapper class per response.
  • Generic DTOs. TypeScript generics disappear at runtime, so a Paginated<OrderDto> return type documents nothing useful. A class factory fixes it (below).
  • Serialized-away fields. ClassSerializerInterceptor strips properties marked @Exclude() from responses, but the plugin still documents them unless they also carry @ApiHideProperty(). The frontend type then promises a passwordHash that never arrives.
  • Undeclared error responses. The NestJS ValidationPipe throws a 400 whether or not the spec mentions it. Unless the controller declares @ApiBadRequestResponse({ type: ErrorDto }), openapi-fetch has no useful type for error.
  • Interfaces and type aliases. Interfaces have no runtime representation, so properties typed with them come out vague. I make every nested response shape a class.
// paginated.ts — deliberately not *.dto.ts, so the CLI plugin does not try to infer T import { Type } from '@nestjs/common'; import { ApiProperty } from '@nestjs/swagger'; export function Paginated<T>(item: Type<T>) { class PaginatedResult { @ApiProperty({ type: [item] }) items!: T[]; @ApiProperty({ type: String, nullable: true }) nextCursor!: string | null; } return PaginatedResult; } // orders.dto.ts export class OrderPageDto extends Paginated(OrderDto) {} 

None of this validates responses at runtime: openapi-fetch trusts the server. My NestJS e2e tests validate a handful of critical responses against the committed openapi.json, which is what caught the interceptor wrapper for me.

How do I stop the API contract drifting in CI?

A contract drift check regenerates the OpenAPI spec and the frontend types on every pull request and fails if either differs from what is committed. In a pnpm monorepo it is four steps:

# .github/workflows/contract.yml (steps excerpt) - run: pnpm --filter api build - run: node dist/export-openapi.js working-directory: apps/api - run: pnpm --filter web exec openapi-typescript ../api/openapi.json -o src/lib/api/schema.d.ts - run: git diff --exit-code -- apps/api/openapi.json apps/web/src/lib/api/schema.d.ts 

The diff check catches forgotten regeneration; it does not judge whether a change is safe. When an API has clients that do not deploy together with it, such as a mobile app already in the stores, I also run oasdiff breaking with --fail-on ERR against the spec from the main branch. oasdiff is an OpenAPI diff tool, and it fails the build when a change removes a response field or makes an optional request field required.

When should I use OpenAPI codegen instead of tRPC or ts-rest?

OpenAPI codegen is the right choice when the NestJS API already exists as REST controllers or serves clients that are not written in TypeScript. tRPC and ts-rest are better when you control both ends and want the contract written in TypeScript first.

Approach Source of truth Non-TypeScript clients Fits existing NestJS controllers Main catch
Shared types package Hand-written TS types No Yes Describes intent, not the wire (dates, interceptors)
tRPC TS router types Not without an extra adapter No, it replaces the controllers Couples client and server to TypeScript
ts-rest Contract object in TS, often with Zod Via its OpenAPI generator Partly, through @ts-rest/nest handlers Contract lives in a package both sides import
OpenAPI codegen (openapi-typescript + openapi-fetch) Spec generated from NestJS decorators Yes Yes Spec can disagree with runtime behavior

My backends already had REST controllers and Swagger UI, and some of them also serve a React Native app, so generating from OpenAPI meant no rewrite and one contract for every client.

FAQ

Q: Does openapi-fetch add much to my Next.js bundle?

A: Very little. openapi-fetch is a small wrapper around the native fetch, and the openapi-typescript output is a .d.ts file that compiles away completely.

Q: Should I commit the generated openapi.json and schema.d.ts?

A: Yes. Committing both files makes API contract changes visible in code review and gives the CI drift check something to compare against.

Q: Why do NestJS Date fields come out as string in the generated types?

A: JSON has no date type, so NestJS serializes a Date as an ISO 8601 string and the spec marks it type: string, format: date-time. openapi-typescript keeps it a string, which is correct; parse it where you need a date.

Q: Can a React Native app use the same generated client?

A: Yes. openapi-fetch only depends on the global fetch, which React Native provides, so a mobile app can import the same paths type from a shared package or a copy of schema.d.ts.

Q: Do I need Swagger UI enabled in production for this to work?

A: No. The spec is written by a build-time script, and the typed client only needs the committed openapi.json. Exposing Swagger UI with SwaggerModule.setup() is a separate, optional decision.

Originally published on devya.dev. Also on eng-ahmed.com. Built by Devya Solutions.