@trpc/client 11.22.1 → 11.22.2-canary.11.4427f0bea

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.
@@ -1,317 +0,0 @@
1
- ---
2
- name: client-setup
3
- description: >
4
- Create a vanilla tRPC client with createTRPCClient<AppRouter>(), configure
5
- link chain with httpBatchLink/httpLink, dynamic headers for auth, transformer
6
- on links (not client constructor). Infer types with inferRouterInputs and
7
- inferRouterOutputs. AbortController signal support. TRPCClientError typing.
8
- type: core
9
- library: trpc
10
- library_version: '11.16.0'
11
- requires:
12
- - server-setup
13
- sources:
14
- - www/docs/client/overview.md
15
- - www/docs/client/vanilla/overview.md
16
- - www/docs/client/vanilla/setup.mdx
17
- - www/docs/client/vanilla/infer-types.md
18
- - www/docs/client/headers.md
19
- - packages/client/src/internals/TRPCUntypedClient.ts
20
- ---
21
-
22
- # tRPC -- Client Setup
23
-
24
- ## Setup
25
-
26
- ```ts
27
- // server.ts
28
- import { initTRPC } from '@trpc/server';
29
- import { z } from 'zod';
30
-
31
- const t = initTRPC.create();
32
-
33
- const appRouter = t.router({
34
- user: t.router({
35
- byId: t.procedure
36
- .input(z.object({ id: z.string() }))
37
- .query(({ input }) => ({ id: input.id, name: 'Bilbo' })),
38
- create: t.procedure
39
- .input(z.object({ name: z.string() }))
40
- .mutation(({ input }) => ({ id: '1', ...input })),
41
- }),
42
- });
43
-
44
- export type AppRouter = typeof appRouter;
45
- ```
46
-
47
- ```ts
48
- // client.ts
49
- import { createTRPCClient, httpBatchLink } from '@trpc/client';
50
- import type { AppRouter } from './server';
51
-
52
- const client = createTRPCClient<AppRouter>({
53
- links: [
54
- httpBatchLink({
55
- url: 'http://localhost:3000/trpc',
56
- }),
57
- ],
58
- });
59
-
60
- const user = await client.user.byId.query({ id: '1' });
61
- const created = await client.user.create.mutate({ name: 'Frodo' });
62
- ```
63
-
64
- ## Core Patterns
65
-
66
- ### Dynamic Auth Headers
67
-
68
- ```ts
69
- import { createTRPCClient, httpBatchLink } from '@trpc/client';
70
- import type { AppRouter } from './server';
71
-
72
- let token = '';
73
-
74
- export function setToken(newToken: string) {
75
- token = newToken;
76
- }
77
-
78
- export const client = createTRPCClient<AppRouter>({
79
- links: [
80
- httpBatchLink({
81
- url: 'http://localhost:3000/trpc',
82
- headers() {
83
- return {
84
- Authorization: token ? `Bearer ${token}` : '',
85
- };
86
- },
87
- }),
88
- ],
89
- });
90
- ```
91
-
92
- The `headers` callback is invoked on every HTTP request, so token changes take effect immediately.
93
-
94
- ### Inferring Procedure Input and Output Types
95
-
96
- ```ts
97
- import type { inferRouterInputs, inferRouterOutputs } from '@trpc/server';
98
- import type { AppRouter } from './server';
99
-
100
- type RouterInput = inferRouterInputs<AppRouter>;
101
- type RouterOutput = inferRouterOutputs<AppRouter>;
102
-
103
- type UserCreateInput = RouterInput['user']['create'];
104
- type UserByIdOutput = RouterOutput['user']['byId'];
105
- ```
106
-
107
- ### Aborting Requests with AbortController
108
-
109
- ```ts
110
- import { createTRPCClient, httpBatchLink } from '@trpc/client';
111
- import type { AppRouter } from './server';
112
-
113
- const client = createTRPCClient<AppRouter>({
114
- links: [httpBatchLink({ url: 'http://localhost:3000/trpc' })],
115
- });
116
-
117
- const ac = new AbortController();
118
- const query = client.user.byId.query({ id: '1' }, { signal: ac.signal });
119
- ac.abort();
120
- ```
121
-
122
- ### Typed Error Handling
123
-
124
- ```ts
125
- import { TRPCClientError } from '@trpc/client';
126
- import type { AppRouter } from './server';
127
-
128
- function isTRPCClientError(
129
- cause: unknown,
130
- ): cause is TRPCClientError<AppRouter> {
131
- return cause instanceof TRPCClientError;
132
- }
133
-
134
- try {
135
- await client.user.byId.query({ id: '1' });
136
- } catch (cause) {
137
- if (isTRPCClientError(cause)) {
138
- console.log('tRPC error code:', cause.data?.code);
139
- }
140
- }
141
- ```
142
-
143
- ## Common Mistakes
144
-
145
- ### [CRITICAL] Missing AppRouter type parameter on createTRPCClient
146
-
147
- Wrong:
148
-
149
- ```ts
150
- const client = createTRPCClient({ links: [httpBatchLink({ url })] });
151
- ```
152
-
153
- Correct:
154
-
155
- ```ts
156
- import type { AppRouter } from './server';
157
-
158
- const client = createTRPCClient<AppRouter>({ links: [httpBatchLink({ url })] });
159
- ```
160
-
161
- Without the type parameter, all procedure calls return `any` and type safety is completely lost.
162
-
163
- Source: www/docs/client/vanilla/setup.mdx
164
-
165
- ### [CRITICAL] Transformer goes on individual links, not createTRPCClient
166
-
167
- In v11, the `transformer` option is on individual terminating links, not the client constructor:
168
-
169
- ```ts
170
- import superjson from 'superjson';
171
-
172
- createTRPCClient<AppRouter>({
173
- links: [
174
- httpBatchLink({
175
- url: 'http://localhost:3000',
176
- transformer: superjson,
177
- }),
178
- ],
179
- });
180
- ```
181
-
182
- In v11, the `transformer` option was moved from the client constructor to individual terminating links. Passing it to `createTRPCClient` throws a TypeError.
183
-
184
- Source: packages/client/src/internals/TRPCUntypedClient.ts
185
-
186
- ### [CRITICAL] Transformer on server but not on client links
187
-
188
- Wrong:
189
-
190
- ```ts
191
- // Server: initTRPC.create({ transformer: superjson })
192
- // Client:
193
- httpBatchLink({ url: 'http://localhost:3000' });
194
- ```
195
-
196
- Correct:
197
-
198
- ```ts
199
- // Server: initTRPC.create({ transformer: superjson })
200
- // Client:
201
- httpBatchLink({ url: 'http://localhost:3000', transformer: superjson });
202
- ```
203
-
204
- If the server uses a transformer, every terminating link on the client must also specify that transformer. Mismatch causes "Unable to transform response" errors.
205
-
206
- Source: https://github.com/trpc/trpc/issues/7083
207
-
208
- ### [CRITICAL] Using import instead of import type for AppRouter
209
-
210
- Wrong:
211
-
212
- ```ts
213
- import { AppRouter } from '../server/router';
214
- ```
215
-
216
- Correct:
217
-
218
- ```ts
219
- import type { AppRouter } from '../server/router';
220
- ```
221
-
222
- A non-type import pulls the entire server bundle into the client. Use `import type` so it is erased at build time.
223
-
224
- Source: www/docs/client/vanilla/setup.mdx
225
-
226
- ### [CRITICAL] Importing appRouter value to derive type in client
227
-
228
- Wrong:
229
-
230
- ```ts
231
- import { appRouter } from '../server/router';
232
-
233
- type AppRouter = typeof appRouter;
234
- ```
235
-
236
- Correct:
237
-
238
- ```ts
239
- // In server: export type AppRouter = typeof appRouter;
240
- // In client:
241
- import type { AppRouter } from '../server/router';
242
- ```
243
-
244
- Importing the `appRouter` value (not just the type) bundles the entire server into the client, shipping server code to the browser.
245
-
246
- Source: www/docs/server/routers.md
247
-
248
- ### [CRITICAL] Using type assertions to bypass AppRouter import errors
249
-
250
- Wrong:
251
-
252
- ```ts
253
- const client = createTRPCClient<any>({ links: [httpBatchLink({ url })] });
254
- ```
255
-
256
- Correct:
257
-
258
- ```ts
259
- // Fix the import path or monorepo configuration
260
- import type { AppRouter } from '@myorg/api-types';
261
-
262
- const client = createTRPCClient<AppRouter>({ links: [httpBatchLink({ url })] });
263
- ```
264
-
265
- Casting to `any` or manually recreating the router type destroys end-to-end type safety. Fix the import path or monorepo config instead.
266
-
267
- Source: www/docs/client/vanilla/setup.mdx
268
-
269
- ### [CRITICAL] Using createTRPCProxyClient (renamed in v11)
270
-
271
- Wrong:
272
-
273
- ```ts
274
- import { createTRPCProxyClient } from '@trpc/client';
275
- ```
276
-
277
- Correct:
278
-
279
- ```ts
280
- import { createTRPCClient } from '@trpc/client';
281
- ```
282
-
283
- `createTRPCProxyClient` was renamed to `createTRPCClient` in v11.
284
-
285
- Source: www/docs/client/vanilla/setup.mdx
286
-
287
- ### [CRITICAL] Treating tRPC as a REST API
288
-
289
- Wrong:
290
-
291
- ```ts
292
- fetch('/api/trpc/users/123', { method: 'GET' });
293
- ```
294
-
295
- Correct:
296
-
297
- ```ts
298
- const user = await client.user.byId.query({ id: '123' });
299
- // Raw equivalent: GET /api/trpc/user.byId?input={"id":"123"}
300
- ```
301
-
302
- tRPC uses JSON-RPC over HTTP. Procedures are called by dot-separated name with JSON input, not by REST resource paths.
303
-
304
- Source: www/docs/client/overview.md
305
-
306
- ### [HIGH] HTML error page instead of JSON response
307
-
308
- If you see `couldn't parse JSON, invalid character '<'`, the tRPC endpoint returned an HTML page (404/503) instead of JSON. This means the `url` in your link config is wrong or infrastructure routing is misconfigured -- it is not a tRPC bug. Verify the URL matches your adapter's mount point.
309
-
310
- Source: www/docs/client/vanilla/setup.mdx
311
-
312
- ## See Also
313
-
314
- - `links` -- configure httpBatchLink, httpLink, splitLink, and other link types
315
- - `superjson` -- set up SuperJSON transformer on server and client
316
- - `server-setup` -- define routers, procedures, context, and export AppRouter type
317
- - `react-query-setup` -- use tRPC with TanStack React Query for React applications
@@ -1,301 +0,0 @@
1
- ---
2
- name: links
3
- description: >
4
- Configure the tRPC client link chain: httpLink, httpBatchLink,
5
- httpBatchStreamLink, splitLink, loggerLink, wsLink, createWSClient,
6
- httpSubscriptionLink, unstable_localLink, retryLink. Choose the right
7
- terminating link. Route subscriptions via splitLink. Build custom links
8
- for SOA routing. Link options: url, headers, transformer, maxURLLength,
9
- maxItems, connectionParams, EventSource ponyfill.
10
- type: core
11
- library: trpc
12
- library_version: '11.16.0'
13
- requires:
14
- - client-setup
15
- sources:
16
- - www/docs/client/links/overview.md
17
- - www/docs/client/links/httpLink.md
18
- - www/docs/client/links/httpBatchLink.md
19
- - www/docs/client/links/httpBatchStreamLink.md
20
- - www/docs/client/links/splitLink.mdx
21
- - www/docs/client/links/wsLink.md
22
- - www/docs/client/links/httpSubscriptionLink.md
23
- - www/docs/client/links/localLink.mdx
24
- - www/docs/client/links/loggerLink.md
25
- - packages/client/src/links/
26
- ---
27
-
28
- # tRPC -- Links
29
-
30
- ## Setup
31
-
32
- ```ts
33
- import { createTRPCClient, httpBatchLink, loggerLink } from '@trpc/client';
34
- import type { AppRouter } from './server';
35
-
36
- const client = createTRPCClient<AppRouter>({
37
- links: [
38
- loggerLink(),
39
- httpBatchLink({
40
- url: 'http://localhost:3000/trpc',
41
- }),
42
- ],
43
- });
44
- ```
45
-
46
- The `links` array is a chain: non-terminating links (loggerLink, splitLink, retryLink) forward operations; the chain must end with a terminating link (httpBatchLink, httpLink, httpBatchStreamLink, wsLink, httpSubscriptionLink, unstable_localLink).
47
-
48
- ## Core Patterns
49
-
50
- ### httpBatchLink -- Batch Multiple Calls into One Request
51
-
52
- ```ts
53
- import { createTRPCClient, httpBatchLink } from '@trpc/client';
54
- import type { AppRouter } from './server';
55
-
56
- const client = createTRPCClient<AppRouter>({
57
- links: [
58
- httpBatchLink({
59
- url: 'http://localhost:3000/trpc',
60
- maxURLLength: 2083,
61
- maxItems: 10,
62
- }),
63
- ],
64
- });
65
-
66
- const [post1, post2, post3] = await Promise.all([
67
- client.post.byId.query(1),
68
- client.post.byId.query(2),
69
- client.post.byId.query(3),
70
- ]);
71
- ```
72
-
73
- Concurrent calls are batched into a single HTTP request. Set `maxURLLength` to prevent 414 errors from long URLs.
74
-
75
- ### splitLink -- Route Subscriptions to SSE
76
-
77
- ```ts
78
- import {
79
- createTRPCClient,
80
- httpBatchLink,
81
- httpSubscriptionLink,
82
- splitLink,
83
- } from '@trpc/client';
84
- import type { AppRouter } from './server';
85
-
86
- const client = createTRPCClient<AppRouter>({
87
- links: [
88
- splitLink({
89
- condition: (op) => op.type === 'subscription',
90
- true: httpSubscriptionLink({
91
- url: 'http://localhost:3000/trpc',
92
- }),
93
- false: httpBatchLink({
94
- url: 'http://localhost:3000/trpc',
95
- }),
96
- }),
97
- ],
98
- });
99
- ```
100
-
101
- ### splitLink -- Disable Batching Per-Request via Context
102
-
103
- ```ts
104
- import {
105
- createTRPCClient,
106
- httpBatchLink,
107
- httpLink,
108
- splitLink,
109
- } from '@trpc/client';
110
- import type { AppRouter } from './server';
111
-
112
- const client = createTRPCClient<AppRouter>({
113
- links: [
114
- splitLink({
115
- condition: (op) => Boolean(op.context.skipBatch),
116
- true: httpLink({ url: 'http://localhost:3000/trpc' }),
117
- false: httpBatchLink({ url: 'http://localhost:3000/trpc' }),
118
- }),
119
- ],
120
- });
121
-
122
- const result = await client.post.byId.query(1, {
123
- context: { skipBatch: true },
124
- });
125
- ```
126
-
127
- ### httpBatchStreamLink -- Stream Responses as They Arrive
128
-
129
- ```ts
130
- import { createTRPCClient, httpBatchStreamLink } from '@trpc/client';
131
- import type { AppRouter } from './server';
132
-
133
- const client = createTRPCClient<AppRouter>({
134
- links: [
135
- httpBatchStreamLink({
136
- url: 'http://localhost:3000/trpc',
137
- }),
138
- ],
139
- });
140
-
141
- const iterable = await client.examples.iterable.query();
142
- for await (const value of iterable) {
143
- console.log(value);
144
- }
145
- ```
146
-
147
- ### wsLink -- WebSocket Terminating Link
148
-
149
- ```ts
150
- import { createTRPCClient, createWSClient, wsLink } from '@trpc/client';
151
- import type { AppRouter } from './server';
152
-
153
- const wsClient = createWSClient({
154
- url: 'ws://localhost:3000',
155
- });
156
-
157
- const client = createTRPCClient<AppRouter>({
158
- links: [wsLink<AppRouter>({ client: wsClient })],
159
- });
160
- ```
161
-
162
- ### Custom Link
163
-
164
- ```ts
165
- import { TRPCLink } from '@trpc/client';
166
- import { observable } from '@trpc/server/observable';
167
- import type { AppRouter } from './server';
168
-
169
- export const timingLink: TRPCLink<AppRouter> = () => {
170
- return ({ next, op }) => {
171
- return observable((observer) => {
172
- const start = Date.now();
173
- const unsubscribe = next(op).subscribe({
174
- next(value) {
175
- observer.next(value);
176
- },
177
- error(err) {
178
- console.error(`${op.path} failed in ${Date.now() - start}ms`);
179
- observer.error(err);
180
- },
181
- complete() {
182
- console.log(`${op.path} completed in ${Date.now() - start}ms`);
183
- observer.complete();
184
- },
185
- });
186
- return unsubscribe;
187
- });
188
- };
189
- };
190
- ```
191
-
192
- ## Common Mistakes
193
-
194
- ### [CRITICAL] No terminating link in the chain
195
-
196
- Wrong:
197
-
198
- ```ts
199
- const client = createTRPCClient<AppRouter>({
200
- links: [loggerLink()],
201
- });
202
- ```
203
-
204
- Correct:
205
-
206
- ```ts
207
- const client = createTRPCClient<AppRouter>({
208
- links: [loggerLink(), httpBatchLink({ url: 'http://localhost:3000/trpc' })],
209
- });
210
- ```
211
-
212
- The link chain must end with a terminating link. Without one, tRPC throws "No more links to execute - did you forget to add an ending link?"
213
-
214
- Source: packages/client/src/links/internals/createChain.ts
215
-
216
- ### [CRITICAL] Sending subscriptions through httpLink or httpBatchLink
217
-
218
- Wrong:
219
-
220
- ```ts
221
- const client = createTRPCClient<AppRouter>({
222
- links: [httpBatchLink({ url: 'http://localhost:3000/trpc' })],
223
- });
224
- await client.onMessage.subscribe({});
225
- ```
226
-
227
- Correct:
228
-
229
- ```ts
230
- const client = createTRPCClient<AppRouter>({
231
- links: [
232
- splitLink({
233
- condition: (op) => op.type === 'subscription',
234
- true: httpSubscriptionLink({ url: 'http://localhost:3000/trpc' }),
235
- false: httpBatchLink({ url: 'http://localhost:3000/trpc' }),
236
- }),
237
- ],
238
- });
239
- ```
240
-
241
- httpLink and httpBatchLink throw on subscription operations. Subscriptions must use httpSubscriptionLink or wsLink, routed via splitLink.
242
-
243
- Source: packages/client/src/links/httpLink.ts
244
-
245
- ### [HIGH] httpBatchLink and httpBatchStreamLink headers callback receives { opList }
246
-
247
- `httpBatchLink` and `httpBatchStreamLink` headers callbacks receive `{ opList }` (a `NonEmptyArray<Operation>`), not `{ op }` like `httpLink`. Access per-operation context via `opList[0]?.context`:
248
-
249
- ```ts
250
- httpBatchLink({
251
- url: 'http://localhost:3000/trpc',
252
- headers({ opList }) {
253
- return { authorization: opList[0]?.context.token };
254
- },
255
- });
256
- ```
257
-
258
- `httpBatchLink` headers callback receives `{ opList }` (an array of operations)
259
-
260
- Source: packages/client/src/links/httpBatchLink.ts
261
-
262
- ### [MEDIUM] Default batch limits are Infinity
263
-
264
- Wrong:
265
-
266
- ```ts
267
- httpBatchLink({ url: 'http://localhost:3000/trpc' });
268
- ```
269
-
270
- Correct:
271
-
272
- ```ts
273
- httpBatchLink({
274
- url: 'http://localhost:3000/trpc',
275
- maxURLLength: 2083,
276
- // should be the same or lower than the server's maxBatchSize
277
- maxItems: 10,
278
- });
279
- ```
280
-
281
- Both `maxURLLength` and `maxItems` default to `Infinity`, which can cause 413/414 HTTP errors on servers or CDNs with URL length limits. When the server sets `maxBatchSize`, set `maxItems` to the same or lower value so the client auto-splits batches instead of triggering a `400 Bad Request`.
282
-
283
- Source: packages/client/src/links/httpBatchLink.ts
284
-
285
- ### [HIGH] httpBatchStreamLink data loss on stream completion
286
-
287
- There is a known race condition where buffered chunks can be lost on normal stream completion. Long streaming responses (e.g., LLM output) may be truncated. If you experience truncated data, switch to `httpBatchLink` for those operations.
288
-
289
- Source: https://github.com/trpc/trpc/issues/7209
290
-
291
- ## References
292
-
293
- - [Link options reference](references/link-options.md)
294
-
295
- ## See Also
296
-
297
- - `client-setup` -- create the tRPC client and configure links
298
- - `superjson` -- add transformer to links for Date/Map/Set support
299
- - `subscriptions` -- set up SSE or WebSocket real-time streams
300
- - `non-json-content-types` -- route FormData/binary through splitLink + httpLink
301
- - `service-oriented-architecture` -- build custom routing links for multi-service backends