Angular and tRPC

Maximum type safety across the entire stack

Kevin Kreuzer
6 min readJan 24

--

On Twitter and Youtube, I heard many React developers talk about tRPC. I became curious and wanted to try it in Angular. Here's how to do it.

What is tRPC?

tRPC is a lightweight, high-performance RPC (Remote Procedure Call) framework designed to be simple, fast, and easy to use.

It allows you to make calls to a server from a client, as if the server was a local object, and enables you to build distributed systems using a variety of programming languages.

The main benefit of using tRPC is type safety without code generation.

Let's set up a fastify server with tRPC

To set up a tRPC server, we first have to initiate a fresh npm project and install the required packages.

tRPC can be combined with different node backend frameworks such as express or fastify. Throughout this blog post, we will be using fastify. Furthermore, we will use zod to verify incoming request data.

npm init
npm i @trpc/server fastify fastify-cors zod

Once we installed the packages. we can go ahead and generate a server.ts file.

Okay, if you have ever used fastify the code here looks very familiar. We spin up a fastify server on port 3000 and enable CORS. However, there are a few very interesting tRPC-specific lines here. Let's talk about them.

First, we import the fastifyTRPCPlugin from @trpc/server/adapters/fastify. We then use this plugin to register a tRPC router on our fastify server.

The router doesn't yet exist; let's go ahead and create one.

tRPC router

In a tRPC system, a router routes incoming requests to the appropriate server or service. The router acts as a central point of communication, forwarding client requests to the correct server and returning responses to the client.

A tRPC router typically does the following:

--

--

Kevin Kreuzer

Passionate freelance frontend engineer. ❤️ Always eager to learn, share and expand knowledge.