Web Development · Nov 25, 2026 · 10 min read

tRPC v10 in Turborepo: Type-Safe Monorepos Without Contracts

Practical guide to tRPC v10.9 in a Turborepo monorepo with Next.js 15. Covers shared routers, Zod validation, protected procedures, React Query integration, error handling, testing, and production dep

tRPC v10 in Turborepo: Type-Safe Monorepos Without Contracts

Project Structure That Scales

A well-organized Turborepo monorepo keeps your tRPC routers, types, and business logic in packages that both your Next.js app and any future services can import directly. This eliminates duplicate type definitions and prevents drift between frontend and backend.

Run the following command to create the monorepo:

npx create-turbo@latest my-saas --example with-tailwind

After creation, the structure looks like this:

  • apps/web – Next.js 15 application using the App Router
  • packages/api – tRPC routers, procedures and context
  • packages/database – Drizzle ORM schemas and client
  • packages/ui – Shared React components
  • packages/eslint-config and packages/typescript-config – Shared tooling

The most important package is packages/api. This is where all type safety originates. Every procedure defined here is automatically typed on the client without any code generation step.

Installing Exact Dependencies

Use these versions for compatibility with Next.js 15 and React 19:

cd packages/api
npm install @trpc/server@10.45.2 zod@3.23.8
cd ../../apps/web
npm install @trpc/client@10.45.2 @trpc/react-query@10.45.2 @trpc/next@10.45.2 @tanstack/react-query@5.59.0 zod@3.23.8

The shared typescript-config package should extend from strictest with moduleResolution: "bundler" to get the best inference from tRPC.

Creating the tRPC Context with Database and Auth

The context is the foundation. It carries the database client, authenticated user, and any request-scoped services. Here is the complete implementation in packages/api/src/context.ts:

import { inferAsyncReturnType } from '@trpc/server';
import { db } from '@myorg/database';
import type { User } from '@myorg/database';

interface CreateContextOptions {
  user: User | null;
  requestId: string;
}

export const createContextInner = async (opts: CreateContextOptions) => {
  return {
    db,
    user: opts.user,
    requestId: opts.requestId,
  };
};

export const createTRPCContext = async (opts: {
  req: Request;
  user: User | null;
}) => {
  const requestId = crypto.randomUUID();
  const innerContext = await createContextInner({
    user: opts.user,
    requestId,
  });

  return {
    ...innerContext,
    req: opts.req,
  };
};

export type Context = inferAsyncReturnType<typeof createTRPCContext>;

This pattern separates test-friendly inner context creation from the actual request handler. The requestId helps with tracing across logs without relying on external observability tools in early stages.

Initializing tRPC with Middleware and Error Formatting

In packages/api/src/trpc.ts we create the tRPC instance with reusable middleware:

import { initTRPC, TRPCError } from '@trpc/server';
import type { Context } from './context';
import { z } from 'zod';

const t = initTRPC.context<Context>().create({
  errorFormatter({ shape, error }) {
    return {
      ...shape,
      data: {
        ...shape.data,
        zodError:
          error.code === 'BAD_REQUEST' && error.cause instanceof z.ZodError
            ? error.cause.flatten()
            : null,
      },
    };
  },
});

export const router = t.router;
export const publicProcedure = t.procedure;

const enforceUserIsAuthed = t.middleware(({ ctx, next }) => {
  if (!ctx.user) {
    throw new TRPCError({ code: 'UNAUTHORIZED' });
  }
  return next({
    ctx: {
      ...ctx,
      user: ctx.user,
    },
  });
});

export const protectedProcedure = t.procedure.use(enforceUserIsAuthed);

The error formatter attaches flattened Zod errors directly to the response. This allows the React client to display field-specific validation messages without extra parsing logic. The protectedProcedure is used for 80% of your application procedures in a typical SaaS.

Building Your First Router with Zod Validation

Let's implement a task management router as a realistic example. Create packages/api/src/routers/task.ts:

import { z } from 'zod';
import { router, protectedProcedure } from '../trpc';
import { tasks, projects } from '@myorg/database/schema';
import { eq, and } from 'drizzle-orm';

export const taskRouter = router({
  create: protectedProcedure
    .input(
      z.object({
        title: z.string().min(3).max(120),
        description: z.string().max(800).optional(),
        projectId: z.string().uuid(),
        dueDate: z.date().optional(),
      })
    )
    .mutation(async ({ ctx, input }) => {
      // Authorization check - user must belong to project
      const project = await ctx.db.query.projects.findFirst({
        where: and(
          eq(projects.id, input.projectId),
          eq(projects.organizationId, ctx.user.organizationId)
        ),
      });

      if (!project) {
        throw new TRPCError({
          code: 'FORBIDDEN',
          message: 'Project not found or access denied',
        });
      }

      const [task] = await ctx.db
        .insert(tasks)
        .values({
          ...input,
          createdBy: ctx.user.id,
          organizationId: ctx.user.organizationId,
        })
        .returning();

      return task;
    }),

  list: protectedProcedure
    .input(
      z.object({
        projectId: z.string().uuid().optional(),
        status: z.enum(['todo', 'in_progress', 'done']).optional(),
        limit: z.number().min(1).max(100).default(30),
      })
    )
    .query(async ({ ctx, input }) => {
      const conditions = [eq(tasks.organizationId, ctx.user.organizationId)];

      if (input.projectId) conditions.push(eq(tasks.projectId, input.projectId));
      if (input.status) conditions.push(eq(tasks.status, input.status));

      return await ctx.db.query.tasks.findMany({
        where: and(...conditions),
        limit: input.limit,
        orderBy: (tasks, { desc }) => [desc(tasks.createdAt)],
      });
    }),
});

Notice how the same Zod schemas used for validation become TypeScript types on the client automatically. The authorization check against organizationId implements basic multi-tenancy at the procedure level.

Merging Routers and Exporting the App Router

In packages/api/src/root.ts combine multiple routers:

import { router } from './trpc';
import { taskRouter } from './routers/task';
import { projectRouter } from './routers/project';
import { organizationRouter } from './routers/organization';

export const appRouter = router({
  task: taskRouter,
  project: projectRouter,
  organization: organizationRouter,
});

export type AppRouter = typeof appRouter;

This AppRouter type is imported by the Next.js frontend. Any change to a procedure signature immediately shows TypeScript errors in the calling components during development.

Creating the tRPC Handler in Next.js App Router

Inside apps/web/src/app/api/trpc/[trpc]/route.ts:

import { fetchRequestHandler } from '@trpc/server/adapters/fetch';
import { appRouter } from '@myorg/api';
import { createTRPCContext } from '@myorg/api';
import { getCurrentUser } from '@/lib/auth'; // your auth solution

const handler = (req: Request) =>
  fetchRequestHandler({
    endpoint: '/api/trpc',
    req,
    router: appRouter,
    createContext: async () => {
      const user = await getCurrentUser();
      return createTRPCContext({ req, user });
    },
    onError({ error, path }) {
      console.error(`tRPC error on ${path}:`, error);
      // Send to Sentry or your error tracking service here
    },
  });

export { handler as GET, handler as POST };

Using the fetch adapter works perfectly with the App Router and edge runtime when needed. The getCurrentUser function can come from Lucia, Auth.js, or Clerk depending on your stack.

Creating the Type-Safe React Client

In apps/web/src/trpc/react.tsx set up the React Query integration:

import { createTRPCReact } from '@trpc/react-query';
import type { AppRouter } from '@myorg/api';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { httpBatchLink } from '@trpc/client';
import { useState } from 'react';

export const trpc = createTRPCReact<AppRouter>();

export function TRPCProvider(props: { children: React.ReactNode }) {
  const [queryClient] = useState(() => new QueryClient({
    defaultOptions: {
      queries: {
        staleTime: 1000 * 60 * 5, // 5 minutes
        refetchOnWindowFocus: false,
      },
    },
  }));

  const [trpcClient] = useState(() =>
    trpc.createClient({
      links: [
        httpBatchLink({
          url: '/api/trpc',
          fetch(url, opts) {
            return fetch(url, {
              ...opts,
              credentials: 'include',
            });
          },
        }),
      ],
    })
  );

  return (
    <trpc.Provider client={trpcClient} queryClient={queryClient}>
      <QueryClientProvider client={queryClient}>
        {props.children}
      </QueryClientProvider>
    </trpc.Provider>
  );
}

The httpBatchLink automatically batches multiple tRPC calls into a single HTTP request when they happen within the same event loop tick. This reduces network overhead significantly in dashboard interfaces that load multiple related resources.

Using tRPC Procedures in Components

With the provider wrapping your app, components become fully typed:

'use client';

import { trpc } from '@/trpc/react';
import { TaskCard } from './TaskCard';

export default function ProjectDashboard({ projectId }: { projectId: string }) {
  const { data: tasks, isLoading } = trpc.task.list.useQuery({
    projectId,
    status: 'todo',
  });

  const createTask = trpc.task.create.useMutation({
    onSuccess() {
      // Invalidates and refetches the list query automatically
      utils.task.list.invalidate();
    },
  });

  if (isLoading) return <div>Loading tasks...</div>;

  return (
    <div>
      {tasks?.map((task) => (
        <TaskCard key={task.id} task={task} />
      ))}
      
      <button => createTask.mutate({
        title: 'New feature',
        projectId,
      })}>
        Create Task
      </button>
    </div>
  );
}

The utils object (available via trpc.useUtils()) gives you access to invalidate, setData, and optimistic updates with full type safety. No more stringly-typed query keys.

Optimistic Updates and Rollbacks

For better UX, implement optimistic updates on mutations:

const utils = trpc.useUtils();

const createTask = trpc.task.create.useMutation({
  onMutate: async (newTask) => {
    await utils.task.list.cancel();
    
    const previousTasks = utils.task.list.getData({ projectId: newTask.projectId });
    
    utils.task.list.setData(
      { projectId: newTask.projectId },
      (old) => [...(old || []), { id: 'temp-id', ...newTask, status: 'todo' }]
    );
    
    return { previousTasks };
  },
  onError(err, newTask, context) {
    if (context?.previousTasks) {
      utils.task.list.setData(
        { projectId: newTask.projectId },
        context.previousTasks
      );
    }
  },
  onSettled() {
    utils.task.list.invalidate();
  },
});

This pattern provides instant feedback to users while gracefully handling network failures by restoring the previous cache state.

Advanced Middleware Patterns

You can stack multiple middlewares. For example, a rate limiting middleware combined with organization context:

const rateLimit = t.middleware(async ({ ctx, next }) => {
  // Implement simple in-memory rate limiting for demonstration
  const key = `rate-limit:${ctx.user?.id}`;
  // In production use Upstash Redis or similar
  // const count = await redis.incr(key);
  
  return next();
});

const withOrganization = t.middleware(async ({ ctx, next }) => {
  if (!ctx.user?.organizationId) {
    throw new TRPCError({ code: 'BAD_REQUEST' });
  }
  return next({
    ctx: { ...ctx, organizationId: ctx.user.organizationId },
  });
});

export const orgProcedure = protectedProcedure
  .use(rateLimit)
  .use(withOrganization);

These composable middlewares keep your procedure code clean while enforcing cross-cutting concerns consistently.

Testing Routers in Isolation

Because the context is injectable, unit testing is straightforward. Using Vitest:

import { describe, it, expect, vi } from 'vitest';
import { appRouter } from '@myorg/api';
import { createContextInner } from '@myorg/api/context';

describe('task router', () => {
  it('creates a task', async () => {
    const ctx = await createContextInner({
      user: { id: 'user_1', organizationId: 'org_1' },
      requestId: 'test-1',
    });
    
    const caller = appRouter.createCaller(ctx);
    
    const task = await caller.task.create({
      title: 'Test task',
      projectId: 'proj_1',
    });
    
    expect(task.title).toBe('Test task');
  });
});

This approach tests business logic without starting an HTTP server. Integration tests can use the full fetch handler against a test database.

Production Considerations and Trade-offs

tRPC shines when your team owns both frontend and backend. The tight coupling becomes an advantage because changes are caught at compile time. However, if you need to expose APIs to third-party developers, you should provide a separate REST or GraphQL interface that reuses the same business logic.

Bundle size impact is minimal. The client bundle for tRPC with React Query adds roughly 14kB gzipped. This is comparable to a single TanStack Query installation but with far more type safety.

For extremely high throughput public APIs, the JSON-RPC format of tRPC can be slightly more verbose than hand-tuned REST endpoints. In practice this only matters beyond 5000 requests per second per instance. Most SaaS applications never reach this scale.

Deployment on Vercel works without configuration. When using the Edge Runtime, make sure your database client supports it (Drizzle with Neon or PlanetScale driver does). For complex queries that need longer execution time, use Node.js runtime for the tRPC route specifically.

Subscriptions and Real-Time Updates

While tRPC supports WebSocket subscriptions, in a Next.js App Router context many teams prefer Server-Sent Events (SSE) for simplicity. You can implement an SSE procedure using protectedProcedure.subscription with a simple event emitter or by integrating with Pusher, Supabase Realtime or Liveblocks.

Example skeleton for an SSE-based task update subscription:

taskUpdates: protectedProcedure
  .input(z.object({ projectId: z.string().uuid() }))
  .subscription(({ ctx, input }) => {
    return observable<Task>((emit) => {
      const listener = (updatedTask: Task) => {
        if (updatedTask.projectId === input.projectId) {
          emit.next(updatedTask);
        }
      };
      
      eventEmitter.on('task.updated', listener);
      
      return () => {
        eventEmitter.off('task.updated', listener);
      };
    });
  }),

The React client can consume this with useSubscription from @trpc/react-query.

Migrating an Existing Codebase

When introducing tRPC to a brownfield project, start by wrapping existing REST endpoints in tRPC procedures that call the same service functions. This gives you type safety on the frontend immediately. Over time, move business logic into the procedures themselves. The shared packages/api makes this migration incremental and low risk.

Avoid the temptation to create one giant router. The nested structure (task.create, task.list, organization.billing) improves both discoverability in autocomplete and logical separation of concerns.

Always version your procedures implicitly by keeping backward compatibility during refactors. Since the entire contract is TypeScript, you get compile-time warnings when frontend code breaks. This is more reliable than OpenAPI specification drift that occurs in many codebases.

The combination of tRPC v10.9, Turborepo, and Next.js 15 provides the tightest feedback loop currently available in the TypeScript ecosystem for full-stack development. Changes to your database schema or business rules surface immediately in your editor across every layer of the application.

By centralizing all API logic in one place with proper middleware composition, input validation, and authorization, you reduce the surface area for bugs that typically appear at the boundaries between frontend and backend teams.

Keep reading

Related Articles