@trpc/server 11.22.2-canary.7.c01346ec8 → 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
@@ -1,84 +1,151 @@
1
1
  ---
2
2
  name: subscriptions
3
- description: >
4
- Set up real-time event streams with async generator subscriptions using
5
- .subscription(async function*() { yield }). SSE via httpSubscriptionLink is
6
- recommended over WebSocket. Use tracked(id, data) from @trpc/server for
7
- reconnection recovery with lastEventId. WebSocket via wsLink and
8
- createWSClient from @trpc/client, applyWSSHandler from @trpc/server/adapters/ws. Configure SSE ping with
9
- initTRPC.create({ sse: { ping: { enabled, intervalMs } } }). AbortSignal
10
- via opts.signal for cleanup. splitLink to route subscriptions.
11
- type: core
12
- library: trpc
13
- library_version: '11.16.0'
3
+ description: "Set up real-time event streams with async generator subscriptions using .subscription(async function*() { yield }). SSE via httpSubscriptionLink is recommended over WebSocket. Use tracked(id, data) from @trpc/server for reconnection recovery with lastEventId. WebSocket via wsLink and createWSClient from @trpc/client, applyWSSHandler from @trpc/server/adapters/ws. Configure SSE ping with initTRPC.create({ sse: { ping: { enabled, intervalMs } } }). AbortSignal via opts.signal for cleanup. splitLink to route subscriptions. Consume them with the client's .subscribe(input, { onData, onError }) and .unsubscribe()."
14
4
  requires:
15
5
  - server-setup
16
6
  - links
17
7
  sources:
18
- - www/docs/server/subscriptions.md
19
- - www/docs/server/websockets.md
20
- - www/docs/client/links/httpSubscriptionLink.md
21
- - www/docs/client/links/wsLink.md
22
- - packages/server/src/unstable-core-do-not-import/stream/sse.ts
23
- - packages/server/src/unstable-core-do-not-import/stream/tracked.ts
24
- - examples/standalone-server/src/server.ts
8
+ - www/v11/docs/server/subscriptions.md
9
+ - www/v11/docs/server/websockets.md
10
+ - www/v11/docs/client/links/httpSubscriptionLink.md
11
+ - www/v11/docs/client/links/wsLink.md
12
+ metadata:
13
+ type: core
14
+ library: trpc
15
+ library_version: 11.23.0
25
16
  ---
26
17
 
27
- # tRPC — Subscriptions
18
+ <!-- Generated from www/v11/docs/server/subscriptions.md by www/build/skills.ts. Edit the docs instead. -->
28
19
 
29
- ## Setup
20
+ # Subscriptions
30
21
 
31
- SSE is recommended for most subscription use cases. It is simpler to set up and does not require a WebSocket server.
22
+ From https://trpc.io/docs/server/subscriptions
32
23
 
33
- ### Server
24
+ ## Introduction
34
25
 
35
- ```ts
36
- // server.ts
26
+ Subscriptions are a type of real-time event stream between the client and server. Use subscriptions when you need to push real-time updates to the client.
27
+
28
+ With tRPC's subscriptions, the client establishes and maintains a persistent connection to the server plus automatically attempts to reconnect and recover gracefully if disconnected with the help of [`tracked()`](https://trpc.io/docs/server/subscriptions#tracked) events.
29
+
30
+ ## WebSockets or Server-sent Events?
31
+
32
+ You can either use WebSockets or [Server-sent Events](https://en.wikipedia.org/wiki/Server-sent_events) (SSE) to setup real-time subscriptions in tRPC.
33
+
34
+ - For WebSockets, see [the WebSockets page](https://trpc.io/docs/server/websockets)
35
+ - For SSE, see the [httpSubscriptionLink](https://trpc.io/docs/client/links/httpSubscriptionLink)
36
+
37
+ If you are unsure which one to use, we recommend using SSE for subscriptions as it's easier to setup and doesn't require setting up a WebSocket server.
38
+
39
+ ## Reference projects
40
+
41
+ | Type | Example Type | Link |
42
+ | ---------- | --------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- |
43
+ | WebSockets | Bare-minimum Node.js WebSockets example | [/examples/standalone-server](https://github.com/trpc/trpc/tree/main/examples/standalone-server) |
44
+ | SSE | Full-stack SSE implementation | [github.com/trpc/examples-tanstack-start-sse-chat](https://github.com/trpc/examples-tanstack-start-sse-chat) |
45
+ | WebSockets | Full-stack WebSockets implementation | [github.com/trpc/examples-next-prisma-websockets-starter](https://github.com/trpc/examples-next-prisma-starter-websockets) |
46
+
47
+ ## Basic example
48
+
49
+ > [!TIP]
50
+ > For a full example, see [our full-stack SSE example](https://github.com/trpc/examples-tanstack-start-sse-chat).
51
+
52
+
53
+ ```ts no-check title="server.ts"
54
+ import EventEmitter, { on } from 'node:events';
55
+ import { initTRPC } from '@trpc/server';
56
+
57
+ const t = initTRPC.create();
58
+
59
+ type Post = { id: string; title: string };
60
+ const ee = new EventEmitter();
61
+
62
+ export const appRouter = t.router({
63
+ onPostAdd: t.procedure.subscription(async function* (opts) {
64
+ // listen for new events
65
+ for await (const [data] of on(ee, 'add', {
66
+ // Passing the AbortSignal from the request automatically cancels the event emitter when the request is aborted
67
+ signal: opts.signal,
68
+ })) {
69
+ const post = data as Post;
70
+ yield post;
71
+ }
72
+ }),
73
+ });
74
+ ```
75
+
76
+ ## Automatic tracking of id using `tracked()` (recommended)
77
+
78
+ 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.
79
+
80
+ You can send an initial `lastEventId` when initializing the subscription and it will be automatically updated as the browser receives data.
81
+
82
+ - For SSE, this is part of the [`EventSource`-spec](https://html.spec.whatwg.org/multipage/server-sent-events.html#the-last-event-id-header) and will be propagated through `lastEventId` in your `.input()`.
83
+ - For WebSockets, our `wsLink` will automatically send the last known ID and update it as the browser receives data.
84
+
85
+ > [!TIP]
86
+ > If you're fetching data based on the `lastEventId`, and capturing all events is critical, make sure you set up the event listener before fetching events from your database as is done in [our full-stack SSE example](https://github.com/trpc/examples-tanstack-start-sse-chat), this can prevent newly emitted events being ignored while yield'ing the original batch based on `lastEventId`.
87
+
88
+
89
+ ```ts no-check
37
90
  import EventEmitter, { on } from 'node:events';
38
91
  import { initTRPC, tracked } from '@trpc/server';
39
- import { createHTTPServer } from '@trpc/server/adapters/standalone';
40
92
  import { z } from 'zod';
41
93
 
42
- const t = initTRPC.create({
43
- sse: {
44
- ping: {
45
- enabled: true,
46
- intervalMs: 2000,
47
- },
48
- client: {
49
- reconnectAfterInactivityMs: 5000,
50
- },
51
- },
52
- });
94
+ class IterableEventEmitter extends EventEmitter {
95
+ toIterable(eventName: string, opts?: { signal?: AbortSignal }) {
96
+ return on(this, eventName, opts);
97
+ }
98
+ }
53
99
 
54
100
  type Post = { id: string; title: string };
55
- const ee = new EventEmitter();
56
101
 
57
- const appRouter = t.router({
58
- onPostAdd: t.procedure
59
- .input(z.object({ lastEventId: z.string().nullish() }).optional())
102
+ const t = initTRPC.create();
103
+ const publicProcedure = t.procedure;
104
+ const router = t.router;
105
+
106
+ const ee = new IterableEventEmitter();
107
+
108
+ export const subRouter = router({
109
+ onPostAdd: publicProcedure
110
+ .input(
111
+ z
112
+ .object({
113
+ // lastEventId is the last event id that the client has received
114
+ // On the first call, it will be whatever was passed in the initial setup
115
+ // If the client reconnects, it will be the last event id that the client received
116
+ lastEventId: z.string().nullish(),
117
+ })
118
+ .optional(),
119
+ )
60
120
  .subscription(async function* (opts) {
61
- for await (const [data] of on(ee, 'add', { signal: opts.signal })) {
121
+ // We start by subscribing to the ee so that we don't miss any new events while fetching
122
+ const iterable = ee.toIterable('add', {
123
+ // Passing the AbortSignal from the request automatically cancels the event emitter when the request is aborted
124
+ signal: opts.signal,
125
+ });
126
+
127
+ if (opts.input?.lastEventId) {
128
+ // [...] get the posts since the last event id and yield them
129
+ // const items = await db.post.findMany({ ... })
130
+ // for (const item of items) {
131
+ // yield tracked(item.id, item);
132
+ // }
133
+ }
134
+ // listen for new events from the iterable we set up above
135
+ for await (const [data] of iterable) {
62
136
  const post = data as Post;
137
+ // tracking the post id ensures the client can reconnect at any time and get the latest events since this id
63
138
  yield tracked(post.id, post);
64
139
  }
65
140
  }),
66
141
  });
67
-
68
- export type AppRouter = typeof appRouter;
69
-
70
- createHTTPServer({
71
- router: appRouter,
72
- createContext() {
73
- return {};
74
- },
75
- }).listen(3000);
76
142
  ```
77
143
 
78
- ### Client (SSE)
144
+ ## Subscribing from the client
79
145
 
80
- ```ts
81
- // client.ts
146
+ Route subscriptions to [`httpSubscriptionLink`](https://trpc.io/docs/client/links/httpSubscriptionLink) (SSE) or [`wsLink`](https://trpc.io/docs/client/links/wsLink) with a [`splitLink`](https://trpc.io/docs/client/links/splitLink), then call `.subscribe()` with the input and your callbacks. Tracked events arrive in `onData` as `{ id, data }`.
147
+
148
+ ```ts no-check title="client.ts"
82
149
  import {
83
150
  createTRPCClient,
84
151
  httpBatchLink,
@@ -87,7 +154,7 @@ import {
87
154
  } from '@trpc/client';
88
155
  import type { AppRouter } from './server';
89
156
 
90
- const trpc = createTRPCClient<AppRouter>({
157
+ const client = createTRPCClient<AppRouter>({
91
158
  links: [
92
159
  splitLink({
93
160
  condition: (op) => op.type === 'subscription',
@@ -97,310 +164,287 @@ const trpc = createTRPCClient<AppRouter>({
97
164
  ],
98
165
  });
99
166
 
100
- const subscription = trpc.onPostAdd.subscribe(
167
+ const subscription = client.onPostAdd.subscribe(
101
168
  { lastEventId: null },
102
169
  {
103
- onData(post) {
104
- console.log('New post:', post);
170
+ onData(event) {
171
+ console.log(event.id, event.data.title);
105
172
  },
106
173
  onError(err) {
107
- console.error('Subscription error:', err);
174
+ console.error(err);
108
175
  },
109
176
  },
110
177
  );
111
178
 
112
- // To stop:
113
- // subscription.unsubscribe();
179
+ // stop listening
180
+ subscription.unsubscribe();
114
181
  ```
115
182
 
116
- ## Core Patterns
183
+ For React, see [`subscriptionOptions`](https://trpc.io/docs/client/tanstack-react-query/usage#subscriptionOptions) with TanStack React Query, or the classic [`useSubscription()`](https://trpc.io/docs/client/react/useSubscription).
117
184
 
118
- ### tracked() for reconnection recovery
185
+ ## Pull data in a loop
119
186
 
120
- ```ts
121
- import EventEmitter, { on } from 'node:events';
122
- import { initTRPC, tracked } from '@trpc/server';
123
- import { z } from 'zod';
187
+ This recipe is useful when you want to periodically check for new data from a source like a database and push it to the client.
124
188
 
125
- const t = initTRPC.create();
126
- const ee = new EventEmitter();
127
-
128
- const appRouter = t.router({
129
- onPostAdd: t.procedure
130
- .input(z.object({ lastEventId: z.string().nullish() }).optional())
189
+ ```ts no-check title="server.ts"
190
+ import { tracked } from '@trpc/server';
191
+ import { z } from 'zod';
192
+ import { publicProcedure, router } from './trpc';
193
+
194
+ export const subRouter = router({
195
+ onPostAdd: publicProcedure
196
+ .input(
197
+ z.object({
198
+ // lastEventId is the last event id that the client has received
199
+ // On the first call, it will be whatever was passed in the initial setup
200
+ // If the client reconnects, it will be the last event id that the client received
201
+ // The id is the createdAt of the post
202
+ lastEventId: z.coerce.date().nullish(),
203
+ }),
204
+ )
131
205
  .subscription(async function* (opts) {
132
- const iterable = on(ee, 'add', { signal: opts.signal });
206
+ // `opts.signal` is an AbortSignal that will be aborted when the client disconnects.
207
+ let lastEventId = opts.input?.lastEventId ?? null;
208
+
209
+ // We use a `while` loop that checks `!opts.signal.aborted`
210
+ while (!opts.signal!.aborted) {
211
+ const posts = await db.post.findMany({
212
+ // If we have a `lastEventId`, we only fetch posts created after it.
213
+ where: lastEventId
214
+ ? {
215
+ createdAt: {
216
+ gt: lastEventId,
217
+ },
218
+ }
219
+ : undefined,
220
+ orderBy: {
221
+ createdAt: 'asc',
222
+ },
223
+ });
133
224
 
134
- if (opts.input?.lastEventId) {
135
- // Fetch and yield events since lastEventId from your database
136
- // const missed = await db.post.findMany({ where: { id: { gt: opts.input.lastEventId } } });
137
- // for (const post of missed) { yield tracked(post.id, post); }
138
- }
225
+ for (const post of posts) {
226
+ // `tracked` is a helper that sends an `id` with each event.
227
+ // This allows the client to resume from the last received event upon reconnection.
228
+ yield tracked(post.createdAt.toJSON(), post);
229
+ lastEventId = post.createdAt;
230
+ }
139
231
 
140
- for await (const [data] of iterable) {
141
- yield tracked(data.id, data);
232
+ // Wait for a bit before polling again to avoid hammering the database.
233
+ await sleep(1_000);
142
234
  }
143
235
  }),
144
236
  });
145
237
  ```
146
238
 
147
- When using `tracked(id, data)`, the client automatically sends `lastEventId` on reconnection. For SSE this is part of the EventSource spec; for WebSocket, `wsLink` handles it.
239
+ ## Stopping a subscription from the server
148
240
 
149
- ### Polling loop subscription
241
+ If you need to stop a subscription from the server, simply `return` in the generator function.
150
242
 
151
- ```ts
152
- import { initTRPC, tracked } from '@trpc/server';
153
- import { z } from 'zod';
154
-
155
- const t = initTRPC.create();
156
-
157
- const appRouter = t.router({
158
- onNewItems: t.procedure
159
- .input(z.object({ lastEventId: z.coerce.date().nullish() }))
243
+ ```ts no-check
244
+ export const subRouter = router({
245
+ onPostAdd: publicProcedure
246
+ .input(
247
+ z.object({
248
+ lastEventId: z.coerce.number().min(0).optional(),
249
+ }),
250
+ )
160
251
  .subscription(async function* (opts) {
161
- let cursor = opts.input?.lastEventId ?? null;
162
-
163
- while (!opts.signal?.aborted) {
164
- const items = await db.item.findMany({
165
- where: cursor ? { createdAt: { gt: cursor } } : undefined,
166
- orderBy: { createdAt: 'asc' },
167
- });
168
-
169
- for (const item of items) {
170
- yield tracked(item.createdAt.toJSON(), item);
171
- cursor = item.createdAt;
252
+ let index = opts.input.lastEventId ?? 0;
253
+ while (!opts.signal!.aborted) {
254
+ const idx = index++;
255
+ if (idx > 100) {
256
+ // With this, the subscription will stop and the client will disconnect
257
+ return;
172
258
  }
173
-
174
- await new Promise((r) => setTimeout(r, 1000));
259
+ await new Promise((resolve) => setTimeout(resolve, 10));
175
260
  }
176
261
  }),
177
262
  });
178
263
  ```
179
264
 
180
- ### WebSocket setup (when bidirectional communication is required)
181
-
182
- ```ts
183
- // server
184
- import { applyWSSHandler } from '@trpc/server/adapters/ws';
185
- import { WebSocketServer } from 'ws';
186
- import { appRouter } from './router';
265
+ On the client, you just `.unsubscribe()` the subscription.
187
266
 
188
- const wss = new WebSocketServer({ port: 3001 });
189
- const handler = applyWSSHandler({
190
- wss,
191
- router: appRouter,
192
- createContext() {
193
- return {};
194
- },
195
- keepAlive: {
196
- enabled: true,
197
- pingMs: 30000,
198
- pongWaitMs: 5000,
199
- },
200
- });
267
+ ## Cleanup of side effects
201
268
 
202
- process.on('SIGTERM', () => {
203
- handler.broadcastReconnectNotification();
204
- wss.close();
205
- });
206
- ```
269
+ If you need to clean up any side-effects of your subscription you can use the [`try...finally`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Generator/return#using_return_with_try...finally) pattern, as `trpc` invokes the `.return()` of the Generator Instance when the subscription stops for any reason.
207
270
 
208
- ```ts
209
- // client
210
- import {
211
- createTRPCClient,
212
- createWSClient,
213
- httpBatchLink,
214
- splitLink,
215
- wsLink,
216
- } from '@trpc/client';
217
- import type { AppRouter } from './server';
271
+ ```ts no-check
272
+ import EventEmitter, { on } from 'events';
273
+ import { initTRPC } from '@trpc/server';
218
274
 
219
- const wsClient = createWSClient({ url: 'ws://localhost:3001' });
275
+ type Post = { id: string; title: string };
220
276
 
221
- const trpc = createTRPCClient<AppRouter>({
222
- links: [
223
- splitLink({
224
- condition: (op) => op.type === 'subscription',
225
- true: wsLink({ client: wsClient }),
226
- false: httpBatchLink({ url: 'http://localhost:3000' }),
227
- }),
228
- ],
229
- });
230
- ```
277
+ const t = initTRPC.create();
278
+ const publicProcedure = t.procedure;
279
+ const router = t.router;
231
280
 
232
- ### Cleanup with try...finally
281
+ const ee = new EventEmitter();
233
282
 
234
- ```ts
235
- const appRouter = t.router({
236
- events: t.procedure.subscription(async function* (opts) {
237
- const cleanup = registerListener();
283
+ export const subRouter = router({
284
+ onPostAdd: publicProcedure.subscription(async function* (opts) {
285
+ let timeout: ReturnType<typeof setTimeout> | undefined;
238
286
  try {
239
- for await (const [data] of on(ee, 'event', { signal: opts.signal })) {
240
- yield data;
287
+ for await (const [data] of on(ee, 'add', {
288
+ signal: opts.signal,
289
+ })) {
290
+ timeout = setTimeout(() => console.log('Pretend like this is useful'));
291
+ const post = data as Post;
292
+ yield post;
241
293
  }
242
294
  } finally {
243
- cleanup();
295
+ if (timeout) clearTimeout(timeout);
244
296
  }
245
297
  }),
246
298
  });
247
299
  ```
248
300
 
249
- tRPC invokes `.return()` on the generator when the subscription stops, triggering the `finally` block.
250
-
251
- ## Common Mistakes
252
-
253
- ### HIGH Using Observable instead of async generator
254
-
255
- Wrong:
256
-
257
- ```ts
258
- import { observable } from '@trpc/server/observable';
259
-
260
- t.procedure.subscription(({ input }) => {
261
- return observable((emit) => {
262
- emit.next(data);
263
- });
264
- });
265
- ```
266
-
267
- Correct:
268
-
269
- ```ts
270
- t.procedure.subscription(async function* ({ input, signal }) {
271
- for await (const [data] of on(ee, 'event', { signal })) {
272
- yield data;
273
- }
274
- });
275
- ```
276
-
277
- Observable subscriptions are deprecated and will be removed in v12. Use async generator syntax (`async function*`).
301
+ ## Error handling
278
302
 
279
- Source: packages/server/src/unstable-core-do-not-import/procedureBuilder.ts
303
+ Throwing an error in a generator function propagates to `trpc`'s `onError()` on the backend.
280
304
 
281
- ### MEDIUM Empty string as tracked event ID
305
+ If the error thrown is a 5xx error, the client will automatically attempt to reconnect based on the last event id that is [tracked using `tracked()`](https://trpc.io/docs/server/subscriptions#tracked). For other errors, the subscription will be cancelled and propagate to the `onError()` callback.
282
306
 
283
- Wrong:
284
-
285
- ```ts
286
- yield tracked('', data);
287
- ```
307
+ ## Output validation
288
308
 
289
- Correct:
309
+ Since subscriptions are async iterators, you have to go through the iterator to validate the output.
290
310
 
291
- ```ts
292
- yield tracked(event.id.toString(), data);
293
- ```
294
-
295
- `tracked()` throws if the ID is an empty string because it conflicts with SSE "no id" semantics.
296
-
297
- Source: packages/server/src/unstable-core-do-not-import/stream/tracked.ts
298
-
299
- ### HIGH Fetching history before setting up event listener
300
-
301
- Wrong:
302
-
303
- ```ts
304
- t.procedure.subscription(async function* (opts) {
305
- const history = await db.getEvents(); // events may fire here and be lost
306
- yield* history;
307
- for await (const event of listener) {
308
- yield event;
309
- }
310
- });
311
- ```
311
+ ### Example with Zod v4
312
312
 
313
- Correct:
314
-
315
- ```ts
316
- t.procedure.subscription(async function* (opts) {
317
- const iterable = on(ee, 'event', { signal: opts.signal }); // listen first
318
- const history = await db.getEvents();
319
- for (const item of history) {
320
- yield tracked(item.id, item);
321
- }
322
- for await (const [event] of iterable) {
323
- yield tracked(event.id, event);
324
- }
325
- });
326
- ```
327
-
328
- If you fetch historical data before setting up the event listener, events emitted between the fetch and listener setup are lost.
329
-
330
- Source: www/docs/server/subscriptions.md
331
-
332
- ### MEDIUM SSE ping interval >= client reconnect interval
333
-
334
- Wrong:
335
-
336
- ```ts
337
- initTRPC.create({
338
- sse: {
339
- ping: { enabled: true, intervalMs: 10000 },
340
- client: { reconnectAfterInactivityMs: 5000 },
341
- },
342
- });
343
- ```
344
-
345
- Correct:
346
-
347
- ```ts
348
- initTRPC.create({
349
- sse: {
350
- ping: { enabled: true, intervalMs: 2000 },
351
- client: { reconnectAfterInactivityMs: 5000 },
352
- },
353
- });
354
- ```
355
-
356
- If the server ping interval is >= the client reconnect timeout, the client disconnects thinking the connection is dead before receiving a ping.
357
-
358
- Source: packages/server/src/unstable-core-do-not-import/stream/sse.ts
359
-
360
- ### HIGH Sending custom headers with SSE without EventSource polyfill
361
-
362
- Wrong:
313
+ ```ts no-check title="zAsyncIterable.ts"
314
+ import type { TrackedEnvelope } from '@trpc/server';
315
+ import { isTrackedEnvelope, tracked } from '@trpc/server';
316
+ import { z } from 'zod';
363
317
 
364
- ```ts
365
- httpSubscriptionLink({
366
- url: 'http://localhost:3000',
367
- // Native EventSource does not support custom headers
368
- });
318
+ function isAsyncIterable<TValue, TReturn = unknown>(
319
+ value: unknown,
320
+ ): value is AsyncIterable<TValue, TReturn> {
321
+ return !!value && typeof value === 'object' && Symbol.asyncIterator in value;
322
+ }
323
+ const trackedEnvelopeSchema =
324
+ z.custom<TrackedEnvelope<unknown>>(isTrackedEnvelope);
325
+
326
+ /**
327
+ * A Zod schema helper designed specifically for validating async iterables. This schema ensures that:
328
+ * 1. The value being validated is an async iterable.
329
+ * 2. Each item yielded by the async iterable conforms to a specified type.
330
+ * 3. The return value of the async iterable, if any, also conforms to a specified type.
331
+ */
332
+ export function zAsyncIterable<
333
+ TYieldIn,
334
+ TYieldOut,
335
+ TReturnIn = void,
336
+ TReturnOut = void,
337
+ Tracked extends boolean = false,
338
+ >(opts: {
339
+ /**
340
+ * Validate the value yielded by the async generator
341
+ */
342
+ yield: z.ZodType<TYieldOut, TYieldIn>;
343
+ /**
344
+ * Validate the return value of the async generator
345
+ * @remarks not applicable for subscriptions
346
+ */
347
+ return?: z.ZodType<TReturnOut, TReturnIn>;
348
+ /**
349
+ * Whether the yielded values are tracked
350
+ * @remarks only applicable for subscriptions
351
+ */
352
+ tracked?: Tracked;
353
+ }) {
354
+ return z
355
+ .custom<
356
+ AsyncIterable<
357
+ Tracked extends true ? TrackedEnvelope<TYieldIn> : TYieldIn,
358
+ TReturnIn
359
+ >
360
+ >((val) => isAsyncIterable(val))
361
+ .transform(async function* (iter) {
362
+ const iterator = iter[Symbol.asyncIterator]();
363
+
364
+ try {
365
+ let next;
366
+ while ((next = await iterator.next()) && !next.done) {
367
+ if (opts.tracked) {
368
+ const [id, data] = trackedEnvelopeSchema.parse(next.value);
369
+ yield tracked(id, await opts.yield.parseAsync(data));
370
+ continue;
371
+ }
372
+ yield opts.yield.parseAsync(next.value);
373
+ }
374
+ if (opts.return) {
375
+ return await opts.return.parseAsync(next.value);
376
+ }
377
+ return;
378
+ } finally {
379
+ await iterator.return?.();
380
+ }
381
+ }) as z.ZodType<
382
+ AsyncIterable<
383
+ Tracked extends true ? TrackedEnvelope<TYieldIn> : TYieldIn,
384
+ TReturnIn,
385
+ unknown
386
+ >,
387
+ AsyncIterable<
388
+ Tracked extends true ? TrackedEnvelope<TYieldOut> : TYieldOut,
389
+ TReturnOut,
390
+ unknown
391
+ >
392
+ >;
393
+ }
369
394
  ```
370
395
 
371
- Correct:
396
+ Now you can use this helper to validate the output of your subscription procedures:
372
397
 
373
- ```ts
374
- import { EventSourcePolyfill } from 'event-source-polyfill';
398
+ ```ts no-check title="_app.ts"
399
+ import { tracked } from '@trpc/server';
400
+ import { z } from 'zod';
401
+ import { publicProcedure, router } from './trpc';
402
+ import { zAsyncIterable } from './zAsyncIterable';
403
+
404
+ export const appRouter = router({
405
+ mySubscription: publicProcedure
406
+ .input(
407
+ z.object({
408
+ lastEventId: z.coerce.number().min(0).optional(),
409
+ }),
410
+ )
411
+ .output(
412
+ zAsyncIterable({
413
+ yield: z.object({
414
+ count: z.number(),
415
+ }),
416
+ tracked: true,
417
+ }),
418
+ )
419
+ .subscription(async function* (opts) {
420
+ let index = opts.input.lastEventId ?? 0;
421
+ while (true) {
422
+ index++;
423
+ yield tracked(String(index), {
424
+ count: index,
425
+ });
375
426
 
376
- httpSubscriptionLink({
377
- url: 'http://localhost:3000',
378
- EventSource: EventSourcePolyfill,
379
- eventSourceOptions: async () => ({
380
- headers: { authorization: 'Bearer token' },
381
- }),
427
+ await new Promise((resolve) => setTimeout(resolve, 1000));
428
+ }
429
+ }),
382
430
  });
383
431
  ```
384
432
 
385
- The native EventSource API does not support custom headers. Use an EventSource polyfill and pass it via the `EventSource` option on `httpSubscriptionLink`.
386
-
387
- Source: www/docs/client/links/httpSubscriptionLink.md
388
-
389
- ### MEDIUM Choosing WebSocket when SSE would suffice
390
-
391
- SSE (`httpSubscriptionLink`) is recommended for most subscription use cases. WebSockets add complexity (connection management, reconnection, keepalive, separate server process). Only use `wsLink` when bidirectional communication or WebSocket-specific features are required.
392
-
393
- Source: maintainer interview
433
+ ## Common mistakes
394
434
 
395
- ### MEDIUM WebSocket subscription stale inputs on reconnect
435
+ - **Not passing `opts.signal` on.** Pass it to what you're waiting on, like `on(ee, 'add', { signal: opts.signal })`, or check `opts.signal.aborted` in loops. Otherwise your generator can keep waiting, with its listeners attached, after the client is gone.
436
+ - **Fetching missed events before listening for new ones.** Events emitted in between are lost. Start listening first, as in the [`tracked()` example](https://trpc.io/docs/server/subscriptions#tracked).
437
+ - **Tracking an event with an empty id.** `tracked('', data)` throws, since an empty id means "no id" in SSE.
438
+ - **Returning an `observable()`.** Observable subscriptions are deprecated and will be removed in v12. Use an async generator.
439
+ - **Pinging less often than the client reconnects.** With SSE, keep `sse.ping.intervalMs` lower than `sse.client.reconnectAfterInactivityMs`, or the client reconnects between pings. tRPC throws when the ping interval is the longer one. See [Server Ping Configuration](https://trpc.io/docs/client/links/httpSubscriptionLink#server-ping).
396
440
 
397
- When a WebSocket reconnects, subscriptions re-send the original input parameters. There is no hook to re-evaluate inputs on reconnect, which can cause stale data. Consider using `tracked()` with `lastEventId` to mitigate this.
441
+ ## References
398
442
 
399
- Source: https://github.com/trpc/trpc/issues/4122
443
+ - [WebSockets](references/server-websockets.md)
444
+ - [HTTP Subscription Link](references/client-links-httpSubscriptionLink.md): A terminating link for subscriptions over Server-sent Events
445
+ - [WebSocket Link](references/client-links-wsLink.md): A terminating link that sends tRPC operations over a WebSocket
400
446
 
401
- ## See Also
447
+ ## Related skills
402
448
 
403
- - **links** -- `splitLink`, `httpSubscriptionLink`, `wsLink`, `httpBatchLink`
404
- - **auth** -- authenticating subscription connections (connectionParams, cookies, EventSource polyfill headers)
405
- - **server-setup** -- `initTRPC.create()` SSE configuration options
406
- - **adapter-fastify** -- WebSocket subscriptions via `@fastify/websocket` and `useWSS`
449
+ - `server-setup` (https://trpc.io/docs/server/overview): `npx @tanstack/intent@latest load @trpc/server#server-setup`
450
+ - `links` (https://trpc.io/docs/client/links): `npx @tanstack/intent@latest load @trpc/client#links`