Repository navigation
Description
Describe the feature you'd like to request
See example repo (https://github.com/rhinodavid/trpc-server-definition) for all the details
My request is similar to the one @iduuck wrote about in #3496 (comment). tldr: One should not need the server implementation in order to get a typed client. Currently this is not possible (I don't think -- I"m pretty new here) -- all the examples I've seen create the client using the typeof the AppRouter definition.
Describe the solution you'd like to see
My proposed solution is to create utility types to define the router type. Usage would look like this:
// appRouterInterface.ts
import type { defineRouter, defineQueryProcedure } from "@trpc/server";
export type TAppRouter = defineRouter<{
greet: defineQueryProcedure<{name: string}, {greeting: string}>;
}>In the server implementation, you'd enforce that the server satisfies the interface:
// server.ts
// ...
import type { TAppRouter } from "./appRouterInterface";
// this could be published as an open source package ^^
export const appRouter = t.router({ /* ... */ }) satisfies TAppRouter;Then the client is typed with the interface:
// client.ts
import type { TAppRouter } from "./appRouterInterface";
export const client = createTRPCProxyClient<TAppRouter>({ /* ... */ });The example repo has a complete(?) working PoC.
Describe alternate solutions
Another possible solution is a codegen step as described in #3496 (comment).
The pro of this solution is it keeps the existing pattern of
[implement router] -> [extract interface].
Some might prefer this, but after a long time using gRPC/stubby I'm more used to the [define interface] -> [implement router] pattern. This pattern is better for large organizations where multiple teams might need to debate and agree on the interface.
The con of the solution is codegen can be finicky. It also doesn't easily solve the workspace organization problem I describe in my example repo readme.
Additional information
No response
👨👧👦 Contributing
- 🙋♂️ Yes, I'd be down to file a PR implementing this feature!
Activity
[-]feat: Define a router independently of its definition[/-][+]feat: Define a router independently of its implementation[/+]Nick-Lucas commentedon Feb 19, 2023
My understanding is the implementation->interface approach is very much at the core of tRPC's design. It's likely to never be flipped around simply because every time I've seen the suggestion the justification amounts to "because I like it that way", and that's not a great justification for increasing the project's API surface. - my views and understanding here are my own by the way, the core team definitely might have changed their view since this last came up.
Doing this in TypeScript is a bit different to most languages. When you
import type {} fromyou don't pull in any of the implementation code, just the resulting types. Some people choose to put their routers in a library and then the API just imports that library and handles the server stuff.This is actually likely to be possible today just with a little work on utility types, and could be prototyped in user-land - even released in user-land as a community project if the proposal doesn't get traction.
The best way to then apply your interface post TS4.9 would be like:
The thing is I'm not sure what benefits it really has, it's not functionally necessary as best I can tell, just has some possible organisational benefit to big teams
rhinodavid commentedon Feb 24, 2023
It's definitely possible -- I did it in my example repo. It's just fragile since it's not upstreamed and uses internal types.
I think the benefit is optionality. User-first API design starts with the API and the implementation follows. It's fine to do it the other way around if the stakeholders are all colocated with the implementation, but once the API needs to be pushed out to external users or some other team or company or whatever then there needs to be a way to define, not infer, the API. trpc is awesome, but right now it doesn't enable this.
Nick-Lucas commentedon Feb 24, 2023
If you want to push it out to external clients/users you might want to look at the tRPC openapi extension. That way they can consume it like a REST api and use codegen.
It should also be possible to use TSC to generate types in an npm package but I haven't seen a full example of this yet or had time to play with it
ilijaNL commentedon Mar 12, 2023
Coming from #3699.
Another approach is just to have a "defined router". This router does not have any procedure implementation however still has input & output validation implementations. You can easy put the defined router in shared library with minimal dependencies (only trpc and the validation lib) and use it to implement the server. On the client the same definition can be used to infer the trpcClient. Additional benefit is that the client can re-use the input validation implementation. However this probably needs a major rewrite in the core.
rhinodavid commentedon May 10, 2023
FWIW we've been using a slightly different version of https://github.com/rhinodavid/trpc-server-definition at 0x for a few months now and it's working pretty well. In an interface package we define the router spec:
And using that plus a context type (could also include
meta) we can produce a router type:Clients get initialized with the exported router type, and in the router implementation we make sure it
satisfiesthe exported router type.The only real downside is that we're importing types from
internals.masha256 commentedon May 16, 2023
I for one would love to have separated type definitions!
ajs11174 commentedon May 17, 2023
Here's what I landed on in my codebase. I can pass a typed client to my components without needing the server implementation.
I created a type that recreates the types generated from the
createTRPCNext<AppRouter>({...})function.I'm using clerk here and that isn't required for an implementation, however the
ctx,errorShape, andtransformershould all match thetobject created when calling theinitTRPC.context<Context>().create({...})function.Assuming you have a nested router like this:
You can create a component like this:
This can be done without calling
createTRPCNext<AppRouter>({...})Eventually you will need to assemble an app router and call
createTRPCNext<AppRouter>({...}).When you do, make sure you mount your nested routers on the correct path. Based on the above example it would look like this.
Then you will be able to pass down the
trpcobject created bycreateTRPCNext<AppRouter>({...})to your component.I assume the same setup could be used for a react client, but I haven't looked at that.
It would be great if trpc could add some utility types that are easier to create directly in one of the
@trpcpackages.[-]feat: Define a router independently of its implementation[/-][+][TRP-52] feat: Define a router independently of its implementation[/+][-][TRP-52] feat: Define a router independently of its implementation[/-][+]feat: Define a router independently of its implementation[/+]4 remaining items
thekumar commentedon Dec 29, 2023
I still wish TRPC had better support for splitting up definition and implementation, but for now @misupov 's solution seems to be the best way to achieve this. The need to split up API vs Impl isn't just an aesthetic preferences, but makes the whole system more testable.
For example, in my case, I have a simple react frontend app that's deployed to firebase hosting, and have a nodejs server with an api that comes with additional dependencies on firestore, a postgres database backend, and a large multi-gigabyte custom ml model inference library. For me to build and test the simple frontend app... I now have to depend on the heavy server package unnecessarily just to get the type of the AppRouter.
Being able to split the router def from its implementation means that my react-app can depend on a lightweight api package, and the server can also depend on this lightweight package to implement the interface definition. I can also now mock out the server implementation easily for tests. In addition, I any number of server implementations built that satisfy the TRPC interface and have them run on various different database backends.
For now, I will follow the pattern laid out by @misupov . Thanks!
ferdy-roz commentedon Apr 23, 2024
+1 I have been messing around migrating to other libraries like ts-rest that do this, but they are really all much worse than tRPC. if tRPC supported this I wouldn't have to migrate.
My use case is developing an SDK for public consumption on top of our APIs
KATT commentedon Apr 23, 2024
You can do something like this to define a structure:
then define the router accordingly
the above can be used in e.g.
t.router({ myRouter })It's totally possible to do a public SDK with tRPC, but it'd take me a some hours to build a good reference - feel free to email me at [email protected] if you want to hire and pay me to do it.
ferdy-roz commentedon Apr 24, 2024
@KATT that's helpful, how do you use
MyRouterhere when calling e.g.createTRPCProxyClient?I have something like
InfiniteXyy commentedon Apr 30, 2024
I am also looking forward to see trpc support structure only definition.
The situation I encountered is:
We don't use monorepo, but have many microservices. In order to avoid duplicated type definitions, we want to publish a private npm package to store API types, the implemention should in microservices, and usage is in frontend.
If frontend directly import from the backend (as document said), then we need to publish all microservices we have with npm, which is not good.
My current workaround is like
(Inspired by @misupov , thanks!)
nicroto commentedon Aug 25, 2024
+1
We have a monorepo setup, micro-services communicate via tRPC, and since we can't just load only the client definition without a connection to the implementation - the caller's compilation pulls unnecessary requirements for things like env variables.
ivan-kleshnin commentedon Sep 21, 2024
Here's my feedback based on TRPC, Zodios and TS-REST experience 🙏
It's only partially related to the quoted paragraph... but I'd still like to add my 5 cents.
I experimented with all 3. With Zodios and TS-REST:
I agree that TRPC is not convenient for monorepos. But there's a more important issue underneath IMO:
It is the positioning of TRPC as a tool strongly focused on "internal API"s. There's nothing wrong with RPC for public APIs per se. Just POST to
/myActionNameand call it a day if you can unlearn the things REST cultists told you... But TRPC wanted to be smart, so it started to mess with input formats, encode, bother about HTTP caching that you shouldn't really use in APis. Making itself incompatible with Postman and basically every HTTP and testing tool in existence. Was it worth it? Similar concerns were raised previously:It still boggles me that I have to use another framework on top of TRPC or hack with adapters simply to integrate an external logger like BetterStack or mock a req/resp in Playwright.
NextJS presented its actions as "we have TRPC at home" and, because TRPC had exactly the same project scope, it was kinda destined to lose the battle against a larger opponent.
I think there's still a chance to rematch it. Reposition & refactor TRPC to a general purpose API layer. Make queries and mutations accept simple
POST json-bodyto have it ecosystem compatible. Finally, think about builtin, streamlined type generation for monorepos (instead of a shared schema).KATT commentedon Sep 22, 2024
Appreciate the feedback @ivan-kleshnin.
The thing is, I built trpc for myself and my usecases - if I had the need of this, I would've made it compatible and probably open-sourced it.
There's no financial incentives behind trpc apart donations - we mainly do this for fun. As DHH nicely puts it - open-source is a gift exchange.
If you want a specific feature implemented, you can either offer to pay us to do it or get involved and we'll happily show you the ropes on how you could contribute the feature you need.
I have played with the idea of building a trpc-openapi like thing and make it a paid extension, would that be of interest?
ivan-kleshnin commentedon Sep 22, 2024
@KATT thank you! I would never call TRPC a "hobby project" – it's one of the most professionally written TS library I'm aware of. In general, we're in the process of switching from TypeScript to Python, thus we can't really invest too much in NodeJS ecosystem. Why Python? Mostly becase we have a lot of ML and it's too hard to support 2 backend languages for a small team. Partly because we're preparing for Mojo 🔥 and Python -> Mojo transition is gonna be much easier than TS -> Mojo.
hayksaryan commentedon Jan 14, 2025
Does this mean we should expect TRPC to transition to a more passively maintained/unmaintained state? We're using TRPC in our project, and it would be best if we knew beforehand if we're looking at a potential migration away from TRPC
Nick-Lucas commentedon Jan 14, 2025
@hayksaryan tRPC is still under very active development, and has sponsors, but still all FOSS is technically hobby projects. If you'd like to ensure its sustainability then please consider sponsoring it
Nick-Lucas commentedon Jan 14, 2025
I'm going to close this issue as it's been around for a long time and there are no current plans to do this
github-actions commentedon Jan 16, 2025
This issue has been locked because we are very unlikely to see comments on closed issues. If you are running into a similar issue, please create a new issue. Thank you.