Organizing tRPC Routers and Server-Side Callers
On this page
Nest routers by feature
A router can contain other routers, and the nesting becomes part of each procedure's path. TaskBoard has tasks, an admin area and a simple health check:
// src/routers/task.ts
export const taskRouter = router({
list: protectedProcedure.input(ListInput).query(/* ... */),
byId: protectedProcedure.input(z.object({ id: z.string() })).query(/* ... */),
create: protectedProcedure.input(CreateTask).mutation(/* ... */),
toggle: protectedProcedure.input(z.object({ id: z.string() })).mutation(/* ... */),
});
// src/routers/admin.ts
export const adminRouter = router({
stats: adminProcedure.query(() => ({ tasks: db.tasks.size })),
});
// src/routers/_app.ts
export const appRouter = router({
health: publicProcedure.query(() => 'ok' as const),
task: taskRouter,
admin: adminRouter,
});
export type AppRouter = typeof appRouter;On the client these become trpc.task.create.mutate(...) and trpc.admin.stats.query(). Over HTTP the path is joined with dots: POST /task.create.
A layout that holds up well as a project grows:
src/
trpc.ts initTRPC, base procedures, middleware
context.ts createContext and the Context type
schemas/task.ts Zod schemas shared with the client
routers/
_app.ts the root router and AppRouter type
task.ts
admin.ts
services/tasks.ts business logic, no tRPC importsThat last folder deserves a word. Keep procedures thin: validate input, check permissions, call a service function, return the result. Business logic that lives in plain functions can be reused by a REST endpoint, a queue worker or a script, none of which care about tRPC.
Merge routers when nesting doesn't fit
Sometimes you want procedures from two files at the *same* level, without an extra path segment. t.mergeRouters combines them:
export const appRouter = t.mergeRouters(publicRouter, accountRouter);
// procedures from both appear at the top levelMost of the time plain nesting is clearer, so treat merging as the exception.
Load big routers lazily
In serverless deployments, cold start time depends on how much code loads at startup. tRPC 11 lets you load a sub-router only when one of its procedures is first called:
import { lazy } from '@trpc/server';
export const appRouter = router({
task: taskRouter,
billing: lazy(() => import('./billing').then((m) => m.billingRouter)),
});Types still flow normally. In a test, trpc.billing.plan.query() returned 'pro' from a router that hadn't been imported until that call.
Call procedures without HTTP
Sometimes server code needs to call a procedure directly: in a test, a cron job, or server-side rendering. Going through HTTP to reach your own process would be slow and silly. A server-side caller runs procedures in-process, with the same validation and middleware:
// src/trpc.ts
export const createCallerFactory = t.createCallerFactory;
// anywhere on the server
const createCaller = createCallerFactory(appRouter);
const caller = createCaller({ user: { id: 'u9', name: 'Test', role: 'member' } });
const task = await caller.task.create({ title: 'from caller' });
const list = await caller.task.list({});Notice the calls have no .query() or .mutate(). A caller is just a tree of async functions.
You pass the context directly, which is exactly what makes callers useful for tests: you can be any user you like. If your context includes things like a database connection, build a real one for the caller rather than faking only part of it.
Write tests with a caller
Because callers skip HTTP, tests are fast and need no server. This example uses Node's built-in test runner, and Vitest works the same way:
// src/routers/task.test.ts
import test from 'node:test';
import assert from 'node:assert/strict';
import { createCallerFactory } from '../trpc';
import { appRouter } from './_app';
const createCaller = createCallerFactory(appRouter);
const ada = createCaller({ user: { id: 'u1', name: 'Ada', role: 'member' } });
const anonymous = createCaller({ user: null });
test('creates a task with a trimmed title', async () => {
const task = await ada.task.create({ title: ' Buy milk ' });
assert.equal(task.title, 'Buy milk');
});
test('rejects an empty title', async () => {
await assert.rejects(ada.task.create({ title: ' ' }), (e: any) => e.code === 'BAD_REQUEST');
});
test('requires sign-in', async () => {
await assert.rejects(anonymous.task.list({}), (e: any) => e.code === 'UNAUTHORIZED');
});ok 1 - creates a task with a trimmed title
ok 2 - rejects an empty title
ok 3 - requires sign-in
# pass 3Callers throw TRPCError directly, with a code property, so assertions are simple. These tests cover input validation, middleware and the procedure in one go.
What they don't cover is the HTTP layer: adapters, headers, cookies and batching. Add a few tests that start a real server on a random port for those, and keep the bulk of your tests on callers.
Check yourself
POST /task.create. Nested router keys are joined with dots to form the path, and the method is POST because create is a mutation. If the server is mounted under a prefix, such as /trpc on Fastify, the full path becomes /trpc/task.create.
Plain functions can be reused by other entry points like REST endpoints, workers and scripts, and they're easy to test on their own. Procedures stay thin wrappers that validate, authorize and delegate.
It runs procedures in the same process without HTTP, takes the context directly, and its procedures are plain async functions without .query() or .mutate(). Validation and middleware still run.
Callers run procedures in-process, so they skip the HTTP layer entirely: adapters, headers, cookies, body limits and batching. A misconfigured adapter, such as Fastify's parameter length limit, only shows up over real HTTP. Keep most tests on callers, and add a few that start a real server on a random port.
When cold start time matters, typically on serverless platforms. A lazy router is only imported the first time one of its procedures is called, so a rarely used area like billing doesn't slow every cold start. Types still flow normally, so clients see no difference.