Frameworks & Languages

NestJS and TypeScript End to End: Sharing Types Between API and Front End

A NestJS API and a TypeScript front end should not define the same shapes twice. We compare shared packages, OpenAPI-generated clients, Zod schemas and GraphQL codegen, and cover the details that cause contract bugs.

Close-up of a car instrument cluster with rev counter, speedometer and fuel and temperature gauges

When a NestJS API and a React, Next.js or Angular front end are both written in TypeScript, it seems obvious that they should share types. In practice many teams still define the same shapes twice: a DTO on the server and a hand-written interface in the front end. The two drift apart, a field is renamed on one side, and the bug only shows up when a user sees an empty column or a form that silently fails.

Keeping the contract in one place is a standard part of our NestJS development work. There are several ways to do it, and each makes different trade-offs. This article compares them and covers the details that trip teams up.

Types Are Not Validation

One point first, because it shapes every option below. TypeScript types disappear at compile time. A shared interface tells the front-end developer what the API promises, but it does nothing to stop a malformed request reaching the server. The API still needs runtime validation at its boundary, which in NestJS usually means a global ValidationPipe with whitelist enabled so unknown properties are stripped, plus explicit transformation of strings into numbers and dates.

So the real goal is a single source of truth that produces both compile-time types for the client and runtime validation on the server.

Four Ways to Share the Contract

Option 1: A Shared Package in a Monorepo

The API and front end live in one repository managed with pnpm workspaces, Nx or Turborepo, and a shared contracts package exports the request and response types both sides import.

  • Works well when one team owns both sides and they deploy together.
  • The trap: NestJS DTOs are usually classes decorated with class-validator and Swagger decorators. Importing those into the front end drags server libraries into the browser bundle. Keep the shared package free of framework code: plain interfaces or schemas only, with the decorated DTO classes in the API implementing them.
  • Never share entities. TypeORM or Prisma models describe your database, not your API. Exposing them couples the front end to your schema and risks leaking fields such as password hashes or internal flags.

Option 2: Generate a Client From OpenAPI

NestJS can describe its own API. With @nestjs/swagger and its CLI plugin, controllers and DTOs produce an OpenAPI document with little extra annotation. From that document, tools such as openapi-typescript, Orval or OpenAPI Generator create typed client functions or hooks for the front end.

  • Works well when the API has more than one consumer: a web app, a mobile app, partners or other services. The same document can generate a Dart client for a Flutter app or a Kotlin or Swift client for native apps.
  • It decouples deployment. The front end consumes a published contract rather than the API's source code, so the repositories can live separately.
  • The trap: the generated types are only as accurate as the annotations. Responses that are not declared, union types and inherited DTOs need care, or the document quietly describes something other than what the API returns.

This is our default for APIs with several consumers, and it fits naturally with our API development and integration practice of treating the contract as a published, versioned artefact.

Option 3: Schemas as the Single Source

Instead of starting from classes or interfaces, define each request and response once as a Zod schema in a shared package. The API validates with it, through a small custom pipe or a library such as nestjs-zod, and the front end infers TypeScript types from the same schema with z.infer. The front end can also reuse the schema to validate forms before submission, so the same rules apply on both sides.

  • Works well when validation rules are rich and you want client-side form checks to match the server exactly.
  • The trap: it moves away from the class-validator approach most NestJS documentation assumes, so the team needs to agree on it and stay consistent. OpenAPI generation is still possible, but needs an extra step.

Option 4: GraphQL With Code Generation

If the API is GraphQL, NestJS's code-first approach generates the schema from TypeScript classes, and GraphQL Code Generator produces typed queries and hooks for the client. Types then come from the queries the front end actually writes, which is precise. It is a good fit when the front end needs flexible queries across related data, but it is a bigger architectural decision than type sharing alone should drive.

Details That Cause Bugs

  • Dates are strings on the wire. A Date in a server type becomes an ISO string in JSON. Shared types that claim Date are wrong on the client; define the wire format as a string and parse it deliberately.
  • Large numbers and decimals. Money and 64-bit IDs lose precision as JavaScript numbers. Send them as strings and convert explicitly.
  • Optional versus nullable. A missing field and a null field are different, and databases, ORMs and serialisers do not always agree. Decide on one convention per field.
  • Enums. String unions or string enums survive serialisation predictably; numeric enums produce confusing values in logs and clients.

Keeping the Contract Honest Over Time

  1. Generate in CI. Regenerate the OpenAPI document or client on every build and fail if the committed version differs, so nobody forgets to update it.
  2. Detect breaking changes. Compare the new OpenAPI document with the last released one using a diff tool such as oasdiff, and flag removed fields or changed types before they ship.
  3. Version deliberately. Additive changes are safe; removals and renames need a new version or a deprecation period, especially when mobile apps cannot be force-updated.
  4. Test the boundary. End-to-end tests that call the API through the generated client catch mismatches that unit tests on either side miss.

If you are still choosing a back-end structure, we compare the options in NestJS vs Express, and the contract design ideas in designing an API for vehicle telematics data apply to most APIs with several consumers.

Which Approach We Recommend

For a single web front end built by the same team, a monorepo with a framework-free contracts package or shared Zod schemas is simplest. For APIs consumed by web and mobile apps or third parties, generate clients from OpenAPI. Either way, the front end, whether React, Next.js or Angular, stops guessing what the API returns. If your API and front end have drifted apart, talk to us about putting a single contract between them.

Frequently Asked Questions

Can we share our NestJS DTO classes directly with the React app?

You can, but it usually causes problems. DTO classes carry class-validator and Swagger decorators, which pull server libraries into the browser bundle and couple the front end to the API's internals. Sharing plain interfaces or schemas that the DTOs implement gives the same type safety without the baggage.

Do generated API clients work for mobile apps as well?

Yes, which is one of the main reasons to use OpenAPI. The same document that produces a TypeScript client for the web can generate a Dart client for Flutter or Kotlin and Swift clients for native apps, so every consumer works from the same contract rather than hand-written models.

Do we still need validation on the API if the front end is fully typed?

Always. TypeScript types are removed at compile time and offer no protection at runtime. Requests can come from old app versions, scripts, partners or attackers, so the API must validate and sanitise every input regardless of how carefully the front end is written.

How do we stop API changes breaking older versions of our mobile app?

Treat the API contract as published. Make additive changes where possible, compare each new OpenAPI document with the last release to catch breaking changes in CI, and introduce a new version or a deprecation period for removals and renames. Logging which app versions call each endpoint shows when an old version can safely be retired.

Is it worth adding type sharing to an existing NestJS project?

Usually yes, and it can be done gradually. Adding the Swagger CLI plugin and generating a client for a few endpoints at a time lets the front end migrate screen by screen. Most teams find mismatched fields during the first pass, which is useful in itself.

How We Can Help

Services Related to This Article

The work we do with the technologies discussed above — with pricing, process and real examples on each page.

  • NestJS Development

    Structured, testable Node.js backends with NestJS: REST and GraphQL APIs, microservices, queues and real-time services built to be maintained.

  • API Development & Integration

    Custom REST and GraphQL API development plus integrations with CRMs, ERPs, payment gateways, shipping carriers and marketing platforms.

  • React Development

    Custom React.js front ends, dashboards and single-page applications built with TypeScript, reusable components and server-side rendering for SEO.

  • Next.js Development

    Next.js websites and web apps with server-side rendering, static generation, image optimisation and route-level code splitting for top Core Web Vitals.

In Practice

Case Studies on This Topic

Projects where we put these ideas to work, each with a live demo.

  • Kestrel Wealth demo — home page
    • Next.js
    • React
    • TypeScript

    Headless CMS Website

    Wealth Management Insights Hub

    A Next.js front end over headless WordPress that took a compliance-heavy content library from slow to near-instant.

  • Watch Clock — Meridian & Co.
    • Shopify Storefront API
    • Next.js
    • React

    Headless Shopify eCommerce

    Pre-Owned Luxury Watch Storefront

    A headless Shopify storefront for one-of-one inventory, with authentication records and a sell-your-watch flow.

  • House Home — Harborne Estates
    • Next.js
    • React
    • Headless CMS

    Headless CMS Website

    Estate Agency Property Listings

    A headless CMS and Next.js site rendering 1,240 live listings that sync from the agency system every few minutes.

Keep Reading

  • Close-up of a metal bicycle chain running over worn, oily sprockets

    Rust for Web Services: Where Its Safety and Speed Pay Off

    Rust is the wrong tool for most business web applications, but for parsing untrusted input, CPU-heavy hot paths and strict latency targets its safety and speed pay for themselves. Here is where it fits, what the stack looks like and what it costs.

  • Drupal module code in an editor beside a panel outlining a Drupal stack of content model, editorial workflow, Twig theme and PHP platform

    Life After Drupal 7: Upgrade to Modern Drupal or Move Platforms?

    Drupal 7 reached end of life in January 2025, and moving on means a rebuild whichever platform you choose. Here is what the risk looks like now, what moving to Drupal 11 involves, and when WordPress, a headless CMS or Backdrop fits better.

  • Empty open-plan office with exposed red brick walls, tall windows and a long glossy work table

    Hotwire and Turbo in Rails: Interactive Pages Without a JavaScript Framework

    Hotwire lets a Rails application deliver fast, interactive pages with server-rendered HTML instead of a separate single-page app. Here is what Turbo and Stimulus do, where they fit, where they do not, and the pitfalls to avoid.

Let’s Connect

Let’s Build Something Amazing Together

Share your project details and our experts will get back to you within one business day with the best solution — free consultation, no obligation.