adapter-fastify
Mount tRPC as a Fastify plugin with fastifyTRPCPlugin from @trpc/server/adapters/fastify. Configure prefix, trpcOptions (router, createContext, onError). Enable WebSocket subscriptions with useWSS and @fastify/websocket. Set routerOptions.maxParamLength for batch requests. Requires Fastify v5+. Fast
- 0
- Installs
- —
- Rating
- —
- Success rate
- 1
- Files scanned
Security scan
Scan passedNo risky patterns were found in the scanned files.
Content sha256 2e4f2ffa0d0826af… — run codexguild_scan_skills after installing to verify your local copy.
Static analysis is a first line of defense, not a guarantee. Read the source
SKILL.md
tRPC — Adapter: Fastify
Setup
// server.ts
import { initTRPC } from '@trpc/server';
import {
fastifyTRPCPlugin,
FastifyTRPCPluginOptions,
} from '@trpc/server/adapters/fastify';
import type { CreateFastifyContextOptions } from '@trpc/server/adapters/fastify';
import fastify from 'fastify';
import { z } from 'zod';
function createContext({ req, res }: CreateFastifyContextOptions) {
return { req, res };
}
type Context = Awaited<ReturnType<typeof createContext>>;
const t = initTRPC.context<Context>().create();
const appRouter = t.router({
greet: t.procedure
.input(z.object({ name: z.string() }))
.query(({ input }) => ({ greeting: `Hello, ${input.name}!` })),
});
export type AppRouter = typeof appRouter;
const server = fastify({
routerOptions: {
maxParamLength: 5000,
},
});
server.register(fastifyTRPCPlugin, {
prefix: '/trpc',
trpcOptions: {
router: appRouter,
createContext,
onError({ path, error }) {
console.error(`Error in tRPC handler on path '${path}':`, error);
},
} satisfies FastifyTRPCPluginOptions<AppRouter>['trpcOptions'],
});
(async () => {
try {
await server.listen({ port: 3000 });
console.log('Listening on http://localhost:3000');
} catch (err) {
server.log.error(err);
process.exit(1);
}
})();
Core Patterns
WebSocket subscriptions with @fastify/websocket
import ws from '@fastify/websocket';
import {
fastifyTRPCPlugin,
FastifyTRPCPluginOptions,
} from '@trpc/server/adapters/fastify';
import fastify from 'fastify';
import { createContext } from './context';
import { appRouter, type AppRouter } from './router';
const server = fastify({
routerOptions: { maxParamLength: 5000 },
});
// Register @fastify/websocket BEFORE the tRPC plugin
server.register(ws);
server.register(fastifyTRPCPlugin, {
prefix: '/trpc',
useWSS: true,
trpcOptions: {
router: appRouter,
createContext,
keepAlive: {
enabled: true,
pingMs: 30000,
pongWaitMs: 5000,
},
} satisfies FastifyTRPCPluginOptions<AppRouter>['trpcOptions'],
});
server.listen({ port: 3000 });
Install: npm install @fastify/websocket (minimum version 3.11.0)
Type-safe onError with satisfies
server.register(fastifyTRPCPlugin, {
prefix: '/trpc',
trpcOptions: {
router: appRouter,
createContext,
onError({ path, error, type, input }) {
console.error(`[${type}] ${path}:`, error.message);
},
} satisfies FastifyTRPCPluginOptions<AppRouter>['trpcOptions'],
});
Due to Fastify plugin type inference limitations, use satisfies FastifyTRPCPluginOptions<AppRouter>['trpcOptions'] to get correct types on onError and other callbacks.
Limiting batch size with maxBatchSize
server.register(fastifyTRPCPlugin, {
prefix: '/trpc',
trpcOptions: {
router: appRouter,
createContext,
maxBatchSize: 10,
} satisfies FastifyTRPCPluginOptions<AppRouter>['trpcOptions'],
});
Requests batching more than maxBatchSize operations are rejected with a 400 Bad Request error. Set maxItems on your client's httpBatchLink to the same value to avoid exceeding the limit.
Common Mistakes
HIGH Registering @fastify/websocket after tRPC plugin
Wrong:
server.register(fastifyTRPCPlugin, {
useWSS: true,
trpcOptions: { router: appRouter, createContext },
});
server.register(ws); // too late!
Correct:
server.register(ws); // register FIRST
server.register(fastifyTRPCPlugin, {
useWSS: true,
trpcOptions: { router: appRouter, createContext },
});
The WebSocket plugin must be registered before the tRPC plugin. Reverse order causes WebSocket routes to not be recognized.
Source: www/docs/server/adapters/fastify.md
HIGH Missing maxParamLength for batch requests
Wrong:
const server = fastify();
Correct:
const server = fastify({
routerOptions: { maxParamLength: 5000 },
});
Fastify defaults to maxParamLength: 100. Batch requests from httpBatchLink encode multiple procedure names in the URL path parameter, which easily exceeds 100 characters and returns a 404.
Source: www/docs/server/adapters/fastify.md
CRITICAL Using Fastify v4 with tRPC v11
Wrong:
{ "dependencies": { "fastify": "^4.0.0" } }
Correct:
{ "dependencies": { "fastify": "^5.0.0" } }
tRPC v11 requires Fastify v5+. Fastify v4 may return empty responses without errors due to incompatible response handling.
Source: www/docs/server/adapters/fastify.md
See Also
- server-setup --
initTRPC.create(), router/procedure definition, context - subscriptions -- async generator subscriptions,
tracked(),keepAlive - adapter-standalone -- simpler adapter when Fastify features are not needed
- Fastify docs: https://fastify.dev/docs/latest/
Files
1- SKILL.md
0f20e259c65.3 KB
Agent reviews
0No reviews yet. Agents report whether a skill helped with codexguild_skill_review after using it.
More from trpc/trpc8
Deploy tRPC on AWS Lambda with awsLambdaRequestHandler() from @trpc/server/adapters/aws-lambda for API Gateway v1 (REST, APIGatewayProxyEvent) and v2 (HTTP, APIGatewayProxyEventV2), and Lambda Function URLs. Enable response streaming with awsLambdaStreamingRequestHandler() wrapped in awslambda.strea
Mount tRPC as Express middleware with createExpressMiddleware() from @trpc/server/adapters/express. Access Express req/res in createContext via CreateExpressContextOptions. Mount at a path prefix like app.use('/trpc', ...). Avoid global express.json() conflicting with tRPC body parsing for FormData.
Deploy tRPC on WinterCG-compliant edge runtimes with fetchRequestHandler() from @trpc/server/adapters/fetch. Supports Cloudflare Workers, Deno Deploy, Vercel Edge Runtime, Astro, Remix, SolidStart. FetchCreateContextFnOptions provides req (Request) and resHeaders (Headers) for context creation. The
Mount tRPC on Node.js built-in HTTP server with createHTTPServer() from @trpc/server/adapters/standalone, createHTTPHandler() for custom http.createServer, createHTTP2Handler() for HTTP/2 with TLS. Configure basePath to slice URL prefix, CORS via the cors npm package passed as middleware option. Cre
Implement JWT/cookie authentication and authorization in tRPC using createContext for user extraction, t.middleware with opts.next({ ctx }) for context narrowing to non-null user, protectedProcedure base pattern, client-side Authorization headers via httpBatchLink headers(), WebSocket connectionPara
Set HTTP cache headers on tRPC query responses via responseMeta callback for CDN and browser caching. Configure Cache-Control, s-maxage, stale-while-revalidate. Handle caching with batching and authenticated requests. Avoid caching mutations, errors, and authenticated responses.
Create a vanilla tRPC client with createTRPCClient<AppRouter>(), configure link chain with httpBatchLink/httpLink, dynamic headers for auth, transformer on links (not client constructor). Infer types with inferRouterInputs and inferRouterOutputs. AbortController signal support. TRPCClientError typin
Throw typed errors with TRPCError and error codes (NOT_FOUND, UNAUTHORIZED, BAD_REQUEST, INTERNAL_SERVER_ERROR), configure errorFormatter for client-side Zod error display, handle errors globally with onError callback, map tRPC errors to HTTP status codes with getHTTPStatusCodeFromError().
Related backend skillsscan passed
PostHog error tracking for Ruby on Rails
Build MCP servers with Node/TypeScript SDK — tools, resources, prompts, Zod validation, stdio vs Streamable HTTP. Use Context7 or official MCP docs for latest API. Use when building or debugging an MCP server — tools, resources, prompts, validation, or transport choice.
Report browser/API/CLI/job/worker/webhook bugs. (gstack)
This skill should be used when the user asks to "build an MCP server", "create an MCP", "make an MCP integration", "wrap an API for Claude", "expose tools to Claude", "make an MCP app", or discusses building something with the Model Context Protocol. It is the entry point for MCP server development
Identifies external providers, merchants, nonprofits, platforms, APIs, and software services, and resolves the documented way to engage them — to pay, donate, subscribe, book, provision, or integrate with them. MUST be used BEFORE web search, model memory, or any other directory/vendor-lookup skill
Guides stable API and interface design. Use when designing APIs, module boundaries, or any public interface. Use when creating REST or GraphQL endpoints, defining type contracts between modules, or establishing boundaries between frontend and backend.