Does Fastify Work With tRPC?
Fastify and tRPC work together seamlessly, with tRPC providing an official Fastify adapter for typesafe RPC endpoints.
Quick Facts
How Fastify Works With tRPC
Fastify and tRPC integrate through tRPC's official `@trpc/server` adapter for Fastify, which handles HTTP request routing and response serialization. You define your tRPC router with procedures (queries, mutations, subscriptions) and mount it as a Fastify plugin using `fastifyTrpcPlugin`. The developer experience is excellent: you get end-to-end TypeScript type safety from client to server without code generation, while Fastify handles the HTTP layer with its characteristic performance and plugin ecosystem. The setup involves creating a tRPC router, wrapping it in Fastify using the adapter, and optionally configuring CORS, error handling, and middleware. Fastify's async-first design pairs naturally with tRPC's async procedure handlers. You can leverage Fastify's full plugin system for middleware, authentication, and other concerns while keeping your RPC logic cleanly separated in tRPC procedures. WebSocket support for real-time subscriptions works through Fastify's WebSocket plugin integration.
Best Use Cases
Quick Setup
npm install fastify @trpc/server @trpc/client zodimport Fastify from 'fastify';
import { initTRPC } from '@trpc/server';
import { fastifyTRPCPlugin } from '@trpc/server/adapters/fastify';
import { z } from 'zod';
const t = initTRPC.create();
const appRouter = t.router({
hello: t.procedure
.input(z.object({ name: z.string() }))
.query(({ input }) => `Hello, ${input.name}!`),
});
const fastify = Fastify();
await fastify.register(fastifyTRPCPlugin, {
prefix: '/trpc',
router: appRouter,
});
await fastify.listen({ port: 3000 });
export type AppRouter = typeof appRouter;Known Issues & Gotchas
Context initialization timing with async dependencies
Fix: Use tRPC's createContext with async operations; Fastify plugins load in order, so ensure auth/DB connections initialize before tRPC plugin
WebSocket subscriptions require additional Fastify WebSocket plugin configuration
Fix: Install @fastify/websocket separately and configure it before mounting tRPC adapter; check tRPC docs for ws transport setup
Error serialization differences between tRPC and Fastify error handlers
Fix: Define custom error formatting in tRPC's error handler option to ensure consistent error responses across your API
Alternatives
- •Express.js with tRPC - more ecosystem libraries but slower than Fastify
- •Hono with tRPC - lightweight alternative with similar performance, better for edge/Cloudflare Workers
- •Nitro (Nuxt server engine) with tRPC - opinionated Vue.js fullstack solution
Resources
Related Compatibility Guides
Explore more compatibility guides