Using TRPC with Cloudflare Workers in a monorepo
In this article we will learn about how we can integrate TRPC with cloudflare workers in a monorepo.
What is TRPC?
TRPC is a tool via which you can build typesafe APIs without having to generate any schema that you have to keep in sync with the server and client.
It essentially reduces the logical distance between the client and the server by allowing you to call your APIs as if they were local functions.
What is a monorepo?
If you are not familiar with a monorepo, it is a codebase that contains multiple projects, such as a frontend and a backend, in a single repository. This can be useful for sharing code between projects, managing dependencies, and simplifying the development process.
To create a monorepo, there are a lot of options, but for this experiment we will use Turborepo .
To get started, you can either clone this repo, or run the following command to bootstrap a new project:
After you’ve cloned the project, the backend code should look something like this:
This is what would look like calling the backend from the frontend:
As you can see this works, but here are some of the problems with this approach:
The API is not typesafe.
-
What if the backend changes the response shape?
-
What if the frontend parses the response incorrectly?
The API is not easily documented.
- What if the frontend developer doesn’t know what the expected input is?
Enter TRPC. With TRPC, you can call your backend APIs as if they were local functions. This means the API called is typesafe and the input and output schema is well documented.
Let’s first setup TRPC in the server
- Installing packages
Notice we have installed zod as well, which will help us in validating the user input.
- Define the router
- Initialize the router instance
- Add a query
- Validate the input with zod
- Serve the API
Now the cloudflare worker should serve the trpc routes under /trpc
.
Now let’s setup TRPC in the client
- Installing packages
- Create a client instance
- Consume the API
🎉 Congratulations, you have succesfully implemented end-to-end typesafety using TRPC
Keep in mind that this is just the setup, and you can do a lot more with TRPC. I suggest you go through the following resources to learn more:
If you want to see the complete code, you can find it here .
I hope you found this article helpful. If you have any questions or feedback, feel free to reach out to me.