Skip to content

feat: Define a router independently of its implementation #3798

Closed as not planned

Description

@rhinodavid

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!

TRP-52

Activity

  1. changed the title [-]feat: Define a router independently of its definition[/-] [+]feat: Define a router independently of its implementation[/+] on Feb 19, 2023
  2. Nick-Lucas commented on Feb 19, 2023

    @Nick-Lucas
    Contributor

    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.

    One should not need the server implementation in order to get a typed client

    Doing this in TypeScript is a bit different to most languages. When you import type {} from you 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.

    My proposed solution is to create utility types to define the router type

    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:

    const appRouter = router({
      greet: procedure/*etc*/
    }) satisfies TAppRouter

    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

  3. rhinodavid commented on Feb 24, 2023

    @rhinodavid
    Author

    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.

  4. Nick-Lucas commented on Feb 24, 2023

    @Nick-Lucas
    Contributor

    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

  5. ilijaNL commented on Mar 12, 2023

    @ilijaNL

    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.

  6. rhinodavid commented on May 10, 2023

    @rhinodavid
    Author

    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:

     const teamRouterDefinition =  {
            getById: {
                // Get a team by its ID
                input: z.string().cuid().describe('The team ID'),
                output: team
                    .strip()
                    .nullable()
                    .describe(
                        'The team, or null if not found. '
                    ),
                type: 'query',
            }
    };

    And using that plus a context type (could also include meta) we can produce a router type:

    export type TeamRouter = defineTrpcRouter<typeof teamRouterDefinition, { ctx: { isLoggedIn: boolean }}>;

    Clients get initialized with the exported router type, and in the router implementation we make sure it satisfies the exported router type.

    The only real downside is that we're importing types from internals.

  7. masha256 commented on May 16, 2023

    @masha256

    I for one would love to have separated type definitions!

  8. ajs11174 commented on May 17, 2023

    @ajs11174

    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.

    import { SignedInAuthObject, SignedOutAuthObject } from '@clerk/clerk-sdk-node';
    import { CreateTRPCNextBase } from '@trpc/next';
    import { DecoratedProcedureRecord } from '@trpc/react-query/shared';
    import { AnyRouter, DefaultErrorShape, RootConfig } from '@trpc/server';
    import { CreateRouterInner } from '@trpc/server/dist/core/router';
    import { NextPageContext } from 'next';
    import superjson from 'superjson';
    
    export type TRPCNextClientLike<RouterDef extends { [key: string]: AnyRouter }> = CreateTRPCNextBase<
      CreateRouterInner<
        RootConfig<{
          ctx: {
            auth: SignedInAuthObject | SignedOutAuthObject;
          };
          meta: object;
          errorShape: DefaultErrorShape;
          transformer: typeof superjson;
        }>,
        RouterDef
      >,
      NextPageContext
    > &
      DecoratedProcedureRecord<RouterDef, null>;

    I'm using clerk here and that isn't required for an implementation, however the ctx, errorShape, and transformer should all match the t object created when calling the initTRPC.context<Context>().create({...}) function.


    Assuming you have a nested router like this:

    const exampleRouter = t.router({
      hello: t.procedure.query(() => {
        return 'world';
      }),
    });

    You can create a component like this:

    export function MyComponent({ trpc }: { trpc: TRPCNextClientLike<{ example: typeof exampleRouter }> }) {
      const { data } = trpc.example.hello.useQuery();
    
      return <pre>{JSON.stringify(data, null, 2)}</pre>;
    }

    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.

    export const appRouter = t.router({
      example: exampleRouter,
    });
    
    export type AppRouter = typeof appRouter;

    Then you will be able to pass down the trpc object created by createTRPCNext<AppRouter>({...}) to your component.

    import { trpc } from '../server/client';
    
    export function MyPage() {
      return (
        <MyComponent trpc={trpc} />
      )
    }

    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 @trpc packages.

  9. changed the title [-]feat: Define a router independently of its implementation[/-] [+][TRP-52] feat: Define a router independently of its implementation[/+] on May 25, 2023
  10. changed the title [-][TRP-52] feat: Define a router independently of its implementation[/-] [+]feat: Define a router independently of its implementation[/+] on May 25, 2023
  11. 4 remaining items

  12. thekumar commented on Dec 29, 2023

    @thekumar

    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!

  13. ferdy-roz commented on Apr 23, 2024

    @ferdy-roz

    +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

  14. KATT commented on Apr 23, 2024

    @KATT
    Member

    You can do something like this to define a structure:

    interface MyRouter {
      greeting: QueryProcedure<{
        input: {
          name: string;
        };
        output: {
          message: string;
        };
      }>;
    }

    then define the router accordingly

    export const myRouter = {
      greeting: publicProcedure
        .input(
          z.object({
            name: z.string(),
          }),
        )
        .query((opts) => {
          return {
            message: `Hello ${opts.input.name}`,
          };
        }),
    } satisfies MyRouter;

    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.

  15. ferdy-roz commented on Apr 24, 2024

    @ferdy-roz

    @KATT that's helpful, how do you use MyRouter here when calling e.g. createTRPCProxyClient?

    I have something like

    class SdkClient {
       ...
       // TS2344: Type MyRouter does not satisfy the constraint Router<any, any>
       // Type MyRouter is missing the following properties from type Router<any, any>: _def, createCaller
       private trpc: ReturnType<typeof createTRPCProxyClient<MyRouter>>;
    }
    
  16. InfiniteXyy commented on Apr 30, 2024

    @InfiniteXyy

    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!)

    // Defintion 
    type TQuery<PB extends ProcedureBuilder<any>> = Parameters<PB["query"]>[0];
    
    const searchApi = publicProcedure
      .input(z.object({ keyword: z.string() }))
      .output(z.array(z.object({ query: z.string(), title: z.string() })));
    
    const completionApi = publicProcedure
      .input(z.object({ keyword: z.string() }))
      .output(z.array(z.object({ option: z.string() })));
    
    export const createSearchRouter = (queries: {
      searchQuery: TQuery<typeof searchApi>;
      completionQuery: TQuery<typeof completionApi>;
    }) => {
      return router({
        search: searchApi.query(queries.searchQuery),
        completions: completionApi.query(queries.completionQuery),
      });
    };
    
    // Implementation
    export const appRouter = createSearchRouter({ searchQuery: xxx, completionQuery :xxx })
    
    // Usage 
    const client = createTRPCClient<ReturnType<typeof createSearchRouter>>()
  17. nicroto commented on Aug 25, 2024

    @nicroto

    +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.

  18. ivan-kleshnin commented on Sep 21, 2024

    @ivan-kleshnin

    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.

    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:

    • "Go to definition" editor action moves you to a contract. To see an implementation you have to do extra steps. With TRPC "Cmd-B" works perfectly. There're just 2 places. It's similar to Tailwind CSS convenience over basic CSS.
    • Type inference in Zodios and TS-REST is much slower. And with large projects, with Zod, it becomes the most CPU consuming task... I'm not sure what is the issue but it might be related to separate contracts and overcomplicated type-safety (this one is too easy to get too far). E.g. TS-REST wants to validate status codes, and headers...
    • TRPC shares just types with client. It prevents the browser from accidentally bundling BE code. We had so many issues with unwanted bundling in Zodios (schemas tend to pull in some helpers and then it begins...). It also makes Zod a FE requirement, adds a whole new layer or logic (Zodios validates inputs & outputs on the FE as well). Great in theory, not so great in practice.

    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 /myActionName and 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-body to have it ecosystem compatible. Finally, think about builtin, streamlined type generation for monorepos (instead of a shared schema).

  19. KATT commented on Sep 22, 2024

    @KATT
    Member

    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?

  20. ivan-kleshnin commented on Sep 22, 2024

    @ivan-kleshnin

    @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.

  21. hayksaryan commented on Jan 14, 2025

    @hayksaryan

    @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.

    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

  22. Nick-Lucas commented on Jan 14, 2025

    @Nick-Lucas
    Contributor

    @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

  23. Nick-Lucas commented on Jan 14, 2025

    @Nick-Lucas
    Contributor

    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

  24. github-actions commented on Jan 16, 2025

    @github-actions
    Contributor

    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.

  25. locked as resolved and limited conversation to collaborators on Jan 16, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions