@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.
Files changed (114) hide show
  1. package/README.md +0 -8
  2. package/dist/adapters/aws-lambda/index.cjs +1 -1
  3. package/dist/adapters/aws-lambda/index.d.cts.map +1 -1
  4. package/dist/adapters/aws-lambda/index.d.mts.map +1 -1
  5. package/dist/adapters/aws-lambda/index.mjs +1 -1
  6. package/dist/adapters/aws-lambda/index.mjs.map +1 -1
  7. package/dist/adapters/express.cjs +1 -1
  8. package/dist/adapters/express.mjs +1 -1
  9. package/dist/adapters/express.mjs.map +1 -1
  10. package/dist/adapters/fastify/index.cjs +3 -3
  11. package/dist/adapters/fastify/index.mjs +3 -3
  12. package/dist/adapters/fetch/index.cjs +1 -1
  13. package/dist/adapters/fetch/index.mjs +1 -1
  14. package/dist/adapters/next-app-dir.mjs.map +1 -1
  15. package/dist/adapters/next.cjs +1 -1
  16. package/dist/adapters/next.mjs +1 -1
  17. package/dist/adapters/next.mjs.map +1 -1
  18. package/dist/adapters/node-http/index.cjs +1 -1
  19. package/dist/adapters/node-http/index.mjs +1 -1
  20. package/dist/adapters/standalone.cjs +9 -3
  21. package/dist/adapters/standalone.d.cts +0 -1
  22. package/dist/adapters/standalone.d.cts.map +1 -1
  23. package/dist/adapters/standalone.d.mts +0 -1
  24. package/dist/adapters/standalone.d.mts.map +1 -1
  25. package/dist/adapters/standalone.mjs +9 -3
  26. package/dist/adapters/standalone.mjs.map +1 -1
  27. package/dist/adapters/ws.cjs +1 -1
  28. package/dist/adapters/ws.mjs +1 -1
  29. package/dist/asyncGeneratorDelegate-FcEJT04i.mjs.map +1 -1
  30. package/dist/codes-C9N0z0an.mjs.map +1 -1
  31. package/dist/getErrorShape-zlj81BiC.mjs.map +1 -1
  32. package/dist/http.cjs +1 -1
  33. package/dist/http.mjs +1 -1
  34. package/dist/initTRPC-RMeQIy9H.mjs.map +1 -1
  35. package/dist/{node-http-B5jkpWn7.mjs → node-http-ChhZEv1k.mjs} +2 -2
  36. package/dist/node-http-ChhZEv1k.mjs.map +1 -0
  37. package/dist/{node-http-BZ0HlzkC.cjs → node-http-X8RiQEuH.cjs} +1 -1
  38. package/dist/parseTRPCMessage-CJ4DJVBp.mjs.map +1 -1
  39. package/dist/{resolveResponse-b9D_SrLs.cjs → resolveResponse-CoGjFxK0.cjs} +8 -4
  40. package/dist/{resolveResponse-DH5L33sC.mjs → resolveResponse-DksrxZ2k.mjs} +9 -5
  41. package/dist/resolveResponse-DksrxZ2k.mjs.map +1 -0
  42. package/dist/unstable-core-do-not-import-B8epiErP.d.cts.map +1 -1
  43. package/dist/unstable-core-do-not-import-Dbo98mkh.d.mts.map +1 -1
  44. package/dist/unstable-core-do-not-import.cjs +1 -1
  45. package/dist/unstable-core-do-not-import.mjs +1 -1
  46. package/dist/unstable-core-do-not-import.mjs.map +1 -1
  47. package/dist/{ws-83TNWW-W.cjs → ws-7qWW7Uec.cjs} +2 -2
  48. package/dist/{ws-DJ2SSChC.mjs → ws-BYfo-HED.mjs} +3 -3
  49. package/dist/ws-BYfo-HED.mjs.map +1 -0
  50. package/package.json +9 -12
  51. package/skills/adapter-aws-lambda/SKILL.md +152 -134
  52. package/skills/adapter-express/SKILL.md +127 -113
  53. package/skills/adapter-fastify/SKILL.md +228 -136
  54. package/skills/adapter-fetch/SKILL.md +388 -111
  55. package/skills/adapter-standalone/SKILL.md +184 -94
  56. package/skills/auth/SKILL.md +327 -202
  57. package/skills/auth/references/client-cors.md +29 -0
  58. package/skills/caching/SKILL.md +58 -148
  59. package/skills/error-handling/SKILL.md +280 -174
  60. package/skills/middlewares/SKILL.md +320 -121
  61. package/skills/non-json-content-types/SKILL.md +149 -168
  62. package/skills/server-setup/SKILL.md +355 -253
  63. package/skills/server-setup/references/server-context.md +219 -0
  64. package/skills/server-setup/references/server-merging-routers.md +141 -0
  65. package/skills/server-setup/references/server-metadata.md +105 -0
  66. package/skills/server-setup/references/server-procedures.md +172 -0
  67. package/skills/server-setup/references/server-routers.md +123 -0
  68. package/skills/server-side-calls/SKILL.md +247 -152
  69. package/skills/service-oriented-architecture/SKILL.md +81 -177
  70. package/skills/subscriptions/SKILL.md +341 -297
  71. package/skills/subscriptions/references/client-links-httpSubscriptionLink.md +404 -0
  72. package/skills/subscriptions/references/client-links-wsLink.md +122 -0
  73. package/skills/subscriptions/references/server-websockets.md +297 -0
  74. package/skills/trpc-router/SKILL.md +156 -86
  75. package/skills/validators/SKILL.md +384 -128
  76. package/src/adapters/aws-lambda/getPlanner.ts +4 -3
  77. package/src/adapters/aws-lambda/index.ts +2 -1
  78. package/src/adapters/express.ts +1 -1
  79. package/src/adapters/next-app-dir/nextAppDirCaller.ts +4 -4
  80. package/src/adapters/next-app-dir/rethrowNextErrors.ts +1 -1
  81. package/src/adapters/next.ts +1 -1
  82. package/src/adapters/node-http/incomingMessageToRequest.ts +1 -1
  83. package/src/adapters/node-http/nodeHTTPRequestHandler.ts +1 -1
  84. package/src/adapters/node-http/types.ts +1 -1
  85. package/src/adapters/node-http/writeResponse.ts +1 -1
  86. package/src/adapters/standalone.ts +12 -6
  87. package/src/adapters/ws.ts +5 -5
  88. package/src/unstable-core-do-not-import/clientish/inferrable.ts +4 -1
  89. package/src/unstable-core-do-not-import/clientish/serialize.ts +4 -4
  90. package/src/unstable-core-do-not-import/error/TRPCError.ts +3 -3
  91. package/src/unstable-core-do-not-import/http/formDataToObject.ts +1 -1
  92. package/src/unstable-core-do-not-import/http/getHTTPStatusCode.ts +1 -1
  93. package/src/unstable-core-do-not-import/http/resolveResponse.ts +13 -2
  94. package/src/unstable-core-do-not-import/procedure.ts +5 -2
  95. package/src/unstable-core-do-not-import/procedureBuilder.ts +3 -2
  96. package/src/unstable-core-do-not-import/rootConfig.ts +2 -2
  97. package/src/unstable-core-do-not-import/router.ts +5 -2
  98. package/src/unstable-core-do-not-import/rpc/envelopes.ts +3 -2
  99. package/src/unstable-core-do-not-import/stream/jsonl.ts +2 -1
  100. package/src/unstable-core-do-not-import/stream/sse.types.ts +1 -1
  101. package/src/unstable-core-do-not-import/stream/utils/asyncIterable.ts +1 -1
  102. package/src/unstable-core-do-not-import/stream/utils/createDeferred.ts +1 -1
  103. package/src/unstable-core-do-not-import/stream/utils/disposable.ts +6 -6
  104. package/src/unstable-core-do-not-import/stream/utils/mergeAsyncIterables.ts +2 -2
  105. package/src/unstable-core-do-not-import/stream/utils/withPing.ts +3 -1
  106. package/src/unstable-core-do-not-import/transformer.ts +4 -1
  107. package/src/unstable-core-do-not-import/types.ts +3 -2
  108. package/src/unstable-core-do-not-import/utils.ts +1 -1
  109. package/src/vendor/standard-schema-v1/spec.ts +2 -2
  110. package/src/vendor/unpromise/unpromise.ts +1 -1
  111. package/bin/intent.js +0 -20
  112. package/dist/node-http-B5jkpWn7.mjs.map +0 -1
  113. package/dist/resolveResponse-DH5L33sC.mjs.map +0 -1
  114. package/dist/ws-DJ2SSChC.mjs.map +0 -1
@@ -0,0 +1,297 @@
1
+ # WebSockets
2
+
3
+ From https://trpc.io/docs/server/websockets
4
+
5
+ You can use WebSockets for all or some of the communication with your server, see [wsLink](https://trpc.io/docs/client/links/wsLink) for how to set it up on the client.
6
+
7
+ > [!TIP]
8
+ > The document here outlines the specific details of using WebSockets. For general usage of subscriptions, see [our subscriptions guide](https://trpc.io/docs/server/subscriptions).
9
+
10
+
11
+ ### Creating a WebSocket-server
12
+
13
+ ```bash
14
+ yarn add ws
15
+ ```
16
+
17
+ ```ts no-check title="server/wsServer.ts"
18
+ import { applyWSSHandler } from '@trpc/server/adapters/ws';
19
+ import { WebSocketServer } from 'ws';
20
+ import { appRouter } from './routers/app';
21
+ import { createContext } from './trpc';
22
+
23
+ const wss = new WebSocketServer({
24
+ port: 3001,
25
+ });
26
+ const handler = applyWSSHandler({
27
+ wss,
28
+ router: appRouter,
29
+ createContext,
30
+ // Enable heartbeat messages to keep connection open (disabled by default)
31
+ keepAlive: {
32
+ enabled: true,
33
+ // server ping message interval in milliseconds
34
+ pingMs: 30000,
35
+ // connection is terminated if pong message is not received in this many milliseconds
36
+ pongWaitMs: 5000,
37
+ },
38
+ });
39
+
40
+ wss.on('connection', (ws) => {
41
+ console.log(`++ Connection (${wss.clients.size})`);
42
+ ws.once('close', () => {
43
+ console.log(`-- Connection (${wss.clients.size})`);
44
+ });
45
+ });
46
+ console.log('WebSocket Server listening on ws://localhost:3001');
47
+
48
+ process.on('SIGTERM', () => {
49
+ console.log('SIGTERM');
50
+ handler.broadcastReconnectNotification();
51
+ wss.close();
52
+ });
53
+ ```
54
+
55
+ ### Sharing a port with your HTTP server
56
+
57
+ To serve HTTP and WebSockets on the same port, pass your HTTP server to `WebSocketServer`. `ws` then handles the upgrade requests, and your adapter handles the rest.
58
+
59
+ ```ts no-check title="server/index.ts"
60
+ import { createHTTPServer } from '@trpc/server/adapters/standalone';
61
+ import { applyWSSHandler } from '@trpc/server/adapters/ws';
62
+ import { WebSocketServer } from 'ws';
63
+ import { appRouter } from './router';
64
+
65
+ const server = createHTTPServer({ router: appRouter });
66
+ const wss = new WebSocketServer({ server });
67
+ applyWSSHandler({ wss, router: appRouter });
68
+
69
+ server.listen(3000);
70
+ ```
71
+
72
+ ### Setting `TRPCClient` to use WebSockets
73
+
74
+ > [!TIP]
75
+ > You can use [Links](https://trpc.io/docs/client/links) to route queries and/or mutations to HTTP transport and subscriptions over WebSockets.
76
+
77
+
78
+ ```tsx no-check title="client.ts"
79
+ import { createTRPCClient, createWSClient, wsLink } from '@trpc/client';
80
+ import type { AppRouter } from './server';
81
+
82
+ // create persistent WebSocket connection
83
+ const wsClient = createWSClient({
84
+ url: `ws://localhost:3001`,
85
+ });
86
+
87
+ // configure TRPCClient to use WebSockets transport
88
+ const client = createTRPCClient<AppRouter>({
89
+ links: [
90
+ wsLink({
91
+ client: wsClient,
92
+ }),
93
+ ],
94
+ });
95
+ ```
96
+
97
+ ## Authentication / connection params
98
+
99
+ > [!TIP]
100
+ > If you're doing a web application, you can ignore this section as the cookies are sent as part of the request.
101
+
102
+
103
+ In order to authenticate with WebSockets, you can define `connectionParams` to `createWSClient`. This will be sent as the first message when the client establishes a WebSocket connection.
104
+
105
+ ```ts no-check title="server/context.ts"
106
+ import type { CreateWSSContextFnOptions } from '@trpc/server/adapters/ws';
107
+
108
+ export const createContext = async (opts: CreateWSSContextFnOptions) => {
109
+ const token = opts.info.connectionParams?.token;
110
+
111
+ // [... authenticate]
112
+
113
+ return {};
114
+ };
115
+
116
+ export type Context = Awaited<ReturnType<typeof createContext>>;
117
+ ```
118
+
119
+ ```ts no-check title="client/trpc.ts"
120
+ import { createTRPCClient, createWSClient, wsLink } from '@trpc/client';
121
+ import type { AppRouter } from './server';
122
+ import superjson from 'superjson';
123
+
124
+ const wsClient = createWSClient({
125
+ url: `ws://localhost:3000`,
126
+
127
+ connectionParams: async () => {
128
+ return {
129
+ token: 'supersecret',
130
+ };
131
+ },
132
+ });
133
+ export const trpc = createTRPCClient<AppRouter>({
134
+ links: [wsLink({ client: wsClient, transformer: superjson })],
135
+ });
136
+ ```
137
+
138
+ `createContext` runs once per connection (after the connection params arrive, if you send them), and every call over that connection shares its result. If it throws, the server sends the error and closes the connection. A token is only checked when the connection opens, so it stays accepted on that connection after it expires.
139
+
140
+ ## Automatic tracking of id using `tracked()` (recommended)
141
+
142
+ If you `yield` an event using our `tracked()`-helper and include an `id`, the client will automatically reconnect when it gets disconnected and send the last known ID when reconnecting as part of the `lastEventId`-input.
143
+
144
+ You can send an initial `lastEventId` when initializing the subscription and it will be automatically updated as the browser receives data.
145
+
146
+ > [!NOTE] Info
147
+ > If you're fetching data based on the `lastEventId`, and capturing all events is critical, you may want to use `ReadableStream`'s or a similar pattern as an intermediary as is done in [our full-stack SSE example](https://github.com/trpc/examples-tanstack-start-sse-chat) to prevent newly emitted events being ignored while yield'ing the original batch based on `lastEventId`.
148
+
149
+
150
+ ```ts no-check
151
+ import EventEmitter, { on } from 'events';
152
+ import { initTRPC, tracked } from '@trpc/server';
153
+ import { z } from 'zod';
154
+
155
+ type Post = { id: string; title: string };
156
+
157
+ const t = initTRPC.create();
158
+ const publicProcedure = t.procedure;
159
+ const router = t.router;
160
+
161
+ const ee = new EventEmitter();
162
+
163
+ export const subRouter = router({
164
+ onPostAdd: publicProcedure
165
+ .input(
166
+ z
167
+ .object({
168
+ // lastEventId is the last event id that the client has received
169
+ // On the first call, it will be whatever was passed in the initial setup
170
+ // If the client reconnects, it will be the last event id that the client received
171
+ lastEventId: z.string().nullish(),
172
+ })
173
+ .optional(),
174
+ )
175
+ .subscription(async function* (opts) {
176
+ if (opts.input?.lastEventId) {
177
+ // [...] get the posts since the last event id and yield them
178
+ }
179
+ // listen for new events
180
+ for await (const [data] of on(ee, 'add', {
181
+ // Passing the AbortSignal from the request automatically cancels the event emitter when the subscription is aborted
182
+ signal: opts.signal,
183
+ })) {
184
+ const post = data as Post;
185
+ // tracking the post id ensures the client can reconnect at any time and get the latest events since this id
186
+ yield tracked(post.id, post);
187
+ }
188
+ }),
189
+ });
190
+ ```
191
+
192
+ ## WebSockets RPC Specification
193
+
194
+ > You can read more details by drilling into the TypeScript definitions:
195
+ >
196
+ > - [/packages/server/src/unstable-core-do-not-import/rpc/envelopes.ts](https://github.com/trpc/trpc/tree/main/packages/server/src/unstable-core-do-not-import/rpc/envelopes.ts)
197
+ > - [/packages/server/src/unstable-core-do-not-import/rpc/codes.ts](https://github.com/trpc/trpc/tree/main/packages/server/src/unstable-core-do-not-import/rpc/codes.ts).
198
+
199
+ ### `query` / `mutation`
200
+
201
+ #### Request
202
+
203
+ ```ts no-check
204
+ interface RequestMessage {
205
+ id: number | string;
206
+ jsonrpc?: '2.0';
207
+ method: 'query' | 'mutation';
208
+ params: {
209
+ path: string;
210
+ input?: unknown; // <-- pass input of procedure, serialized by transformer
211
+ };
212
+ }
213
+ ```
214
+
215
+ #### Response
216
+
217
+ _... below, or an error._
218
+
219
+ ```ts no-check
220
+ interface ResponseMessage {
221
+ id: number | string;
222
+ jsonrpc?: '2.0';
223
+ result: {
224
+ type: 'data'; // always 'data' for mutation / queries
225
+ data: TOutput; // output from procedure
226
+ };
227
+ }
228
+ ```
229
+
230
+ ### `subscription` / `subscription.stop`
231
+
232
+ #### Start a subscription
233
+
234
+ ```ts no-check
235
+ interface SubscriptionRequest {
236
+ id: number | string;
237
+ jsonrpc?: '2.0';
238
+ method: 'subscription';
239
+ params: {
240
+ path: string;
241
+ input?: unknown; // <-- pass input of procedure, serialized by transformer
242
+ };
243
+ }
244
+ ```
245
+
246
+ #### To cancel a subscription, call `subscription.stop`
247
+
248
+ ```ts no-check
249
+ interface SubscriptionStopRequest {
250
+ id: number | string; // <-- id of your created subscription
251
+ jsonrpc?: '2.0';
252
+ method: 'subscription.stop';
253
+ }
254
+ ```
255
+
256
+ #### Subscription response shape
257
+
258
+ _... below, or an error._
259
+
260
+ ```ts no-check
261
+ interface SubscriptionResponse {
262
+ id: number | string;
263
+ jsonrpc?: '2.0';
264
+ result:
265
+ | {
266
+ type: 'data';
267
+ data: TData; // subscription emitted data
268
+ }
269
+ | {
270
+ type: 'started'; // subscription started
271
+ }
272
+ | {
273
+ type: 'stopped'; // subscription stopped
274
+ };
275
+ }
276
+ ```
277
+
278
+ #### Connection params
279
+
280
+ If the connection is initialized with `?connectionParams=1`, the first message has to be connection params.
281
+
282
+ ```ts no-check
283
+ interface ConnectionParamsMessage {
284
+ data: Record<string, string> | null;
285
+ method: 'connectionParams';
286
+ }
287
+ ```
288
+
289
+ ## Errors
290
+
291
+ See [https://www.jsonrpc.org/specification#error_object](https://www.jsonrpc.org/specification#error_object) or [Error Formatting](https://trpc.io/docs/server/error-formatting).
292
+
293
+ ## Notifications from Server to Client
294
+
295
+ ### `{ id: null, type: 'reconnect' }`
296
+
297
+ Tells clients to reconnect before shutting down the server. Invoked by `wssHandler.broadcastReconnectNotification()`.
@@ -1,104 +1,124 @@
1
1
  ---
2
2
  name: trpc-router
3
- description: >
4
- Entry point for all tRPC skills. Decision tree routing by task: initTRPC.create(),
5
- t.router(), t.procedure, createTRPCClient, adapters, subscriptions, React Query,
6
- Next.js, links, middleware, validators, error handling, caching, FormData.
7
- type: core
8
- library: trpc
9
- library_version: '11.16.0'
10
- requires: []
3
+ description: "Entry point for all tRPC skills. Decision tree routing by task: initTRPC.create(), t.router(), t.procedure, createTRPCClient, adapters, subscriptions, React Query, Next.js, links, middleware, validators, error handling, caching, FormData, OpenAPI, multiple services. Includes a minimal working server and client."
11
4
  sources:
12
- - 'trpc/trpc:www/docs/main/introduction.mdx'
13
- - 'trpc/trpc:www/docs/main/quickstart.mdx'
5
+ - www/v11/docs/skills.md
6
+ - www/v11/docs/quickstart.md
7
+ metadata:
8
+ type: core
9
+ library: trpc
10
+ library_version: 11.23.0
14
11
  ---
15
12
 
16
- # tRPC -- Skill Router
13
+ <!-- Generated from www/v11/docs/skills.md by www/build/skills.ts. Edit the docs instead. -->
17
14
 
18
- ## Decision Tree
15
+ # Agent Skills
19
16
 
20
- ### What are you trying to do?
17
+ > Set up and use TanStack Intent to provide AI agent skills for tRPC
21
18
 
22
- #### Define a tRPC backend (server)
19
+ From https://trpc.io/docs/skills
23
20
 
24
- - **Initialize tRPC, define routers, procedures, context, export AppRouter**
25
- -> Load skill: `server-setup`
21
+ tRPC ships [TanStack Intent](https://tanstack.com/intent/latest/docs/getting-started/quick-start-consumers) skills to help AI coding agents work with tRPC. When your agent works on a task that matches a skill, it loads the skill's `SKILL.md` into context.
26
22
 
27
- - **Add middleware (.use), auth guards, logging, base procedures**
28
- -> Load skill: `middlewares`
23
+ The skills ship inside `@trpc/server`, `@trpc/client`, `@trpc/tanstack-react-query`, `@trpc/next` and `@trpc/openapi`, so they're already in your `node_modules`.
29
24
 
30
- - **Add input/output validation with Zod or other libraries**
31
- -> Load skill: `validators`
25
+ ## Setup
32
26
 
33
- - **Throw typed errors, format errors for clients, global error handling**
34
- -> Load skill: `error-handling`
27
+ ### 1. Run install
35
28
 
36
- - **Call procedures from server code, write integration tests**
37
- -> Load skill: `server-side-calls`
29
+ The `install` command adds skill-loading guidance to your agent's config file (`AGENTS.md`, `CLAUDE.md`, etc.):
38
30
 
39
- - **Set Cache-Control headers on query responses (CDN, browser caching)**
40
- -> Load skill: `caching`
31
+ ```bash
32
+ npx @tanstack/intent@latest install
33
+ ```
34
+
35
+ It covers the skills shipped in tRPC and your other installed packages.
36
+
37
+ ### 2. Use skills in your workflow
38
+
39
+ When your agent works on a task that matches a skill, it loads the corresponding `SKILL.md` into context to guide implementation.
41
40
 
42
- - **Accept FormData, File, Blob, or binary uploads in mutations**
43
- -> Load skill: `non-json-content-types`
41
+ To see which skills are available:
44
42
 
45
- - **Set up real-time subscriptions (SSE or WebSocket)**
46
- -> Load skill: `subscriptions`
43
+ ```bash
44
+ npx @tanstack/intent@latest list
45
+ ```
46
+
47
+ To load one yourself, for example the server auth skill:
47
48
 
48
- #### Host the tRPC API (adapters)
49
+ ```bash
50
+ npx @tanstack/intent@latest load @trpc/server#auth
51
+ ```
49
52
 
50
- - **Node.js built-in HTTP server (simplest, local dev)**
51
- -> Load skill: `adapter-standalone`
53
+ ### 3. Keep skills up-to-date
52
54
 
53
- - **Express middleware**
54
- -> Load skill: `adapter-express`
55
+ Skills version with library releases. When you update tRPC (e.g. `npm update @trpc/server`), you get the skills that match your installed version.
55
56
 
56
- - **Fastify plugin**
57
- -> Load skill: `adapter-fastify`
57
+ ## Skills by task
58
58
 
59
- - **AWS Lambda (API Gateway v1/v2, Function URLs)**
60
- -> Load skill: `adapter-aws-lambda`
59
+ Each skill is generated from a page of these docs. Load one with `npx @tanstack/intent@latest load <skill>`, for example `npx @tanstack/intent@latest load @trpc/server#server-setup`.
61
60
 
62
- - **Fetch API / Edge (Cloudflare Workers, Deno, Vercel Edge, Astro, Remix)**
63
- -> Load skill: `adapter-fetch`
61
+ ### Build the API
64
62
 
65
- #### Consume the tRPC API (client)
63
+ | Task | Skill |
64
+ | --- | --- |
65
+ | Initialize tRPC, define routers, procedures and context, export `AppRouter` | [`@trpc/server#server-setup`](https://trpc.io/docs/server/overview) |
66
+ | Add middleware and reusable base procedures | [`@trpc/server#middlewares`](https://trpc.io/docs/server/middlewares) |
67
+ | Validate inputs and outputs with Zod or another library | [`@trpc/server#validators`](https://trpc.io/docs/server/validators) |
68
+ | Throw, format and handle errors | [`@trpc/server#error-handling`](https://trpc.io/docs/server/error-handling) |
69
+ | Authenticate users and protect procedures | [`@trpc/server#auth`](https://trpc.io/docs/server/authorization) |
70
+ | Call procedures from server code or tests | [`@trpc/server#server-side-calls`](https://trpc.io/docs/server/server-side-calls) |
71
+ | Set HTTP cache headers on responses | [`@trpc/server#caching`](https://trpc.io/docs/server/caching) |
72
+ | Accept `FormData`, files and binary inputs | [`@trpc/server#non-json-content-types`](https://trpc.io/docs/server/non-json-content-types) |
73
+ | Stream real-time updates over SSE or WebSockets | [`@trpc/server#subscriptions`](https://trpc.io/docs/server/subscriptions) |
74
+ | Send `Date`, `Map`, `Set` and other rich types with superjson | [`@trpc/client#superjson`](https://trpc.io/docs/server/data-transformers) |
75
+ | Split the API across several services | [`@trpc/server#service-oriented-architecture`](https://trpc.io/docs/server/service-oriented-architecture) |
66
76
 
67
- - **Create a vanilla TypeScript client, configure links, headers, types**
68
- -> Load skill: `client-setup`
77
+ ### Serve the API
69
78
 
70
- - **Configure link chain (batching, streaming, splitting, WebSocket, SSE)**
71
- -> Load skill: `links`
79
+ | Task | Skill |
80
+ | --- | --- |
81
+ | Node.js HTTP server, the simplest setup | [`@trpc/server#adapter-standalone`](https://trpc.io/docs/server/adapters/standalone) |
82
+ | Express | [`@trpc/server#adapter-express`](https://trpc.io/docs/server/adapters/express) |
83
+ | Fastify | [`@trpc/server#adapter-fastify`](https://trpc.io/docs/server/adapters/fastify) |
84
+ | AWS Lambda behind API Gateway or a Function URL | [`@trpc/server#adapter-aws-lambda`](https://trpc.io/docs/server/adapters/aws-lambda) |
85
+ | Fetch API and edge runtimes: Cloudflare Workers, Deno, Vercel Edge, Astro, Remix | [`@trpc/server#adapter-fetch`](https://trpc.io/docs/server/adapters/fetch) |
72
86
 
73
- - **Use SuperJSON transformer for Date, Map, Set, BigInt**
74
- -> Load skill: `superjson`
87
+ ### Call the API
75
88
 
76
- #### Use tRPC with a framework
89
+ | Task | Skill |
90
+ | --- | --- |
91
+ | Create a TypeScript client, infer types, handle errors | [`@trpc/client#client-setup`](https://trpc.io/docs/client/vanilla/setup) |
92
+ | Configure links: batching, streaming, splitting, WebSockets, SSE, retries | [`@trpc/client#links`](https://trpc.io/docs/client/links) |
93
+ | Use tRPC with TanStack React Query | [`@trpc/tanstack-react-query#react-query-setup`](https://trpc.io/docs/client/tanstack-react-query/setup) |
94
+ | Migrate from the classic `@trpc/react-query` client | [`@trpc/tanstack-react-query#react-query-classic-migration`](https://trpc.io/docs/client/tanstack-react-query/migrating) |
95
+ | Next.js App Router, including server components | [`@trpc/next#nextjs-app-router`](https://trpc.io/docs/client/nextjs/app-router-setup) |
96
+ | Next.js Pages Router, SSR and SSG | [`@trpc/next#nextjs-pages-router`](https://trpc.io/docs/client/nextjs/pages-router/setup) |
97
+ | Generate an OpenAPI spec and a REST client | [`@trpc/openapi#openapi`](https://trpc.io/docs/openapi) |
77
98
 
78
- - **React with TanStack Query (useQuery, useMutation, queryOptions)**
79
- -> Load skill: `react-query-setup`
99
+ ## Learn more
80
100
 
81
- - **Next.js App Router (RSC, server components, HydrateClient)**
82
- -> Load skill: `nextjs-app-router`
101
+ For full documentation on TanStack Intent, see the [Quick Start for Consumers](https://tanstack.com/intent/latest/docs/getting-started/quick-start-consumers) guide.
83
102
 
84
- - **Next.js Pages Router (withTRPC, SSR, SSG helpers)**
85
- -> Load skill: `nextjs-pages-router`
103
+ ## Serving the API
86
104
 
87
- #### Advanced patterns
105
+ Now that we have defined our router, we can serve it. tRPC has first-class [adapters](https://trpc.io/docs/server/adapters) for many popular web servers. To keep it simple, we'll use the [`standalone`](https://trpc.io/docs/server/adapters/standalone) Node.js adapter here.
88
106
 
89
- - **Generate OpenAPI spec, REST client from tRPC router**
90
- -> Load skill: `openapi`
107
+ ```ts no-check title="server/index.ts"
108
+ import { createHTTPServer } from '@trpc/server/adapters/standalone';
109
+ import { appRouter } from './appRouter';
91
110
 
92
- - **Multi-service gateway, custom routing links, SOA**
93
- -> Load skill: `service-oriented-architecture`
111
+ const server = createHTTPServer({
112
+ router: appRouter,
113
+ });
94
114
 
95
- - **Auth middleware + client headers + subscription auth**
96
- -> Load skill: `auth`
115
+ server.listen(3000);
116
+ ```
97
117
 
98
- ## Quick Reference: Minimal Working App
118
+ <details>
119
+ <summary>See the full backend code</summary>
99
120
 
100
- ```ts
101
- // server/trpc.ts
121
+ ```ts no-check title="server/trpc.ts"
102
122
  import { initTRPC } from '@trpc/server';
103
123
 
104
124
  const t = initTRPC.create();
@@ -107,45 +127,95 @@ export const router = t.router;
107
127
  export const publicProcedure = t.procedure;
108
128
  ```
109
129
 
110
- ```ts
111
- // server/appRouter.ts
112
- import { z } from 'zod';
113
- import { publicProcedure, router } from './trpc';
130
+ <br/>
131
+
132
+ ```ts no-check title="server/appRouter.ts"
133
+ import { z } from "zod";
134
+ import { publicProcedure, router } from "./trpc";
135
+
136
+ type User = { id: string; name: string };
114
137
 
115
138
  export const appRouter = router({
116
- hello: publicProcedure
139
+ userList: publicProcedure
140
+ .query(async () => {
141
+ const users: User[] = [{ id: '1', name: 'Katt' }];
142
+ return users;
143
+ }),
144
+ userById: publicProcedure
145
+ .input(z.string())
146
+ .query(async (opts) => {
147
+ const { input } = opts;
148
+ const user: User = { id: input, name: 'Katt' };
149
+ return user;
150
+ }),
151
+ userCreate: publicProcedure
117
152
  .input(z.object({ name: z.string() }))
118
- .query(({ input }) => ({ greeting: `Hello ${input.name}` })),
153
+ .mutation(async (opts) => {
154
+ const { input } = opts;
155
+ const user: User = { id: '1', ...input };
156
+ return user;
157
+ }),
119
158
  });
120
159
 
121
160
  export type AppRouter = typeof appRouter;
122
161
  ```
123
162
 
124
- ```ts
125
- // server/index.ts
126
- import { createHTTPServer } from '@trpc/server/adapters/standalone';
127
- import { appRouter } from './appRouter';
163
+ <br/>
164
+
165
+ ```ts no-check title="server/index.ts"
166
+ import { createHTTPServer } from "@trpc/server/adapters/standalone";
167
+ import { appRouter } from "./appRouter";
168
+
169
+ const server = createHTTPServer({
170
+ router: appRouter,
171
+ });
128
172
 
129
- const server = createHTTPServer({ router: appRouter });
130
173
  server.listen(3000);
131
174
  ```
132
175
 
133
- ```ts
134
- // client/index.ts
176
+ </details>
177
+
178
+ From https://trpc.io/docs/quickstart#serving-the-api
179
+
180
+ ## Using your new backend on the client
181
+
182
+ Let's now move to the client-side code and embrace the power of end-to-end typesafety. When we import the `AppRouter` type for the client to use, we have achieved full typesafety for our system without leaking any implementation details to the client.
183
+
184
+ ### 1. Setup the tRPC Client
185
+
186
+ ```ts no-check title="client/index.ts"
135
187
  import { createTRPCClient, httpBatchLink } from '@trpc/client';
136
188
  import type { AppRouter } from '../server/appRouter';
189
+ // 👆 **type-only** imports are stripped at build time
137
190
 
191
+ // Pass AppRouter as a type parameter. 👇 This lets `trpc` know
192
+ // what procedures are available on the server and their input/output types.
138
193
  const trpc = createTRPCClient<AppRouter>({
139
- links: [httpBatchLink({ url: 'http://localhost:3000' })],
194
+ links: [
195
+ httpBatchLink({
196
+ url: 'http://localhost:3000',
197
+ }),
198
+ ],
140
199
  });
200
+ ```
201
+
202
+ Links in tRPC are similar to links in GraphQL, they let us control the data flow to the server. In the example above, we use the [httpBatchLink](https://trpc.io/docs/client/links/httpBatchLink), which automatically batches up multiple calls into a single HTTP request. For more in-depth usage of links, see the [links documentation](https://trpc.io/docs/client/links).
203
+
204
+ ### 2. Type Inference & Autocomplete
205
+
206
+ You now have access to your API procedures on the `trpc` object. Try it out!
141
207
 
142
- const result = await trpc.hello.query({ name: 'World' });
208
+ ```ts no-check title="client/index.ts"
209
+ // Inferred types
210
+ const user = await trpc.userById.query('1');
211
+
212
+ const createdUser = await trpc.userCreate.mutate({ name: 'Katt' });
143
213
  ```
144
214
 
145
- ## See Also
215
+ You can also use your autocomplete to explore the API on your client
216
+
217
+ ```ts no-check title="client/index.ts"
218
+ trpc.u;
219
+ ```
146
220
 
147
- - `server-setup` -- full server initialization details
148
- - `client-setup` -- full client configuration
149
- - `adapter-standalone` -- simplest adapter for getting started
150
- - `react-query-setup` -- React integration
151
- - `nextjs-app-router` -- Next.js App Router integration
221
+ From https://trpc.io/docs/quickstart#using-your-new-backend-on-the-client