How should I share API definitions between the server and the client, both in TypeScript?

Viewed 213

I've got a server (TypeScript, NestJS) and a client (TypeScript, Angular) and they talk to each other.

Currently I have the API repsonse DTO classes defined in the server to output, and again in the client to decode the responses into a class. This smells.

What's a good way to share the API response DTOs between the two projects (or, if this isn't a good idea, why)?

Ideally, I'd like to be able to change the API response format for the server, and then have the client not build because things have changed. It's still in very early beta at the moment, and I control deployment of both client and server so a fair amount of these changes are breaking.

They're currently in two git repositories, but if needed that can change.

1 Answers

You have several options to achieve this - but they need you to think about the structure of the project (and need some work).

  1. Using the monorepo approach, by utilizing tools such as NX (here's a getting started), you can have your types/models in one place and share them between your frontend and backend. There's also other tools such as Turborepo
  2. Another way would be to make a shared repository of types and share them between both your backend and frontend using git submodules.
Related