Course contentsShow
← React
Lesson 1819 of 2,39642. Data Fetching LibrariesFree lesson

Nested Routers and Procedure Organization

Splitting large routers into sub-routers (user, post, comment); merging them with router.merge() for a clean API structure.

Nested Routers and Procedure Organization

What you'll learn: How to split a growing tRPC API into manageable sub-routers and merge them for a clean, scalable structure.

As your tRPC API grows beyond a few procedures, cramming everything into one router becomes unwieldy. You'll have user-related queries, post operations, comment logic, and more—all tangled together. tRPC solves this with nested routers: you create separate routers for each domain (like userRouter, postRouter, commentRouter), then merge them into a main router using router.merge().

Think of it like organizing a company directory. Instead of one massive list of every employee, you have departments (Engineering, Sales, HR), each with their own sub-directory. You access people through their department: company.engineering.johnDoe or company.sales.janeDoe.

How It Works

You define focused routers:

// userRouter.ts
const userRouter = router({
  getProfile: publicProcedure.query(/* ... */),
  updateProfile: protectedProcedure.mutation(/* ... */),
});

// postRouter.ts
const postRouter = router({
  list: publicProcedure.query(/* ... */),
  create: protectedProcedure.mutation(/* ... */),
});

Then merge them under namespaces:

// appRouter.ts
export const appRouter = router({
  user: userRouter,
  post: postRouter,
});

On the client, you call procedures with their nested path:

const { data } = trpc.user.getProfile.useQuery();
const { mutate } = trpc.post.create.useMutation();

This organization keeps related procedures together, makes code easier to navigate, and scales beautifully as teams grow. Each router can live in its own file with its own context logic and validation schemas.

Key Takeaway: Nested routers and router.merge() let you split large APIs into logical, maintainable sub-routers while maintaining full type safety across the entire structure.