tRPC with Fastify and Express: Adapters and Limits
On this page
Why use a framework adapter
The standalone adapter from Day 2 is fine for a demo. A production server also needs a health check for the load balancer, webhook endpoints that other services call with their own payloads, maybe static files, plus logging, CORS and security headers. Fastify and Express already do all of that well. tRPC plugs into them as one route prefix, usually /trpc.
Mount tRPC in Fastify
Fastify 5 is fast and has good TypeScript support. tRPC provides a plugin:
// src/server.ts
import Fastify from 'fastify';
import { fastifyTRPCPlugin, type FastifyTRPCPluginOptions } from '@trpc/server/adapters/fastify';
import { appRouter, type AppRouter } from './routers/_app';
import { createContext } from './context';
const app = Fastify({ logger: true, routerOptions: { maxParamLength: 5000 } });
await app.register(fastifyTRPCPlugin, {
prefix: '/trpc',
trpcOptions: {
router: appRouter,
createContext: ({ req }) => createContext({ headers: req.headers }),
onError({ path, error }) {
if (error.code === 'INTERNAL_SERVER_ERROR') app.log.error({ path, err: error }, 'tRPC error');
},
} satisfies FastifyTRPCPluginOptions<AppRouter>['trpcOptions'],
});
app.get('/healthz', async () => ({ ok: true }));
await app.listen({ port: 3000 });Two details are worth knowing:
maxParamLength. A batched call puts every procedure name in the URL path, like/trpc/task.list,task.byId,me. Fastify's default limit for a path parameter is 100 characters. In a test, a batch of twelve calls with a 205-character path failed with414 URI Too Longuntil the limit was raised. In Fastify 5 this setting belongs underrouterOptions; passing it at the top level still works but logs a deprecation warning, and it will stop working in Fastify 6.satisfies. Writing the options withsatisfies ...keeps full type checking ofcreateContextandonErroragainst your router.
The client's URL now includes the prefix: httpBatchLink({ url: 'http://localhost:3000/trpc' }).
Mount tRPC in Express
Express 5 is the current major version. The adapter is a middleware you mount on a path:
import express from 'express';
import { createExpressMiddleware } from '@trpc/server/adapters/express';
const app = express();
app.post('/webhooks/stripe', express.raw({ type: 'application/json' }), handleStripeWebhook);
app.use('/trpc', createExpressMiddleware({
router: appRouter,
createContext: ({ req }) => createContext({ headers: req.headers }),
}));
app.listen(3000);tRPC reads the request body itself, so you don't need express.json() for it. If a global express.json() runs first, tRPC uses the body it already parsed, which works, but then Express's size limit applies instead of tRPC's own (more on limits below).
The webhook route shows why you want a framework underneath. Stripe signs the raw body, so that route needs express.raw and its own handler. It isn't a tRPC procedure, because the caller isn't your TypeScript client.
The same router, context and client worked unchanged on all three servers in testing: standalone, Fastify and Express, including subscriptions. Only the URL changed.
Set CORS deliberately
If your frontend and API share an origin, for example app.example.com/trpc, you don't need CORS at all. That's the simplest setup and the one to aim for, often with a reverse proxy or a BFF in front.
If they're on different origins, the browser sends a preflight OPTIONS request before every tRPC POST (and before any GET that carries an Authorization header). Allow only your own frontend:
import cors from '@fastify/cors';
await app.register(cors, {
origin: ['https://app.example.com'],
credentials: true, // only if you use cookies
});Never combine credentials: true with a wildcard or a reflected origin. That lets any website make signed-in calls on your users' behalf.
Limit request sizes and batch sizes
Two limits stop a single caller from tying up your server.
// server: reject batches with more than 10 calls with a 400
createExpressMiddleware({ router: appRouter, createContext, maxBatchSize: 10 });
// client: never send more than 10 calls per request
httpBatchLink({ url: '/trpc', maxItems: 10 });Testing a batch of four calls against maxBatchSize: 3 returned 400 Batch call exceeds maximum size. Set the client's maxItems to the same value or lower, so a busy page splits its calls into several requests instead of failing. In the same test, five parallel calls with maxItems: 3 all succeeded.
Body size limits come from the adapter. The standalone and Express adapters accept a maxBodySize in bytes: with maxBodySize: 1000, a 5 KB body was rejected with 413 PAYLOAD_TOO_LARGE. Fastify uses its own bodyLimit setting, which defaults to 1 MiB.
Run on any Fetch runtime
Cloudflare Workers, Deno, Bun and Next.js route handlers all speak the standard Request and Response objects. The Fetch adapter covers them:
import { fetchRequestHandler } from '@trpc/server/adapters/fetch';
export default {
fetch: (req: Request) =>
fetchRequestHandler({ endpoint: '/trpc', req, router: appRouter, createContext: () => ({ user: null }) }),
};A test calling it with new Request('http://x/trpc/health') returned 200 {"result":{"data":"ok"}}. Hono, which runs on all of those runtimes, has a community middleware built on this adapter.
/healthz outside tRPC. Load balancers and Kubernetes probes want a plain URL that returns 200 without any tRPC encoding or context work.Check yourself
The batched procedure names form a long URL path segment, which exceeds Fastify's default 100-character parameter limit and returns 414. Raise maxParamLength under routerOptions.
No. Stripe signs the exact raw bytes of the body, so the route needs raw body parsing and its own signature check, and the caller isn't your typed client anyway. Make it a normal framework route next to tRPC, which is one of the main reasons to mount tRPC inside Fastify or Express.
Set maxItems to 10 or lower on the batch link. Then a busy page that makes many calls at once is split by the client into several requests, instead of one oversized batch being rejected with 400 Batch call exceeds maximum size. Keep the two numbers in one shared constant so they can't drift.
Allow exactly https://app.example.com as the origin, with credentials: true, and nothing else. Never combine credentials with a wildcard or an origin reflected from the request, because that lets any website make signed-in calls for your users. Serving the API from the app's own origin avoids CORS altogether and is simpler still.
tRPC uses a body that Express has already parsed, so its own size check never sees the raw stream, and Express's own limit (100 KB by default) applies instead. Either remove express.json() from the tRPC path or set the limit on express.json() itself.