@trpc/server 11.22.2-canary.9.85bcf328a → 11.23.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +0 -8
- package/dist/adapters/aws-lambda/index.cjs +1 -1
- package/dist/adapters/aws-lambda/index.d.cts.map +1 -1
- package/dist/adapters/aws-lambda/index.d.mts.map +1 -1
- package/dist/adapters/aws-lambda/index.mjs +1 -1
- package/dist/adapters/aws-lambda/index.mjs.map +1 -1
- package/dist/adapters/express.cjs +1 -1
- package/dist/adapters/express.mjs +1 -1
- package/dist/adapters/express.mjs.map +1 -1
- package/dist/adapters/fastify/index.cjs +3 -3
- package/dist/adapters/fastify/index.mjs +3 -3
- package/dist/adapters/fetch/index.cjs +1 -1
- package/dist/adapters/fetch/index.mjs +1 -1
- package/dist/adapters/next-app-dir.mjs.map +1 -1
- package/dist/adapters/next.cjs +1 -1
- package/dist/adapters/next.mjs +1 -1
- package/dist/adapters/next.mjs.map +1 -1
- package/dist/adapters/node-http/index.cjs +1 -1
- package/dist/adapters/node-http/index.mjs +1 -1
- package/dist/adapters/standalone.cjs +9 -3
- package/dist/adapters/standalone.d.cts +0 -1
- package/dist/adapters/standalone.d.cts.map +1 -1
- package/dist/adapters/standalone.d.mts +0 -1
- package/dist/adapters/standalone.d.mts.map +1 -1
- package/dist/adapters/standalone.mjs +9 -3
- package/dist/adapters/standalone.mjs.map +1 -1
- package/dist/adapters/ws.cjs +1 -1
- package/dist/adapters/ws.mjs +1 -1
- package/dist/asyncGeneratorDelegate-FcEJT04i.mjs.map +1 -1
- package/dist/codes-C9N0z0an.mjs.map +1 -1
- package/dist/getErrorShape-zlj81BiC.mjs.map +1 -1
- package/dist/http.cjs +1 -1
- package/dist/http.mjs +1 -1
- package/dist/initTRPC-RMeQIy9H.mjs.map +1 -1
- package/dist/{node-http-B5jkpWn7.mjs → node-http-ChhZEv1k.mjs} +2 -2
- package/dist/node-http-ChhZEv1k.mjs.map +1 -0
- package/dist/{node-http-BZ0HlzkC.cjs → node-http-X8RiQEuH.cjs} +1 -1
- package/dist/parseTRPCMessage-CJ4DJVBp.mjs.map +1 -1
- package/dist/{resolveResponse-b9D_SrLs.cjs → resolveResponse-CoGjFxK0.cjs} +8 -4
- package/dist/{resolveResponse-DH5L33sC.mjs → resolveResponse-DksrxZ2k.mjs} +9 -5
- package/dist/resolveResponse-DksrxZ2k.mjs.map +1 -0
- package/dist/unstable-core-do-not-import-B8epiErP.d.cts.map +1 -1
- package/dist/unstable-core-do-not-import-Dbo98mkh.d.mts.map +1 -1
- package/dist/unstable-core-do-not-import.cjs +1 -1
- package/dist/unstable-core-do-not-import.mjs +1 -1
- package/dist/unstable-core-do-not-import.mjs.map +1 -1
- package/dist/{ws-83TNWW-W.cjs → ws-7qWW7Uec.cjs} +2 -2
- package/dist/{ws-DJ2SSChC.mjs → ws-BYfo-HED.mjs} +3 -3
- package/dist/ws-BYfo-HED.mjs.map +1 -0
- package/package.json +9 -12
- package/skills/adapter-aws-lambda/SKILL.md +152 -134
- package/skills/adapter-express/SKILL.md +127 -113
- package/skills/adapter-fastify/SKILL.md +228 -136
- package/skills/adapter-fetch/SKILL.md +388 -111
- package/skills/adapter-standalone/SKILL.md +184 -94
- package/skills/auth/SKILL.md +327 -202
- package/skills/auth/references/client-cors.md +29 -0
- package/skills/caching/SKILL.md +58 -148
- package/skills/error-handling/SKILL.md +280 -174
- package/skills/middlewares/SKILL.md +320 -121
- package/skills/non-json-content-types/SKILL.md +149 -168
- package/skills/server-setup/SKILL.md +355 -253
- package/skills/server-setup/references/server-context.md +219 -0
- package/skills/server-setup/references/server-merging-routers.md +141 -0
- package/skills/server-setup/references/server-metadata.md +105 -0
- package/skills/server-setup/references/server-procedures.md +172 -0
- package/skills/server-setup/references/server-routers.md +123 -0
- package/skills/server-side-calls/SKILL.md +247 -152
- package/skills/service-oriented-architecture/SKILL.md +81 -177
- package/skills/subscriptions/SKILL.md +341 -297
- package/skills/subscriptions/references/client-links-httpSubscriptionLink.md +404 -0
- package/skills/subscriptions/references/client-links-wsLink.md +122 -0
- package/skills/subscriptions/references/server-websockets.md +297 -0
- package/skills/trpc-router/SKILL.md +156 -86
- package/skills/validators/SKILL.md +384 -128
- package/src/adapters/aws-lambda/getPlanner.ts +4 -3
- package/src/adapters/aws-lambda/index.ts +2 -1
- package/src/adapters/express.ts +1 -1
- package/src/adapters/next-app-dir/nextAppDirCaller.ts +4 -4
- package/src/adapters/next-app-dir/rethrowNextErrors.ts +1 -1
- package/src/adapters/next.ts +1 -1
- package/src/adapters/node-http/incomingMessageToRequest.ts +1 -1
- package/src/adapters/node-http/nodeHTTPRequestHandler.ts +1 -1
- package/src/adapters/node-http/types.ts +1 -1
- package/src/adapters/node-http/writeResponse.ts +1 -1
- package/src/adapters/standalone.ts +12 -6
- package/src/adapters/ws.ts +5 -5
- package/src/unstable-core-do-not-import/clientish/inferrable.ts +4 -1
- package/src/unstable-core-do-not-import/clientish/serialize.ts +4 -4
- package/src/unstable-core-do-not-import/error/TRPCError.ts +3 -3
- package/src/unstable-core-do-not-import/http/formDataToObject.ts +1 -1
- package/src/unstable-core-do-not-import/http/getHTTPStatusCode.ts +1 -1
- package/src/unstable-core-do-not-import/http/resolveResponse.ts +13 -2
- package/src/unstable-core-do-not-import/procedure.ts +5 -2
- package/src/unstable-core-do-not-import/procedureBuilder.ts +3 -2
- package/src/unstable-core-do-not-import/rootConfig.ts +2 -2
- package/src/unstable-core-do-not-import/router.ts +5 -2
- package/src/unstable-core-do-not-import/rpc/envelopes.ts +3 -2
- package/src/unstable-core-do-not-import/stream/jsonl.ts +2 -1
- package/src/unstable-core-do-not-import/stream/sse.types.ts +1 -1
- package/src/unstable-core-do-not-import/stream/utils/asyncIterable.ts +1 -1
- package/src/unstable-core-do-not-import/stream/utils/createDeferred.ts +1 -1
- package/src/unstable-core-do-not-import/stream/utils/disposable.ts +6 -6
- package/src/unstable-core-do-not-import/stream/utils/mergeAsyncIterables.ts +2 -2
- package/src/unstable-core-do-not-import/stream/utils/withPing.ts +3 -1
- package/src/unstable-core-do-not-import/transformer.ts +4 -1
- package/src/unstable-core-do-not-import/types.ts +3 -2
- package/src/unstable-core-do-not-import/utils.ts +1 -1
- package/src/vendor/standard-schema-v1/spec.ts +2 -2
- package/src/vendor/unpromise/unpromise.ts +1 -1
- package/bin/intent.js +0 -20
- package/dist/node-http-B5jkpWn7.mjs.map +0 -1
- package/dist/resolveResponse-DH5L33sC.mjs.map +0 -1
- package/dist/ws-DJ2SSChC.mjs.map +0 -1
|
@@ -1,51 +1,156 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: adapter-fastify
|
|
3
|
-
description:
|
|
4
|
-
Mount tRPC as a Fastify plugin with fastifyTRPCPlugin from
|
|
5
|
-
@trpc/server/adapters/fastify. Configure prefix, trpcOptions (router,
|
|
6
|
-
createContext, onError). Enable WebSocket subscriptions with useWSS and
|
|
7
|
-
@fastify/websocket. Set routerOptions.maxParamLength for batch requests.
|
|
8
|
-
Requires Fastify v5+. FastifyTRPCPluginOptions for type-safe onError.
|
|
9
|
-
CreateFastifyContextOptions provides req, res.
|
|
10
|
-
type: core
|
|
11
|
-
library: trpc
|
|
12
|
-
library_version: '11.16.0'
|
|
3
|
+
description: 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+. FastifyTRPCPluginOptions for type-safe onError. CreateFastifyContextOptions provides req, res. Register @fastify/websocket before the tRPC plugin.
|
|
13
4
|
requires:
|
|
14
5
|
- server-setup
|
|
15
6
|
sources:
|
|
16
|
-
- www/docs/server/adapters/fastify.md
|
|
17
|
-
-
|
|
7
|
+
- www/v11/docs/server/adapters/fastify.md
|
|
8
|
+
- www/v11/docs/server/adapters.md
|
|
9
|
+
metadata:
|
|
10
|
+
type: core
|
|
11
|
+
library: trpc
|
|
12
|
+
library_version: 11.23.0
|
|
18
13
|
---
|
|
19
14
|
|
|
20
|
-
|
|
15
|
+
<!-- Generated from www/v11/docs/server/adapters/fastify.md by www/build/skills.ts. Edit the docs instead. -->
|
|
16
|
+
|
|
17
|
+
# Fastify Adapter
|
|
18
|
+
|
|
19
|
+
From https://trpc.io/docs/server/adapters/fastify
|
|
20
|
+
|
|
21
|
+
## Example app
|
|
22
|
+
|
|
23
|
+
The best way to start with the Fastify adapter is to take a look at the example application.
|
|
24
|
+
|
|
25
|
+
<table>
|
|
26
|
+
<thead>
|
|
27
|
+
<tr>
|
|
28
|
+
<th>Description</th>
|
|
29
|
+
<th>Links</th>
|
|
30
|
+
</tr>
|
|
31
|
+
</thead>
|
|
32
|
+
<tbody>
|
|
33
|
+
<tr>
|
|
34
|
+
<td>
|
|
35
|
+
<ul>
|
|
36
|
+
<li>Fastify server with WebSocket</li>
|
|
37
|
+
<li>Simple tRPC client in node</li>
|
|
38
|
+
</ul>
|
|
39
|
+
</td>
|
|
40
|
+
<td>
|
|
41
|
+
<ul>
|
|
42
|
+
<li><a href="https://codesandbox.io/s/github/trpc/trpc/tree/main/examples/fastify-server">CodeSandbox</a></li>
|
|
43
|
+
<li><a href="https://github.com/trpc/trpc/tree/main/examples/fastify-server">Source</a></li>
|
|
44
|
+
</ul>
|
|
45
|
+
</td>
|
|
46
|
+
</tr>
|
|
47
|
+
</tbody>
|
|
48
|
+
</table>
|
|
49
|
+
|
|
50
|
+
## How to use tRPC with Fastify
|
|
51
|
+
|
|
52
|
+
### Install dependencies
|
|
53
|
+
|
|
54
|
+
```bash
|
|
55
|
+
yarn add @trpc/server fastify zod
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
> ⚠️ **Fastify version requirement**
|
|
59
|
+
>
|
|
60
|
+
> The tRPC v11 Fastify adapter requires **Fastify v5+**.
|
|
61
|
+
> Using Fastify v4 may cause requests to return empty responses without errors.
|
|
62
|
+
|
|
63
|
+
> [Zod](https://github.com/colinhacks/zod) isn't a required dependency, but it's used in the sample router below.
|
|
64
|
+
|
|
65
|
+
### Create the router
|
|
21
66
|
|
|
22
|
-
|
|
67
|
+
First of all you need a [router](https://trpc.io/docs/server/routers) to handle your queries, mutations and subscriptions.
|
|
23
68
|
|
|
24
|
-
|
|
25
|
-
|
|
69
|
+
A sample router is given below, save it in a file named `router.ts`.
|
|
70
|
+
|
|
71
|
+
<details>
|
|
72
|
+
<summary>router.ts</summary>
|
|
73
|
+
|
|
74
|
+
```ts no-check title="router.ts"
|
|
26
75
|
import { initTRPC } from '@trpc/server';
|
|
27
|
-
import {
|
|
28
|
-
fastifyTRPCPlugin,
|
|
29
|
-
FastifyTRPCPluginOptions,
|
|
30
|
-
} from '@trpc/server/adapters/fastify';
|
|
31
|
-
import type { CreateFastifyContextOptions } from '@trpc/server/adapters/fastify';
|
|
32
|
-
import fastify from 'fastify';
|
|
33
76
|
import { z } from 'zod';
|
|
34
77
|
|
|
35
|
-
|
|
36
|
-
|
|
78
|
+
type User = {
|
|
79
|
+
id: string;
|
|
80
|
+
name: string;
|
|
81
|
+
bio?: string;
|
|
82
|
+
};
|
|
83
|
+
|
|
84
|
+
const users: Record<string, User> = {};
|
|
85
|
+
|
|
86
|
+
export const t = initTRPC.create();
|
|
87
|
+
|
|
88
|
+
export const appRouter = t.router({
|
|
89
|
+
getUserById: t.procedure.input(z.string()).query((opts) => {
|
|
90
|
+
return users[opts.input]; // input type is string
|
|
91
|
+
}),
|
|
92
|
+
createUser: t.procedure
|
|
93
|
+
.input(
|
|
94
|
+
z.object({
|
|
95
|
+
name: z.string().min(3),
|
|
96
|
+
bio: z.string().max(142).optional(),
|
|
97
|
+
}),
|
|
98
|
+
)
|
|
99
|
+
.mutation((opts) => {
|
|
100
|
+
const id = Date.now().toString();
|
|
101
|
+
const user: User = { id, ...opts.input };
|
|
102
|
+
users[user.id] = user;
|
|
103
|
+
return user;
|
|
104
|
+
}),
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
// export type definition of API
|
|
108
|
+
export type AppRouter = typeof appRouter;
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
</details>
|
|
112
|
+
|
|
113
|
+
If your router file starts getting too big, split your router into several subrouters each implemented in its own file. Then [merge them](https://trpc.io/docs/server/merging-routers) into a single root `appRouter`.
|
|
114
|
+
|
|
115
|
+
### Create the context
|
|
116
|
+
|
|
117
|
+
Then you need a [context](https://trpc.io/docs/server/context) that will be created for each request.
|
|
118
|
+
|
|
119
|
+
A sample context is given below, save it in a file named `context.ts`:
|
|
120
|
+
|
|
121
|
+
<details>
|
|
122
|
+
<summary>context.ts</summary>
|
|
123
|
+
|
|
124
|
+
```ts no-check title="context.ts"
|
|
125
|
+
import { CreateFastifyContextOptions } from '@trpc/server/adapters/fastify';
|
|
126
|
+
|
|
127
|
+
export function createContext({ req, res }: CreateFastifyContextOptions) {
|
|
128
|
+
const user = { name: req.headers.username ?? 'anonymous' };
|
|
129
|
+
|
|
130
|
+
return { req, res, user };
|
|
37
131
|
}
|
|
38
|
-
type Context = Awaited<ReturnType<typeof createContext>>;
|
|
39
132
|
|
|
40
|
-
|
|
133
|
+
export type Context = Awaited<ReturnType<typeof createContext>>;
|
|
134
|
+
```
|
|
41
135
|
|
|
42
|
-
|
|
43
|
-
greet: t.procedure
|
|
44
|
-
.input(z.object({ name: z.string() }))
|
|
45
|
-
.query(({ input }) => ({ greeting: `Hello, ${input.name}!` })),
|
|
46
|
-
});
|
|
136
|
+
</details>
|
|
47
137
|
|
|
48
|
-
|
|
138
|
+
### Create Fastify server
|
|
139
|
+
|
|
140
|
+
tRPC includes an adapter for [Fastify](https://www.fastify.io/) out of the box. This adapter lets you convert your tRPC router into a [Fastify plugin](https://www.fastify.io/docs/latest/Reference/Plugins/). In order to prevent errors during large batch requests, make sure to set the `maxParamLength` Fastify option to a suitable value, as shown.
|
|
141
|
+
|
|
142
|
+
> [!TIP]
|
|
143
|
+
> Due to limitations in Fastify's plugin system and type inference, there might be some issues getting for example `onError` typed correctly. You can add a `satisfies FastifyTRPCPluginOptions<AppRouter>['trpcOptions']` to help TypeScript out and get the correct types.
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
```ts no-check title="server.ts"
|
|
147
|
+
import {
|
|
148
|
+
fastifyTRPCPlugin,
|
|
149
|
+
FastifyTRPCPluginOptions,
|
|
150
|
+
} from '@trpc/server/adapters/fastify';
|
|
151
|
+
import fastify from 'fastify';
|
|
152
|
+
import { createContext } from './context';
|
|
153
|
+
import { appRouter, type AppRouter } from './router';
|
|
49
154
|
|
|
50
155
|
const server = fastify({
|
|
51
156
|
routerOptions: {
|
|
@@ -59,6 +164,7 @@ server.register(fastifyTRPCPlugin, {
|
|
|
59
164
|
router: appRouter,
|
|
60
165
|
createContext,
|
|
61
166
|
onError({ path, error }) {
|
|
167
|
+
// report to error monitoring
|
|
62
168
|
console.error(`Error in tRPC handler on path '${path}':`, error);
|
|
63
169
|
},
|
|
64
170
|
} satisfies FastifyTRPCPluginOptions<AppRouter>['trpcOptions'],
|
|
@@ -67,7 +173,6 @@ server.register(fastifyTRPCPlugin, {
|
|
|
67
173
|
(async () => {
|
|
68
174
|
try {
|
|
69
175
|
await server.listen({ port: 3000 });
|
|
70
|
-
console.log('Listening on http://localhost:3000');
|
|
71
176
|
} catch (err) {
|
|
72
177
|
server.log.error(err);
|
|
73
178
|
process.exit(1);
|
|
@@ -75,12 +180,53 @@ server.register(fastifyTRPCPlugin, {
|
|
|
75
180
|
})();
|
|
76
181
|
```
|
|
77
182
|
|
|
78
|
-
|
|
183
|
+
Your endpoints are now available via HTTP!
|
|
184
|
+
|
|
185
|
+
| Endpoint | HTTP URI |
|
|
186
|
+
| ------------- | -------------------------------------------------------------------------------------------------------------- |
|
|
187
|
+
| `getUserById` | `GET http://localhost:3000/trpc/getUserById?input=INPUT` <br/><br/>where `INPUT` is a URI-encoded JSON string. |
|
|
188
|
+
| `createUser` | `POST http://localhost:3000/trpc/createUser` <br/><br/>with `req.body` of type `User` |
|
|
189
|
+
|
|
190
|
+
## Enable WebSockets
|
|
191
|
+
|
|
192
|
+
The Fastify adapter supports [WebSockets](https://trpc.io/docs/server/websockets) via the [@fastify/websocket](https://www.npmjs.com/package/@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](https://trpc.io/docs/server/adapters/fastify#fastify-plugin-options) in the plugin. The minimum `@fastify/websocket` version required is `3.11.0`.
|
|
193
|
+
|
|
194
|
+
### Install dependencies
|
|
195
|
+
|
|
196
|
+
```bash
|
|
197
|
+
yarn add @fastify/websocket
|
|
198
|
+
```
|
|
79
199
|
|
|
80
|
-
###
|
|
200
|
+
### Import and register `@fastify/websocket`
|
|
81
201
|
|
|
82
|
-
```ts
|
|
202
|
+
```ts no-check
|
|
83
203
|
import ws from '@fastify/websocket';
|
|
204
|
+
|
|
205
|
+
server.register(ws);
|
|
206
|
+
```
|
|
207
|
+
|
|
208
|
+
### Add some subscriptions
|
|
209
|
+
|
|
210
|
+
Edit the `router.ts` file created in the previous steps and add the following code:
|
|
211
|
+
|
|
212
|
+
```ts no-check title="router.ts"
|
|
213
|
+
import { initTRPC } from '@trpc/server';
|
|
214
|
+
|
|
215
|
+
const t = initTRPC.create();
|
|
216
|
+
|
|
217
|
+
export const appRouter = t.router({
|
|
218
|
+
randomNumber: t.procedure.subscription(async function* () {
|
|
219
|
+
while (true) {
|
|
220
|
+
yield { randomNumber: Math.random() };
|
|
221
|
+
await new Promise((resolve) => setTimeout(resolve, 1000));
|
|
222
|
+
}
|
|
223
|
+
}),
|
|
224
|
+
});
|
|
225
|
+
```
|
|
226
|
+
|
|
227
|
+
### Activate the `useWSS` option
|
|
228
|
+
|
|
229
|
+
```ts no-check title="server.ts"
|
|
84
230
|
import {
|
|
85
231
|
fastifyTRPCPlugin,
|
|
86
232
|
FastifyTRPCPluginOptions,
|
|
@@ -89,133 +235,79 @@ import fastify from 'fastify';
|
|
|
89
235
|
import { createContext } from './context';
|
|
90
236
|
import { appRouter, type AppRouter } from './router';
|
|
91
237
|
|
|
92
|
-
const server = fastify(
|
|
93
|
-
routerOptions: { maxParamLength: 5000 },
|
|
94
|
-
});
|
|
95
|
-
|
|
96
|
-
// Register @fastify/websocket BEFORE the tRPC plugin
|
|
97
|
-
server.register(ws);
|
|
238
|
+
const server = fastify();
|
|
98
239
|
|
|
99
240
|
server.register(fastifyTRPCPlugin, {
|
|
100
|
-
prefix: '/trpc',
|
|
101
241
|
useWSS: true,
|
|
102
242
|
trpcOptions: {
|
|
103
243
|
router: appRouter,
|
|
104
244
|
createContext,
|
|
245
|
+
// Enable heartbeat messages to keep connection open (disabled by default)
|
|
105
246
|
keepAlive: {
|
|
106
247
|
enabled: true,
|
|
248
|
+
// server ping message interval in milliseconds
|
|
107
249
|
pingMs: 30000,
|
|
250
|
+
// connection is terminated if pong message is not received in this many milliseconds
|
|
108
251
|
pongWaitMs: 5000,
|
|
109
252
|
},
|
|
110
|
-
}
|
|
111
|
-
});
|
|
112
|
-
|
|
113
|
-
server.listen({ port: 3000 });
|
|
114
|
-
```
|
|
115
|
-
|
|
116
|
-
Install: `npm install @fastify/websocket` (minimum version 3.11.0)
|
|
117
|
-
|
|
118
|
-
### Type-safe onError with satisfies
|
|
119
|
-
|
|
120
|
-
```ts
|
|
121
|
-
server.register(fastifyTRPCPlugin, {
|
|
122
|
-
prefix: '/trpc',
|
|
123
|
-
trpcOptions: {
|
|
124
|
-
router: appRouter,
|
|
125
|
-
createContext,
|
|
126
|
-
onError({ path, error, type, input }) {
|
|
127
|
-
console.error(`[${type}] ${path}:`, error.message);
|
|
128
|
-
},
|
|
129
|
-
} satisfies FastifyTRPCPluginOptions<AppRouter>['trpcOptions'],
|
|
130
|
-
});
|
|
131
|
-
```
|
|
132
|
-
|
|
133
|
-
Due to Fastify plugin type inference limitations, use `satisfies FastifyTRPCPluginOptions<AppRouter>['trpcOptions']` to get correct types on `onError` and other callbacks.
|
|
134
|
-
|
|
135
|
-
### Limiting batch size with maxBatchSize
|
|
136
|
-
|
|
137
|
-
```ts
|
|
138
|
-
server.register(fastifyTRPCPlugin, {
|
|
139
|
-
prefix: '/trpc',
|
|
140
|
-
trpcOptions: {
|
|
141
|
-
router: appRouter,
|
|
142
|
-
createContext,
|
|
143
|
-
maxBatchSize: 10,
|
|
144
|
-
} satisfies FastifyTRPCPluginOptions<AppRouter>['trpcOptions'],
|
|
145
|
-
});
|
|
146
|
-
```
|
|
147
|
-
|
|
148
|
-
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.
|
|
149
|
-
|
|
150
|
-
## Common Mistakes
|
|
151
|
-
|
|
152
|
-
### HIGH Registering @fastify/websocket after tRPC plugin
|
|
153
|
-
|
|
154
|
-
Wrong:
|
|
155
|
-
|
|
156
|
-
```ts
|
|
157
|
-
server.register(fastifyTRPCPlugin, {
|
|
158
|
-
useWSS: true,
|
|
159
|
-
trpcOptions: { router: appRouter, createContext },
|
|
160
|
-
});
|
|
161
|
-
server.register(ws); // too late!
|
|
162
|
-
```
|
|
163
|
-
|
|
164
|
-
Correct:
|
|
165
|
-
|
|
166
|
-
```ts
|
|
167
|
-
server.register(ws); // register FIRST
|
|
168
|
-
server.register(fastifyTRPCPlugin, {
|
|
169
|
-
useWSS: true,
|
|
170
|
-
trpcOptions: { router: appRouter, createContext },
|
|
253
|
+
},
|
|
171
254
|
});
|
|
172
255
|
```
|
|
173
256
|
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
Source: www/docs/server/adapters/fastify.md
|
|
257
|
+
You can now subscribe to the `randomNumber` topic and should receive a random number every second 🚀.
|
|
177
258
|
|
|
178
|
-
|
|
259
|
+
## Fastify plugin options
|
|
179
260
|
|
|
180
|
-
|
|
261
|
+
| name | type | optional | default | description |
|
|
262
|
+
| ----------- | -------------------------------------------------- | -------- | --------- | -------------------------------------------------------------- |
|
|
263
|
+
| prefix | `string` | `true` | `"/trpc"` | URL prefix for tRPC routes |
|
|
264
|
+
| useWSS | `boolean` | `true` | `false` | Enable WebSocket support via `@fastify/websocket` |
|
|
265
|
+
| trpcOptions | `FastifyHandlerOptions<AppRouter, Request, Reply>` | `false` | `n/a` | tRPC handler options including `router`, `createContext`, etc. |
|
|
181
266
|
|
|
182
|
-
|
|
183
|
-
const server = fastify();
|
|
184
|
-
```
|
|
267
|
+
`trpcOptions` accepts the [options every adapter takes](https://trpc.io/docs/server/adapters#common-options), like `onError` and `maxBatchSize`. With `useWSS`, it also accepts the WebSocket options `keepAlive`, `dangerouslyDisablePong` and `experimental_encoder`.
|
|
185
268
|
|
|
186
|
-
|
|
269
|
+
## Common mistakes
|
|
187
270
|
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
});
|
|
192
|
-
```
|
|
271
|
+
- **Registering `@fastify/websocket` after the tRPC plugin.** It only adds WebSocket support to routes registered after it, so register it first.
|
|
272
|
+
- **Leaving `maxParamLength` at Fastify's default of `100`.** A batch request puts every procedure in one path parameter, like `/trpc/getUserById,createUser`, and Fastify answers `414 URI Too Long` once that gets longer than `maxParamLength`.
|
|
273
|
+
- **Using Fastify v4.** The tRPC v11 adapter requires Fastify v5 or later.
|
|
193
274
|
|
|
194
|
-
|
|
275
|
+
## Common options
|
|
195
276
|
|
|
196
|
-
|
|
277
|
+
Every HTTP adapter accepts these options, next to its own (like `endpoint` for Fetch, or `basePath` for Standalone):
|
|
197
278
|
|
|
198
|
-
|
|
279
|
+
| Option | Description |
|
|
280
|
+
| --------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
281
|
+
| `router` | Your app router. Required. |
|
|
282
|
+
| `createContext` | Creates the [context](https://trpc.io/docs/server/context) for each request. It receives the adapter's own objects (e.g. `req` and `res`) plus `info`. |
|
|
283
|
+
| `onError` | Called with `{ error, type, path, input, ctx, req }` for every error, e.g. to report it. See [Error handling](https://trpc.io/docs/server/error-handling#handling-errors). |
|
|
284
|
+
| `responseMeta` | Returns `{ status, headers }` for the response, e.g. for [caching](https://trpc.io/docs/server/caching). |
|
|
285
|
+
| `allowBatching` | Set to `false` to reject batch requests. Defaults to `true`. |
|
|
286
|
+
| `maxBatchSize` | Rejects batch requests with more calls than this with a `400 Bad Request`. Set `maxItems` on your batch link to the same or a lower value. |
|
|
287
|
+
| `allowMethodOverride` | Accepts queries sent as `POST`, for clients that set `methodOverride: 'POST'` on their link. Defaults to `false`. |
|
|
199
288
|
|
|
200
|
-
|
|
289
|
+
The Node.js adapters (Standalone, Express and Next.js) also accept:
|
|
201
290
|
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
```
|
|
291
|
+
- `maxBodySize`: the largest request body in bytes; larger ones are rejected with `413 PAYLOAD_TOO_LARGE`.
|
|
292
|
+
- `middleware`: a connect-style `(req, res, next)` function that runs before tRPC, e.g. [`cors()`](https://trpc.io/docs/server/adapters/standalone#handling-cors--options).
|
|
205
293
|
|
|
206
|
-
|
|
294
|
+
```ts no-check title="server.ts"
|
|
295
|
+
import { createHTTPServer } from '@trpc/server/adapters/standalone';
|
|
296
|
+
import { appRouter } from './router';
|
|
207
297
|
|
|
208
|
-
|
|
209
|
-
|
|
298
|
+
createHTTPServer({
|
|
299
|
+
router: appRouter,
|
|
300
|
+
createContext: () => ({}),
|
|
301
|
+
onError({ error, path }) {
|
|
302
|
+
console.error(`tRPC error on '${path}':`, error);
|
|
303
|
+
},
|
|
304
|
+
maxBatchSize: 10,
|
|
305
|
+
maxBodySize: 1_000_000, // 1 MB
|
|
306
|
+
}).listen(3000);
|
|
210
307
|
```
|
|
211
308
|
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
Source: www/docs/server/adapters/fastify.md
|
|
309
|
+
From https://trpc.io/docs/server/adapters#common-options
|
|
215
310
|
|
|
216
|
-
##
|
|
311
|
+
## Related skills
|
|
217
312
|
|
|
218
|
-
-
|
|
219
|
-
- **subscriptions** -- async generator subscriptions, `tracked()`, `keepAlive`
|
|
220
|
-
- **adapter-standalone** -- simpler adapter when Fastify features are not needed
|
|
221
|
-
- Fastify docs: https://fastify.dev/docs/latest/
|
|
313
|
+
- `server-setup` (https://trpc.io/docs/server/overview): `npx @tanstack/intent@latest load @trpc/server#server-setup`
|