How Can I Structure Types for tRPC in a Monorepo?

0
16
Asked By CuriousCoder42 On

I have a monorepo set up with a standard structure containing multiple applications and shared packages. Specifically, I have a React app, a Next.js app, and an Express server in the `apps` directory, plus a `type` package for shared types and Zod schemas in the `packages` directory. Now I want to integrate tRPC, but it requires importing the `AppRouter` type from the server. I'm worried that importing anything from the `apps/api` directory into another app could disrupt the monorepo setup. I've heard suggestions to extract the types from the API into a separate package, but that feels messy to me. The T3 template treats the entire API as a package, which they state won't leak backend code to client apps. While that makes sense, it still feels off. Are there any good resources or guides on how to approach this?

2 Answers

Answered By TypeWhisperer99 On

Creating a separate package for your types definitely seems like a reasonable approach. It keeps your applications clean and allows you to share types without directly coupling your apps. I get that it might feel a bit messy, but it’s a common pattern in monorepos. This keeps your API loosely coupled and makes it easier to scale your applications. You might find this video helpful; it shows a guy generating a TypeScript file for types and packaging it, which could give you some insight into the process! [Video Link](https://www.youtube.com/watch?v=bH87ZUYp1GU)

Answered By DevGuruLuke On

I'm not sure what you mean by "breaking the monorepo structure." You can import the `AppRouter` type into your clients without any issues. As long as you're mindful of the dependencies, it shouldn't cause any problems. Just make sure you're careful about using these types and don't end up exposing any sensitive server-side logic to your client applications.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.