Skip to content
MiraiTech
All writing
Full stack

· 7 min read

End-to-end types with tRPC and Next.js

Why we replaced REST controllers with tRPC, how we structure routers, handle errors and write tests, and when we would not use it.

Why we stopped writing REST controllers

Every full-stack TypeScript project we've built hits the same problem at the API layer. Someone renames a field in Prisma, updates the backend handler and forgets the React Query call on the frontend. Nothing breaks at build time. The bug shows up three days later, when a QA engineer happens to click the right button.

tRPC removes that class of bug. The client gets the server's types at compile time, with no code generation step and no OpenAPI spec to keep in sync. We've used it on six production projects, and it's now our default for any Next.js app where the same team owns the frontend and the backend.

Router architecture

We split routers by business capability rather than by database table, then compose them into the root app router. This is the billing router:

src/server/trpc/routers/billing.ts
import { z } from 'zod';
import { router, protectedProcedure, adminProcedure } from '../init';
import { TRPCError } from '@trpc/server';
import { stripe } from '@/lib/stripe';
 
const billingRouter = router({
  getSubscription: protectedProcedure.query(async ({ ctx }) => {
    const sub = await ctx.db.subscription.findUnique({
      where: { organizationId: ctx.session.orgId },
      include: { plan: true, invoices: { take: 5, orderBy: { createdAt: 'desc' } } },
    });
 
    if (!sub) {
      throw new TRPCError({
        code: 'NOT_FOUND',
        message: 'No active subscription found',
      });
    }
 
    return {
      plan: sub.plan.name,
      status: sub.status,
      currentPeriodEnd: sub.currentPeriodEnd,
      recentInvoices: sub.invoices.map((inv) => ({
        id: inv.id,
        amount: inv.amount,
        status: inv.status,
        date: inv.createdAt,
      })),
    };
  }),
 
  changePlan: protectedProcedure
    .input(z.object({
      planId: z.string(),
      prorationBehavior: z.enum(['create_prorations', 'none']).default('create_prorations'),
    }))
    .mutation(async ({ ctx, input }) => {
      const currentSub = await ctx.db.subscription.findUniqueOrThrow({
        where: { organizationId: ctx.session.orgId },
      });
 
      const updated = await stripe.subscriptions.update(currentSub.stripeId, {
        items: [{ id: currentSub.stripeItemId, plan: input.planId }],
        proration_behavior: input.prorationBehavior,
      });
 
      await ctx.db.subscription.update({
        where: { id: currentSub.id },
        data: { planId: input.planId, status: updated.status },
      });
 
      return { success: true, effectiveDate: updated.current_period_start };
    }),
 
  getUsageMetrics: adminProcedure
    .input(z.object({
      period: z.enum(['7d', '30d', '90d']).default('30d'),
    }))
    .query(async ({ ctx, input }) => {
      return ctx.db.usageRecord.groupBy({
        by: ['metric'],
        where: {
          organizationId: ctx.session.orgId,
          createdAt: { gte: periodToDate(input.period) },
        },
        _sum: { value: true },
        _count: true,
      });
    }),
});
 
export default billingRouter;

Composing procedures with middleware

Middleware is the part of tRPC we use most. Instead of decorators or wrapper functions, you build procedures by chaining middleware, and the types carry through the chain:

src/server/trpc/init.ts
import { initTRPC, TRPCError } from '@trpc/server';
import superjson from 'superjson';
import type { Context } from './context';
 
const t = initTRPC.context<Context>().create({
  transformer: superjson,
  errorFormatter({ shape, error }) {
    return {
      ...shape,
      data: {
        ...shape.data,
        zodError: error.cause instanceof z.ZodError ? error.cause.flatten() : null,
      },
    };
  },
});
 
export const router = t.router;
export const publicProcedure = t.procedure;
 
const enforceAuth = t.middleware(async ({ ctx, next }) => {
  if (!ctx.session?.user) {
    throw new TRPCError({ code: 'UNAUTHORIZED' });
  }
  return next({
    ctx: { session: ctx.session },
  });
});
 
const enforceAdmin = t.middleware(async ({ ctx, next }) => {
  if (ctx.session?.user?.role !== 'admin') {
    throw new TRPCError({ code: 'FORBIDDEN' });
  }
  return next({ ctx });
});
 
const withRateLimit = t.middleware(async ({ ctx, next, path }) => {
  const key = `ratelimit:${ctx.session?.user?.id ?? ctx.ip}:${path}`;
  const current = await ctx.redis.incr(key);
  if (current === 1) await ctx.redis.expire(key, 60);
  if (current > 100) {
    throw new TRPCError({ code: 'TOO_MANY_REQUESTS', message: 'Rate limit exceeded' });
  }
  return next();
});
 
export const protectedProcedure = publicProcedure.use(enforceAuth).use(withRateLimit);
export const adminProcedure = protectedProcedure.use(enforceAdmin);

Error handling

We sort tRPC errors into expected ones (validation failures, not found, permissions) and unexpected ones (database timeouts, third-party API failures). The error formatter passes Zod validation details to the client and keeps internal errors opaque.

Error typetRPC codeClient behavior
Validation failureBAD_REQUESTShow field-level errors inline
Not authenticatedUNAUTHORIZEDRedirect to login
Not authorizedFORBIDDENShow permission denied toast
Resource missingNOT_FOUNDShow 404 component
Rate limitedTOO_MANY_REQUESTSRetry with backoff
Server errorINTERNAL_SERVER_ERRORShow generic error, log to Sentry

On the client, we wrap tRPC's React Query hooks with a global error handler:

src/lib/trpc-client.ts
import { httpBatchLink, loggerLink } from '@trpc/client';
import { createTRPCNext } from '@trpc/next';
import type { AppRouter } from '@/server/trpc/root';
import superjson from 'superjson';
import { toast } from 'sonner';
 
export const trpc = createTRPCNext<AppRouter>({
  config() {
    return {
      links: [
        loggerLink({ enabled: () => process.env.NODE_ENV === 'development' }),
        httpBatchLink({
          url: '/api/trpc',
          transformer: superjson,
        }),
      ],
      queryClientConfig: {
        defaultOptions: {
          mutations: {
            onError(error) {
              if (error.data?.code === 'UNAUTHORIZED') {
                window.location.href = '/login';
                return;
              }
              toast.error(error.message);
            },
          },
          queries: {
            retry: (failureCount, error) => {
              if (['UNAUTHORIZED', 'FORBIDDEN', 'NOT_FOUND'].includes(error.data?.code)) {
                return false;
              }
              return failureCount < 3;
            },
            staleTime: 5 * 60 * 1000,
          },
        },
      },
    };
  },
  ssr: false,
});

Testing

Unit testing procedures

We test procedures by calling them directly with a mock context, so no HTTP server is involved. This part of tRPC gets less attention than it deserves:

src/server/trpc/__tests__/billing.test.ts
import { createInnerContext } from '../context';
import { appRouter } from '../root';
import { mockDeep } from 'jest-mock-extended';
import type { PrismaClient } from '@prisma/client';
 
describe('billing.getSubscription', () => {
  it('returns formatted subscription data', async () => {
    const prismaMock = mockDeep<PrismaClient>();
    prismaMock.subscription.findUnique.mockResolvedValue({
      plan: { name: 'Pro' },
      status: 'active',
      currentPeriodEnd: new Date('2025-02-01'),
      invoices: [{ id: 'inv_1', amount: 4900, status: 'paid', createdAt: new Date() }],
    });
 
    const ctx = createInnerContext({
      db: prismaMock,
      session: { user: { id: 'user_1' }, orgId: 'org_1' },
    });
 
    const caller = appRouter.createCaller(ctx);
    const result = await caller.billing.getSubscription();
 
    expect(result.plan).toBe('Pro');
    expect(result.recentInvoices).toHaveLength(1);
  });
 
  it('throws NOT_FOUND when no subscription exists', async () => {
    const prismaMock = mockDeep<PrismaClient>();
    prismaMock.subscription.findUnique.mockResolvedValue(null);
 
    const ctx = createInnerContext({
      db: prismaMock,
      session: { user: { id: 'user_1' }, orgId: 'org_1' },
    });
 
    const caller = appRouter.createCaller(ctx);
    await expect(caller.billing.getSubscription()).rejects.toThrow('NOT_FOUND');
  });
});

Integration tests against a real database

For integration tests we create a database per test file with Prisma migrations. That catches query bugs that mocks silently ignore: wrong include nesting, missing indexes on orderBy fields and constraint violations.

Performance

OptimizationImpactComplexity
HTTP batchingReduces round trips for parallel queriesLow (built-in)
Response caching headersReduces server load for read-heavy routesLow
Query splittingPrevents a slow query from blocking fast onesMedium
Streaming (experimental)Enables progressive UI updatesHigh

We turn on HTTP batching by default but send critical-path queries, such as session validation, through a separate non-batched link. That way the auth check never waits behind a slow analytics query.

When not to use tRPC

tRPC is the right choice when one team owns client and server in a TypeScript monorepo. It's the wrong choice when:

  • External consumers need your API (use OpenAPI/REST or GraphQL instead)
  • Your backend isn't TypeScript (obviously)
  • You need protocol-level caching semantics that rely on standard HTTP methods

We've run tRPC alongside REST endpoints in the same Next.js app: tRPC for internal app routes, REST for webhooks and public API endpoints. The two coexist without trouble.

Written by the MiraiTech team in Tokyo

If something here is wrong, or you are working on a similar problem, write to us at contact@mirai-tech.net.