@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,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
|
-
|
|
23
|
-
|
|
24
|
-
|
|
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
|
-
|
|
18
|
+
<!-- Generated from www/v11/docs/server/subscriptions.md by www/build/skills.ts. Edit the docs instead. -->
|
|
28
19
|
|
|
29
|
-
|
|
20
|
+
# Subscriptions
|
|
30
21
|
|
|
31
|
-
|
|
22
|
+
From https://trpc.io/docs/server/subscriptions
|
|
32
23
|
|
|
33
|
-
|
|
24
|
+
## Introduction
|
|
34
25
|
|
|
35
|
-
|
|
36
|
-
|
|
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
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
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
|
|
58
|
-
|
|
59
|
-
|
|
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
|
-
|
|
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
|
-
|
|
144
|
+
## Subscribing from the client
|
|
79
145
|
|
|
80
|
-
|
|
81
|
-
|
|
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
|
|
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 =
|
|
167
|
+
const subscription = client.onPostAdd.subscribe(
|
|
101
168
|
{ lastEventId: null },
|
|
102
169
|
{
|
|
103
|
-
onData(
|
|
104
|
-
console.log(
|
|
170
|
+
onData(event) {
|
|
171
|
+
console.log(event.id, event.data.title);
|
|
105
172
|
},
|
|
106
173
|
onError(err) {
|
|
107
|
-
console.error(
|
|
174
|
+
console.error(err);
|
|
108
175
|
},
|
|
109
176
|
},
|
|
110
177
|
);
|
|
111
178
|
|
|
112
|
-
//
|
|
113
|
-
|
|
179
|
+
// stop listening
|
|
180
|
+
subscription.unsubscribe();
|
|
114
181
|
```
|
|
115
182
|
|
|
116
|
-
|
|
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
|
-
|
|
185
|
+
## Pull data in a loop
|
|
119
186
|
|
|
120
|
-
|
|
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
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
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
|
-
|
|
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
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
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
|
-
|
|
141
|
-
|
|
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
|
-
|
|
239
|
+
## Stopping a subscription from the server
|
|
148
240
|
|
|
149
|
-
|
|
241
|
+
If you need to stop a subscription from the server, simply `return` in the generator function.
|
|
150
242
|
|
|
151
|
-
```ts
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
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
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
275
|
+
type Post = { id: string; title: string };
|
|
220
276
|
|
|
221
|
-
const
|
|
222
|
-
|
|
223
|
-
|
|
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
|
-
|
|
281
|
+
const ee = new EventEmitter();
|
|
233
282
|
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
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, '
|
|
240
|
-
|
|
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
|
-
|
|
295
|
+
if (timeout) clearTimeout(timeout);
|
|
244
296
|
}
|
|
245
297
|
}),
|
|
246
298
|
});
|
|
247
299
|
```
|
|
248
300
|
|
|
249
|
-
|
|
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
|
-
|
|
303
|
+
Throwing an error in a generator function propagates to `trpc`'s `onError()` on the backend.
|
|
280
304
|
|
|
281
|
-
|
|
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
|
-
|
|
284
|
-
|
|
285
|
-
```ts
|
|
286
|
-
yield tracked('', data);
|
|
287
|
-
```
|
|
307
|
+
## Output validation
|
|
288
308
|
|
|
289
|
-
|
|
309
|
+
Since subscriptions are async iterators, you have to go through the iterator to validate the output.
|
|
290
310
|
|
|
291
|
-
|
|
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
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
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
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
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
|
-
|
|
396
|
+
Now you can use this helper to validate the output of your subscription procedures:
|
|
372
397
|
|
|
373
|
-
```ts
|
|
374
|
-
import {
|
|
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
|
-
|
|
377
|
-
|
|
378
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
441
|
+
## References
|
|
398
442
|
|
|
399
|
-
|
|
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
|
-
##
|
|
447
|
+
## Related skills
|
|
402
448
|
|
|
403
|
-
-
|
|
404
|
-
-
|
|
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`
|