Skip to main content

Usage in an NX monorepo

Read about some NX Basics here on oliverbutler.uk

Why?

NX is a smart build system to help you and your teams build, test, and deploy your projects in a modern monorepo. @ts-rest is the perfect pairing for NX, allowing you to build fully type-safe APIs with little effort.

Declaring an API Lib

Using ts-rest you declare a contract as a seperate lib, which is shared between applications.

This is because we want to enable NX to correctly mark projects as affected, thus enabling NX to only lint/test/build/deploy the affected projects.

Lib Structure

Affected Builds

In a situation where you've only updated the server, having the API as a lib will only rebuild the backend, not any of its consumers.

Without a seperate lib, NX will always rebuild the dependencies, in this case, the whole frontend - unecessarily.

Lib Structure

Optimising Even Further

You can further improve this model when you have many consumers per API. It's possible to split the API into multiple libs, allowing you to reduce the blast radius of any changes.

Lib Structure

Example Library

Below is an example lib is an example of a contract in a shared lib, shared between many libraries (in the ts-rest example repo)

Example Lib