Skip to main content

Merging Routers

Writing all API-code in your code in the same file is not a great idea. It's easy to merge routers with other routers.

Thanks to TypeScript 4.1 template literal types we can also prefix the procedures without breaking typesafety.

Working example​

Example code​

server.ts
import { initTRPC } from '@trpc/server';

export const t = initTRPC()();

const postRouter = t.router({
create: t.procedure
.input(
z.object({
title: z.string(),
}),
)
.mutation(({ input }) => {
// ...
return {
id: 'xxxx',
...input,
};
}),
list: t.procedure.query(() => {
// ...
return [];
}),
});

const userRouter = t.router({
list: t.procedure.query(() => {
// ..
return [];
}),
});

const appRouter = t.router({
user: userRouter, // put procedures under "user" namespace
post: postRouter, // put procedures under "post" namespace
});