Usage with Fastify

Example app

The best way to start with the Fastify adapter is to take a look at the example application.

DescriptionLinks
  • Fastify server with WebSocket
  • Simple TRPC client in node

How to use tRPC with Fastify

Install dependencies

  1. yarn add @trpc/server fastify zod

Zod isn’t a required dependency, but it’s used in the sample router below.

Create the router

First of all you need a router to handle your queries, mutations and subscriptions.

A sample router is given below, save it in a file named router.ts.

router.ts

router.ts

  1. import * as trpc from '@trpc/server';
  2. import { z } from 'zod';
  3. type User = {
  4. id: string;
  5. name: string;
  6. bio?: string;
  7. };
  8. const users: Record<string, User> = {};
  9. export const appRouter = trpc
  10. .router()
  11. .query('getUserById', {
  12. input: z.string(),
  13. async resolve({ input }) {
  14. return users[input]; // input type is string
  15. },
  16. })
  17. .mutation('createUser', {
  18. // validate input with Zod
  19. input: z.object({
  20. name: z.string().min(3),
  21. bio: z.string().max(142).optional(),
  22. }),
  23. async resolve({ input }) {
  24. const id = Date.now().toString();
  25. const user: User = { id, ...input };
  26. users[user.id] = user;
  27. return user;
  28. },
  29. });
  30. // export type definition of API
  31. export type AppRouter = typeof appRouter;

If your router file starts getting too big, split your router into several subrouters each implemented in its own file. Then merge them into a single root appRouter.

Create the context

Then you need a context that will be created for each request.

A sample context is given below, save it in a file named context.ts:

context.ts

context.ts

  1. import { inferAsyncReturnType } from '@trpc/server';
  2. import { CreateFastifyContextOptions } from '@trpc/server/adapters/fastify';
  3. export function createContext({ req, res }: CreateFastifyContextOptions) {
  4. const user = { name: req.headers.username ?? 'anonymous' };
  5. return { req, res, user };
  6. }
  7. export type Context = inferAsyncReturnType<typeof createContext>;

Create Fastify server

tRPC includes an adapter for Fastify out of the box. This adapter lets you convert your tRPC router into an Fastify plugin. In order to prevent errors during large batch requests, make sure to set the maxParamLength Fastify option to a suitable value, as shown.

server.ts

  1. import { fastifyTRPCPlugin } from '@trpc/server/adapters/fastify';
  2. import fastify from 'fastify';
  3. import { createContext } from './context';
  4. import { appRouter } from './router';
  5. const server = fastify({
  6. maxParamLength: 5000,
  7. });
  8. server.register(fastifyTRPCPlugin, {
  9. prefix: '/trpc',
  10. trpcOptions: { router: appRouter, createContext },
  11. });
  12. (async () => {
  13. try {
  14. await server.listen(3000);
  15. } catch (err) {
  16. server.log.error(err);
  17. process.exit(1);
  18. }
  19. })();

Your endpoints are now available via HTTP!

EndpointHTTP URI
getUserGET http://localhost:3000/trpc/getUserById?input=INPUT

where INPUT is a URI-encoded JSON string.
createUserPOST http://localhost:3000/trpc/createUser

with req.body of type User

How to enable subscriptions (WebSocket)

The Fastify adapter supports subscriptions via the @fastify/websocket plugin. All you have to do in addition to the above steps is install the dependency, add some subscriptions to your router and activate the useWSS option in the plugin. The minimum Fastify version required for @fastify/websocket is 3.11.0.

Install dependencies

  1. yarn add @fastify/websocket

Import and register @fastify/websocket

  1. import ws from '@fastify/websocket';
  2. server.register(ws);

Add some subscriptions

Edit the router.ts file created in the previous steps and add the following code:

router.ts

  1. export const appRouter = trpc
  2. .router()
  3. // .query(...)
  4. // .mutation(...)
  5. .subscription('randomNumber', {
  6. resolve() {
  7. return new Subscription<{ randomNumber: number }>((emit) => {
  8. const timer = setInterval(() => {
  9. emit.data({ randomNumber: Math.random() });
  10. }, 1000);
  11. return () => {
  12. clearInterval(timer);
  13. };
  14. });
  15. },
  16. });

Activate the useWSS option

server.ts

  1. server.register(fastifyTRPCPlugin, {
  2. useWSS: true,
  3. // ...
  4. });

It’s alright, you can subscribe to the topic randomNumber and you should receive a random number every second 🚀.

Fastify plugin options

nametypeoptionaldefaultdescription
prefixstringtrue“/trpc”
useWSSbooleantruefalse
trpcOptionsNodeHTTPHandlerOptionsfalsen/a