Usage with Fastify
Example app
The best way to start with the Fastify adapter is to take a look at the example application.
| Description | Links | 
|---|---|
| 
 | 
How to use tRPC with Fastify
Install dependencies
bash
bash
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.tsts
router.tsts
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.tsts
context.tsts
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.tsts
server.tsts
Your endpoints are now available via HTTP!
| Endpoint | HTTP URI | 
|---|---|
| getUser | GET http://localhost:3000/trpc/getUserById?input=INPUTwhere INPUTis a URI-encoded JSON string. | 
| createUser | POST http://localhost:3000/trpc/createUserwith req.bodyof typeUser | 
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
bash
bash
Import and register @fastify/websocket
ts
ts
Add some subscriptions
Edit the router.ts file created in the previous steps and add the following code:
router.tsts
router.tsts
Activate the useWSS option
server.tsts
server.tsts
It's alright, you can subscribe to the topic randomNumber and you should receive a random number every second 🚀.
Fastify plugin options
| name | type | optional | default | description | 
|---|---|---|---|---|
| prefix | string | true | "/trpc" | |
| useWSS | boolean | true | false | |
| trpcOptions | NodeHTTPHandlerOptions | false | n/a |