@trpc/client 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.
- package/README.md +0 -8
- package/dist/TRPCClientError-CxFRO7Js.mjs.map +1 -1
- package/dist/{httpBatchLink-DO3WQoxu.cjs → httpBatchLink-Cmao5uUF.cjs} +1 -1
- package/dist/{httpBatchLink-BMtWxLJV.mjs → httpBatchLink-DPypDRI1.mjs} +2 -2
- package/dist/httpBatchLink-DPypDRI1.mjs.map +1 -0
- package/dist/{httpLink-Tm93WWFA.mjs → httpLink--yqaZ9lA.mjs} +2 -2
- package/dist/{httpLink-Tm93WWFA.mjs.map → httpLink--yqaZ9lA.mjs.map} +1 -1
- package/dist/{httpLink-MDJTSlpi.cjs → httpLink-B6E1HSLY.cjs} +1 -1
- package/dist/{httpUtils-CB_100ND.mjs → httpUtils-CAZsqwOQ.mjs} +3 -2
- package/dist/httpUtils-CAZsqwOQ.mjs.map +1 -0
- package/dist/{httpUtils-cggqcHz0.cjs → httpUtils-CrSF2CZF.cjs} +2 -1
- package/dist/index.cjs +13 -7
- package/dist/index.d.cts +8 -3
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +8 -3
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +13 -8
- package/dist/index.mjs.map +1 -1
- package/dist/links/httpBatchLink.cjs +1 -1
- package/dist/links/httpBatchLink.mjs +1 -1
- package/dist/links/httpLink.cjs +1 -1
- package/dist/links/httpLink.mjs +1 -1
- package/dist/links/wsLink/wsLink.cjs +1 -1
- package/dist/links/wsLink/wsLink.mjs +1 -1
- package/dist/types-BxbMkv6C.d.cts.map +1 -1
- package/dist/types-CAPs7vhA.d.mts.map +1 -1
- package/dist/{wsLink-Bm5LKL6z.mjs → wsLink--7trqYPG.mjs} +2 -1
- package/dist/wsLink--7trqYPG.mjs.map +1 -0
- package/dist/wsLink-C3hsDLsL.d.cts.map +1 -1
- package/dist/{wsLink-CKAsNP9P.cjs → wsLink-CQGBu_VZ.cjs} +1 -0
- package/dist/wsLink-DnvK9sTv.d.mts.map +1 -1
- package/package.json +10 -21
- package/skills/client-setup/SKILL.md +240 -207
- package/skills/links/SKILL.md +98 -224
- package/skills/links/references/client-links-httpBatchLink.md +210 -0
- package/skills/links/references/client-links-httpBatchStreamLink.md +159 -0
- package/skills/links/references/client-links-httpLink.md +63 -0
- package/skills/links/references/client-links-httpSubscriptionLink.md +404 -0
- package/skills/links/references/client-links-localLink.md +78 -0
- package/skills/links/references/client-links-loggerLink.md +66 -0
- package/skills/links/references/client-links-retryLink.md +89 -0
- package/skills/links/references/client-links-splitLink.md +103 -0
- package/skills/links/references/client-links-wsLink.md +122 -0
- package/skills/superjson/SKILL.md +132 -183
- package/src/TRPCClientError.ts +2 -2
- package/src/createTRPCClient.ts +1 -1
- package/src/getFetch.ts +0 -1
- package/src/internals/dataLoader.ts +1 -1
- package/src/links/httpBatchStreamLink.ts +1 -1
- package/src/links/internals/httpUtils.ts +6 -1
- package/src/links/localLink.ts +10 -4
- package/src/links/types.ts +2 -1
- package/src/links/wsLink/wsClient/utils.ts +1 -1
- package/src/links/wsLink/wsClient/wsClient.ts +4 -0
- package/bin/intent.js +0 -20
- package/dist/httpBatchLink-BMtWxLJV.mjs.map +0 -1
- package/dist/httpUtils-CB_100ND.mjs.map +0 -1
- package/dist/wsLink-Bm5LKL6z.mjs.map +0 -1
- package/skills/links/references/link-options.md +0 -248
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
# HTTP Batch Stream Link
|
|
2
|
+
|
|
3
|
+
> A terminating link that batches tRPC calls and streams each response as soon as it is ready
|
|
4
|
+
|
|
5
|
+
From https://trpc.io/docs/client/links/httpBatchStreamLink
|
|
6
|
+
|
|
7
|
+
`httpBatchStreamLink` is a [**terminating link**](https://trpc.io/docs/client/links#the-terminating-link) that batches an array of individual tRPC operations into a single HTTP request that's sent to a single tRPC procedure (equivalent to [`httpBatchLink`](https://trpc.io/docs/client/links/httpBatchLink)), but doesn't wait for all the responses of the batch to be ready and streams the responses as soon as any data is available.
|
|
8
|
+
|
|
9
|
+
## Options
|
|
10
|
+
|
|
11
|
+
Options are identical to [`httpBatchLink options`](https://trpc.io/docs/client/links/httpBatchLink#options), with the following addition:
|
|
12
|
+
|
|
13
|
+
| Option | Type | Default | Description |
|
|
14
|
+
| -------------- | ----------------------------- | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
15
|
+
| `streamHeader` | `'trpc-accept'` \| `'accept'` | `'trpc-accept'` | Which header to use to signal the server that the client wants a streaming response. `'accept'` uses the standard `Accept` header instead of the custom `trpc-accept` header, which can avoid CORS preflight for cross-origin streaming queries since `Accept` is a CORS-safelisted header. |
|
|
16
|
+
|
|
17
|
+
## Usage
|
|
18
|
+
|
|
19
|
+
> All usage and options are identical to [`httpBatchLink`](https://trpc.io/docs/client/links/httpBatchLink).
|
|
20
|
+
|
|
21
|
+
> [!NOTE]
|
|
22
|
+
> If you require the ability to change/set response headers (which includes cookies) from within your procedures, make sure to use `httpBatchLink` instead! This is due to the fact that `httpBatchStreamLink` does not support setting headers once the stream has begun. [Read more](https://trpc.io/docs/client/links/httpBatchLink).
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
You can import and add the `httpBatchStreamLink` to the `links` array as such:
|
|
26
|
+
|
|
27
|
+
```ts no-check title="client/index.ts"
|
|
28
|
+
import { createTRPCClient, httpBatchStreamLink } from '@trpc/client';
|
|
29
|
+
import type { AppRouter } from './server';
|
|
30
|
+
|
|
31
|
+
const client = createTRPCClient<AppRouter>({
|
|
32
|
+
links: [
|
|
33
|
+
httpBatchStreamLink({
|
|
34
|
+
url: 'http://localhost:3000',
|
|
35
|
+
}),
|
|
36
|
+
],
|
|
37
|
+
});
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
After that, you can make use of batching by setting all your procedures in a `Promise.all`. The code below will produce exactly **one** HTTP request and on the server exactly **one** database query:
|
|
41
|
+
|
|
42
|
+
```ts no-check
|
|
43
|
+
const somePosts = await Promise.all([
|
|
44
|
+
trpc.post.byId.query(1),
|
|
45
|
+
trpc.post.byId.query(2),
|
|
46
|
+
trpc.post.byId.query(3),
|
|
47
|
+
]);
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
## Streaming mode
|
|
51
|
+
|
|
52
|
+
When batching requests together, the behavior of a regular `httpBatchLink` is to wait for all requests to finish before sending the response. If you want to send responses as soon as they are ready, you can use `httpBatchStreamLink` instead. This is useful for long-running requests.
|
|
53
|
+
|
|
54
|
+
```ts no-check title="client/index.ts"
|
|
55
|
+
import { createTRPCClient, httpBatchStreamLink } from '@trpc/client';
|
|
56
|
+
import type { AppRouter } from './server';
|
|
57
|
+
|
|
58
|
+
const client = createTRPCClient<AppRouter>({
|
|
59
|
+
links: [
|
|
60
|
+
httpBatchStreamLink({
|
|
61
|
+
url: 'http://localhost:3000',
|
|
62
|
+
}),
|
|
63
|
+
],
|
|
64
|
+
});
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
Compared to a regular `httpBatchLink`, a `httpBatchStreamLink` will:
|
|
68
|
+
|
|
69
|
+
- Cause the requests to be sent with a `trpc-accept: application/jsonl` header (or `Accept: application/jsonl` when using `streamHeader: 'accept'`)
|
|
70
|
+
- Cause the response to be sent with `transfer-encoding: chunked` and `content-type: application/json` by default. You can set the streamed response `content-type` to `application/jsonl`, `application/x-ndjson`, or another value on the server via `initTRPC.create({ jsonl: { contentType: ... } })`.
|
|
71
|
+
- Remove the `data` key from the argument object passed to `responseMeta` (because with a streamed response, the headers are sent before the data is available)
|
|
72
|
+
|
|
73
|
+
## Async generators and deferred promises
|
|
74
|
+
|
|
75
|
+
You can try this out on the homepage of tRPC.io: [https://trpc.io/?try=minimal#try-it-out](https://trpc.io/?try=minimal#try-it-out)
|
|
76
|
+
|
|
77
|
+
```ts no-check
|
|
78
|
+
import { createTRPCClient, httpBatchStreamLink } from '@trpc/client';
|
|
79
|
+
import type { AppRouter } from './server';
|
|
80
|
+
|
|
81
|
+
const trpc = createTRPCClient<AppRouter>({
|
|
82
|
+
links: [
|
|
83
|
+
httpBatchStreamLink({
|
|
84
|
+
url: 'http://localhost:3000',
|
|
85
|
+
}),
|
|
86
|
+
],
|
|
87
|
+
});
|
|
88
|
+
const iterable = await trpc.examples.iterable.query();
|
|
89
|
+
|
|
90
|
+
for await (const value of iterable) {
|
|
91
|
+
console.log('Iterable:', value);
|
|
92
|
+
}
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
## Compatibility (client-side)
|
|
96
|
+
|
|
97
|
+
### Browsers
|
|
98
|
+
|
|
99
|
+
Browser support should be identical to [`fetch`](https://caniuse.com/fetch) support.
|
|
100
|
+
|
|
101
|
+
### Node.js / Deno
|
|
102
|
+
|
|
103
|
+
For runtimes other than the browser ones, the `fetch` implementation should support streaming, meaning that the response obtained by `await fetch(...)` should have a `body` property of type `ReadableStream<Uint8Array> | NodeJS.ReadableStream`, meaning that:
|
|
104
|
+
|
|
105
|
+
- either `response.body.getReader` is a function that returns a `ReadableStreamDefaultReader<Uint8Array>` object
|
|
106
|
+
- or `response.body` is a `Uint8Array` `Buffer`
|
|
107
|
+
|
|
108
|
+
This includes support for `undici`, `node-fetch`, native Node.js fetch implementation, and WebAPI fetch implementation (browsers).
|
|
109
|
+
|
|
110
|
+
### React Native
|
|
111
|
+
|
|
112
|
+
Receiving the stream relies on the `TextDecoder` and `TextDecoderStream` APIs, which are not available in React Native. It's important to note that if your `TextDecoderStream` polyfill does not automatically polyfill `ReadableStream` and `WritableStream` those will also need to be polyfilled. If you still want to enable streaming, you need to polyfill those.
|
|
113
|
+
|
|
114
|
+
You will also need to override the default fetch in the `httpBatchStreamLink` configuration options with one that can stream. In the below example we will be using [`react-native-fetch-api`](https://github.com/react-native-community/fetch), which streams text when you pass its `reactNative` option. On Expo, you can pass `fetch` from [`expo/fetch`](https://docs.expo.dev/versions/latest/sdk/expo/) instead, which streams without extra options.
|
|
115
|
+
|
|
116
|
+
```ts
|
|
117
|
+
import { httpBatchStreamLink } from '@trpc/client';
|
|
118
|
+
import { fetch } from 'react-native-fetch-api';
|
|
119
|
+
|
|
120
|
+
httpBatchStreamLink({
|
|
121
|
+
fetch: (url, opts) =>
|
|
122
|
+
fetch(url, {
|
|
123
|
+
...opts,
|
|
124
|
+
reactNative: { textStreaming: true },
|
|
125
|
+
}),
|
|
126
|
+
url: 'http://localhost:3000',
|
|
127
|
+
});
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
## Compatibility (server-side)
|
|
131
|
+
|
|
132
|
+
> [!WARNING] AWS Lambda
|
|
133
|
+
> `httpBatchStreamLink` only supported on AWS Lambda when your [infrastructure is set up](https://trpc.io/docs/server/adapters/aws-lambda#aws-lambda-response-streaming-adapter) for streaming responses. If not this Link will simply behave like a regular `httpBatchLink`.
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
> [!WARNING] Cloudflare Workers
|
|
137
|
+
> You need to enable the `ReadableStream` API through a feature flag: [`streams_enable_constructors`](https://developers.cloudflare.com/workers/platform/compatibility-dates#streams-constructors).
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
## Reference
|
|
141
|
+
|
|
142
|
+
You can check out the source code for this link on [GitHub.](https://github.com/trpc/trpc/blob/main/packages/client/src/links/httpBatchStreamLink.ts)
|
|
143
|
+
|
|
144
|
+
## Configure JSONL streaming options
|
|
145
|
+
|
|
146
|
+
When setting up your root config, you can pass in a `jsonl` option to configure ping behavior and the response `content-type` for streamed batch responses.
|
|
147
|
+
|
|
148
|
+
```ts no-check
|
|
149
|
+
import { initTRPC } from '@trpc/server';
|
|
150
|
+
|
|
151
|
+
const t = initTRPC.create({
|
|
152
|
+
jsonl: {
|
|
153
|
+
pingMs: 1000,
|
|
154
|
+
contentType: 'application/jsonl',
|
|
155
|
+
},
|
|
156
|
+
});
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
The default `contentType` remains `application/json` for backwards compatibility. Use `application/jsonl` if you want the response header to match the `trpc-accept` / `Accept` header sent by `httpBatchStreamLink`, or choose another value that works better with your tooling.
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
# HTTP Link
|
|
2
|
+
|
|
3
|
+
> A terminating link that sends each tRPC call as its own HTTP request
|
|
4
|
+
|
|
5
|
+
From https://trpc.io/docs/client/links/httpLink
|
|
6
|
+
|
|
7
|
+
`httpLink` is a [**terminating link**](https://trpc.io/docs/client/links#the-terminating-link) that sends a tRPC operation to a tRPC procedure over HTTP.
|
|
8
|
+
|
|
9
|
+
`httpLink` supports both POST and GET requests.
|
|
10
|
+
|
|
11
|
+
## Usage
|
|
12
|
+
|
|
13
|
+
You can import and add the `httpLink` to the `links` array as such:
|
|
14
|
+
|
|
15
|
+
```ts no-check title="client/index.ts"
|
|
16
|
+
import { createTRPCClient, httpLink } from '@trpc/client';
|
|
17
|
+
import type { AppRouter } from './server';
|
|
18
|
+
|
|
19
|
+
const client = createTRPCClient<AppRouter>({
|
|
20
|
+
links: [
|
|
21
|
+
httpLink({
|
|
22
|
+
url: 'http://localhost:3000',
|
|
23
|
+
// transformer,
|
|
24
|
+
}),
|
|
25
|
+
],
|
|
26
|
+
});
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
## `httpLink` Options
|
|
30
|
+
|
|
31
|
+
The `httpLink` function takes an options object that has the `HTTPLinkOptions` shape.
|
|
32
|
+
|
|
33
|
+
```ts no-check
|
|
34
|
+
export interface HTTPLinkOptions {
|
|
35
|
+
url: string | URL;
|
|
36
|
+
/**
|
|
37
|
+
* Add ponyfill for fetch
|
|
38
|
+
*/
|
|
39
|
+
fetch?: typeof fetch;
|
|
40
|
+
/**
|
|
41
|
+
* Data transformer
|
|
42
|
+
* @see https://trpc.io/docs/server/data-transformers
|
|
43
|
+
**/
|
|
44
|
+
transformer?: DataTransformerOptions;
|
|
45
|
+
/**
|
|
46
|
+
* Headers to be set on outgoing requests or a callback that of said headers
|
|
47
|
+
* @see https://trpc.io/docs/client/headers
|
|
48
|
+
*/
|
|
49
|
+
headers?:
|
|
50
|
+
| HTTPHeaders
|
|
51
|
+
| ((opts: { op: Operation }) => HTTPHeaders | Promise<HTTPHeaders>);
|
|
52
|
+
/**
|
|
53
|
+
* Send all requests as POSTS requests regardless of the procedure type
|
|
54
|
+
* The server must separately allow overriding the method. See:
|
|
55
|
+
* @see https://trpc.io/docs/rpc
|
|
56
|
+
*/
|
|
57
|
+
methodOverride?: 'POST';
|
|
58
|
+
}
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
## Reference
|
|
62
|
+
|
|
63
|
+
You can check out the source code for this link on [GitHub.](https://github.com/trpc/trpc/blob/main/packages/client/src/links/httpLink.ts)
|
|
@@ -0,0 +1,404 @@
|
|
|
1
|
+
# HTTP Subscription Link
|
|
2
|
+
|
|
3
|
+
> A terminating link for subscriptions over Server-sent Events
|
|
4
|
+
|
|
5
|
+
From https://trpc.io/docs/client/links/httpSubscriptionLink
|
|
6
|
+
|
|
7
|
+
`httpSubscriptionLink` is a [**terminating link**](https://trpc.io/docs/client/links#the-terminating-link) that uses [Server-sent Events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events) (SSE) for subscriptions.
|
|
8
|
+
|
|
9
|
+
SSE is a good option for real-time as it's a bit easier than setting up a WebSockets-server.
|
|
10
|
+
|
|
11
|
+
## Setup
|
|
12
|
+
|
|
13
|
+
> [!NOTE] Info
|
|
14
|
+
> If your client's environment doesn't support EventSource, you need an [EventSource polyfill](https://www.npmjs.com/package/event-source-polyfill). For React Native specific instructions please defer to the [compatibility section](https://trpc.io/docs/client/links/httpSubscriptionLink#compatibility-react-native).
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
To use `httpSubscriptionLink`, you need to use a [splitLink](https://trpc.io/docs/client/links/splitLink) to make it explicit that we want to use SSE for subscriptions.
|
|
18
|
+
|
|
19
|
+
```ts no-check title="client/index.ts"
|
|
20
|
+
import {
|
|
21
|
+
createTRPCClient,
|
|
22
|
+
httpBatchLink,
|
|
23
|
+
httpSubscriptionLink,
|
|
24
|
+
loggerLink,
|
|
25
|
+
splitLink,
|
|
26
|
+
} from '@trpc/client';
|
|
27
|
+
import type { AppRouter } from './server';
|
|
28
|
+
|
|
29
|
+
const trpcClient = createTRPCClient<AppRouter>({
|
|
30
|
+
/**
|
|
31
|
+
* @see https://trpc.io/docs/v11/client/links
|
|
32
|
+
*/
|
|
33
|
+
links: [
|
|
34
|
+
// adds pretty logs to your console in development and logs errors in production
|
|
35
|
+
loggerLink(),
|
|
36
|
+
splitLink({
|
|
37
|
+
// uses the httpSubscriptionLink for subscriptions
|
|
38
|
+
condition: (op) => op.type === 'subscription',
|
|
39
|
+
true: httpSubscriptionLink({
|
|
40
|
+
url: `/api/trpc`,
|
|
41
|
+
}),
|
|
42
|
+
false: httpBatchLink({
|
|
43
|
+
url: `/api/trpc`,
|
|
44
|
+
}),
|
|
45
|
+
}),
|
|
46
|
+
],
|
|
47
|
+
});
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
> [!TIP]
|
|
51
|
+
> The document here outlines the specific details of using `httpSubscriptionLink`. For general usage of subscriptions, see [our subscriptions guide](https://trpc.io/docs/server/subscriptions).
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
## Headers and authorization / authentication
|
|
55
|
+
|
|
56
|
+
### Web apps
|
|
57
|
+
|
|
58
|
+
#### Same domain
|
|
59
|
+
|
|
60
|
+
If you're doing a web application, cookies are sent as part of the request as long as your client is on the same domain as the server.
|
|
61
|
+
|
|
62
|
+
#### Cross-domain
|
|
63
|
+
|
|
64
|
+
If the client and server are not on the same domain, you can use `withCredentials: true` ([read more on MDN here](https://developer.mozilla.org/en-US/docs/Web/API/EventSource/withCredentials)).
|
|
65
|
+
|
|
66
|
+
**Example:**
|
|
67
|
+
|
|
68
|
+
```tsx no-check
|
|
69
|
+
// [...]
|
|
70
|
+
httpSubscriptionLink({
|
|
71
|
+
url: 'https://example.com/api/trpc',
|
|
72
|
+
eventSourceOptions() {
|
|
73
|
+
return {
|
|
74
|
+
withCredentials: true, // <---
|
|
75
|
+
};
|
|
76
|
+
},
|
|
77
|
+
});
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
### Custom headers through ponyfill
|
|
81
|
+
|
|
82
|
+
**Recommended for non-web environments**
|
|
83
|
+
|
|
84
|
+
You can ponyfill `EventSource` and use the `eventSourceOptions` -callback to populate headers.
|
|
85
|
+
|
|
86
|
+
```tsx no-check
|
|
87
|
+
import {
|
|
88
|
+
createTRPCClient,
|
|
89
|
+
httpBatchLink,
|
|
90
|
+
httpSubscriptionLink,
|
|
91
|
+
splitLink,
|
|
92
|
+
} from '@trpc/client';
|
|
93
|
+
import { EventSourcePolyfill } from 'event-source-polyfill';
|
|
94
|
+
import type { AppRouter } from './server';
|
|
95
|
+
|
|
96
|
+
// Initialize the tRPC client
|
|
97
|
+
const trpc = createTRPCClient<AppRouter>({
|
|
98
|
+
links: [
|
|
99
|
+
splitLink({
|
|
100
|
+
condition: (op) => op.type === 'subscription',
|
|
101
|
+
true: httpSubscriptionLink({
|
|
102
|
+
url: 'http://localhost:3000',
|
|
103
|
+
// ponyfill EventSource
|
|
104
|
+
EventSource: EventSourcePolyfill,
|
|
105
|
+
// options to pass to the EventSourcePolyfill constructor
|
|
106
|
+
eventSourceOptions: async ({ op }) => {
|
|
107
|
+
// ^ Includes the operation that's being executed
|
|
108
|
+
// you can use this to generate a signature for the operation
|
|
109
|
+
const signature = await getSignature(op);
|
|
110
|
+
return {
|
|
111
|
+
headers: {
|
|
112
|
+
authorization: 'Bearer supersecret',
|
|
113
|
+
'x-signature': signature,
|
|
114
|
+
},
|
|
115
|
+
};
|
|
116
|
+
},
|
|
117
|
+
}),
|
|
118
|
+
false: httpBatchLink({
|
|
119
|
+
url: 'http://localhost:3000',
|
|
120
|
+
}),
|
|
121
|
+
}),
|
|
122
|
+
],
|
|
123
|
+
});
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
### Updating configuration on an active connection
|
|
127
|
+
|
|
128
|
+
`httpSubscriptionLink` leverages SSE through `EventSource`, ensuring that connections encountering errors like network failures or bad response codes are automatically retried. However, `EventSource` does not allow re-execution of the `eventSourceOptions()` or `url()` options to update its configuration, which is particularly important in scenarios where authentication has expired since the last connection.
|
|
129
|
+
|
|
130
|
+
To address this limitation, you can use a [`retryLink`](https://trpc.io/docs/client/links/retryLink) in conjunction with `httpSubscriptionLink`. This approach ensures that the connection is re-established with the latest configuration, including any updated authentication details.
|
|
131
|
+
|
|
132
|
+
> [!WARNING] Caution
|
|
133
|
+
> Please note that restarting the connection will result in the `EventSource` being recreated from scratch, which means any previously tracked events will be lost.
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
```tsx no-check
|
|
137
|
+
import {
|
|
138
|
+
createTRPCClient,
|
|
139
|
+
httpBatchLink,
|
|
140
|
+
httpSubscriptionLink,
|
|
141
|
+
retryLink,
|
|
142
|
+
splitLink,
|
|
143
|
+
} from '@trpc/client';
|
|
144
|
+
import {
|
|
145
|
+
EventSourcePolyfill,
|
|
146
|
+
EventSourcePolyfillInit,
|
|
147
|
+
} from 'event-source-polyfill';
|
|
148
|
+
import type { AppRouter } from './server';
|
|
149
|
+
|
|
150
|
+
// Initialize the tRPC client
|
|
151
|
+
const trpc = createTRPCClient<AppRouter>({
|
|
152
|
+
links: [
|
|
153
|
+
splitLink({
|
|
154
|
+
condition: (op) => op.type === 'subscription',
|
|
155
|
+
false: httpBatchLink({
|
|
156
|
+
url: 'http://localhost:3000',
|
|
157
|
+
}),
|
|
158
|
+
true: [
|
|
159
|
+
retryLink({
|
|
160
|
+
retry: (opts) => {
|
|
161
|
+
opts.op.type;
|
|
162
|
+
const code = opts.error.data?.code;
|
|
163
|
+
if (!code) {
|
|
164
|
+
// This shouldn't happen as our httpSubscriptionLink will automatically retry within when there's a non-parsable response
|
|
165
|
+
console.error('No error code found, retrying', opts);
|
|
166
|
+
return true;
|
|
167
|
+
}
|
|
168
|
+
if (code === 'UNAUTHORIZED' || code === 'FORBIDDEN') {
|
|
169
|
+
console.log('Retrying due to 401/403 error');
|
|
170
|
+
return true;
|
|
171
|
+
}
|
|
172
|
+
return false;
|
|
173
|
+
},
|
|
174
|
+
}),
|
|
175
|
+
httpSubscriptionLink({
|
|
176
|
+
url: async () => {
|
|
177
|
+
// calculate the latest URL if needed...
|
|
178
|
+
return getAuthenticatedUri();
|
|
179
|
+
},
|
|
180
|
+
// ponyfill EventSource
|
|
181
|
+
EventSource: EventSourcePolyfill,
|
|
182
|
+
eventSourceOptions: async () => {
|
|
183
|
+
// ...or maybe renew an access token
|
|
184
|
+
const token = await auth.getOrRenewToken();
|
|
185
|
+
|
|
186
|
+
return {
|
|
187
|
+
headers: {
|
|
188
|
+
authorization: `Bearer ${token}`,
|
|
189
|
+
},
|
|
190
|
+
};
|
|
191
|
+
},
|
|
192
|
+
}),
|
|
193
|
+
],
|
|
194
|
+
}),
|
|
195
|
+
],
|
|
196
|
+
});
|
|
197
|
+
```
|
|
198
|
+
|
|
199
|
+
### Connection params
|
|
200
|
+
|
|
201
|
+
In order to authenticate with `EventSource`, you can define `connectionParams` in `httpSubscriptionLink`. This will be sent as part of the URL, which is why other methods are preferred.
|
|
202
|
+
|
|
203
|
+
```ts no-check title="server/context.ts"
|
|
204
|
+
import type { CreateHTTPContextOptions } from '@trpc/server/adapters/standalone';
|
|
205
|
+
|
|
206
|
+
export const createContext = async (opts: CreateHTTPContextOptions) => {
|
|
207
|
+
const token = opts.info.connectionParams?.token;
|
|
208
|
+
|
|
209
|
+
// [... authenticate]
|
|
210
|
+
|
|
211
|
+
return {};
|
|
212
|
+
};
|
|
213
|
+
|
|
214
|
+
export type Context = Awaited<ReturnType<typeof createContext>>;
|
|
215
|
+
```
|
|
216
|
+
|
|
217
|
+
```ts no-check title="client/trpc.ts"
|
|
218
|
+
import {
|
|
219
|
+
createTRPCClient,
|
|
220
|
+
httpBatchLink,
|
|
221
|
+
httpSubscriptionLink,
|
|
222
|
+
splitLink,
|
|
223
|
+
} from '@trpc/client';
|
|
224
|
+
import type { AppRouter } from './server';
|
|
225
|
+
|
|
226
|
+
// Initialize the tRPC client
|
|
227
|
+
const trpc = createTRPCClient<AppRouter>({
|
|
228
|
+
links: [
|
|
229
|
+
splitLink({
|
|
230
|
+
condition: (op) => op.type === 'subscription',
|
|
231
|
+
true: httpSubscriptionLink({
|
|
232
|
+
url: 'http://localhost:3000',
|
|
233
|
+
connectionParams: async () => {
|
|
234
|
+
// Will be serialized as part of the URL
|
|
235
|
+
return {
|
|
236
|
+
token: 'supersecret',
|
|
237
|
+
};
|
|
238
|
+
},
|
|
239
|
+
}),
|
|
240
|
+
false: httpBatchLink({
|
|
241
|
+
url: 'http://localhost:3000',
|
|
242
|
+
}),
|
|
243
|
+
}),
|
|
244
|
+
],
|
|
245
|
+
});
|
|
246
|
+
```
|
|
247
|
+
|
|
248
|
+
## Timeout Configuration
|
|
249
|
+
|
|
250
|
+
The `httpSubscriptionLink` supports configuring a timeout for inactivity through the `reconnectAfterInactivityMs` option. If no messages (including ping messages) are received within the specified timeout period, the connection will be marked as "connecting" and automatically attempt to reconnect.
|
|
251
|
+
|
|
252
|
+
The timeout configuration is set on the server side when initializing tRPC:
|
|
253
|
+
|
|
254
|
+
```ts no-check title="server/trpc.ts"
|
|
255
|
+
import { initTRPC } from '@trpc/server';
|
|
256
|
+
|
|
257
|
+
export const t = initTRPC.create({
|
|
258
|
+
sse: {
|
|
259
|
+
client: {
|
|
260
|
+
reconnectAfterInactivityMs: 3_000,
|
|
261
|
+
},
|
|
262
|
+
},
|
|
263
|
+
});
|
|
264
|
+
```
|
|
265
|
+
|
|
266
|
+
## Server Ping Configuration
|
|
267
|
+
|
|
268
|
+
The server can be configured to send periodic ping messages to keep the connection alive and prevent timeout disconnections. This is particularly useful when combined with the `reconnectAfterInactivityMs`-option.
|
|
269
|
+
|
|
270
|
+
```ts no-check title="server/trpc.ts"
|
|
271
|
+
import { initTRPC } from '@trpc/server';
|
|
272
|
+
|
|
273
|
+
export const t = initTRPC.create({
|
|
274
|
+
sse: {
|
|
275
|
+
// Maximum duration of a single SSE connection in milliseconds
|
|
276
|
+
// maxDurationMs: 60_000,
|
|
277
|
+
ping: {
|
|
278
|
+
// Enable periodic ping messages to keep connection alive
|
|
279
|
+
enabled: true,
|
|
280
|
+
// Send ping message every 2s
|
|
281
|
+
intervalMs: 2_000,
|
|
282
|
+
},
|
|
283
|
+
// client: {
|
|
284
|
+
// reconnectAfterInactivityMs: 3_000
|
|
285
|
+
// }
|
|
286
|
+
},
|
|
287
|
+
});
|
|
288
|
+
```
|
|
289
|
+
|
|
290
|
+
## Compatibility (React Native)
|
|
291
|
+
|
|
292
|
+
The `httpSubscriptionLink` makes use of the `EventSource` API, Streams API, and `AsyncIterator`s, these are not natively supported by React Native and will have to be ponyfilled.
|
|
293
|
+
|
|
294
|
+
To ponyfill `EventSource` we recommend to use a polyfill that utilizes the networking library exposed by React Native, over using a polyfill that uses the `XMLHttpRequest` API. Libraries that polyfill `EventSource` using `XMLHttpRequest` fail to reconnect after the app has been in the background. Consider using the [rn-eventsource-reborn](https://www.npmjs.com/package/rn-eventsource-reborn) package.
|
|
295
|
+
|
|
296
|
+
The Streams API can be ponyfilled using the [web-streams-polyfill](https://www.npmjs.com/package/web-streams-polyfill) package.
|
|
297
|
+
|
|
298
|
+
`AsyncIterator`s can be polyfilled using the [@azure/core-asynciterator-polyfill](https://www.npmjs.com/package/@azure/core-asynciterator-polyfill) package.
|
|
299
|
+
|
|
300
|
+
### Installation
|
|
301
|
+
|
|
302
|
+
Install the required polyfills:
|
|
303
|
+
|
|
304
|
+
```bash
|
|
305
|
+
npm install rn-eventsource-reborn web-streams-polyfill @azure/core-asynciterator-polyfill
|
|
306
|
+
```
|
|
307
|
+
|
|
308
|
+
Add the polyfills to your project before the link is used (e.g. where you add your TRPCReact.Provider):
|
|
309
|
+
|
|
310
|
+
```ts no-check title="utils/api.tsx"
|
|
311
|
+
import '@azure/core-asynciterator-polyfill';
|
|
312
|
+
import { RNEventSource } from 'rn-eventsource-reborn';
|
|
313
|
+
import { ReadableStream, TransformStream } from 'web-streams-polyfill';
|
|
314
|
+
|
|
315
|
+
globalThis.ReadableStream = globalThis.ReadableStream || ReadableStream;
|
|
316
|
+
globalThis.TransformStream = globalThis.TransformStream || TransformStream;
|
|
317
|
+
```
|
|
318
|
+
|
|
319
|
+
Once the ponyfills are added, you can continue setting up the `httpSubscriptionLink` as described in the [setup](https://trpc.io/docs/client/links/httpSubscriptionLink#setup) section.
|
|
320
|
+
|
|
321
|
+
## `httpSubscriptionLink` Options
|
|
322
|
+
|
|
323
|
+
```ts no-check
|
|
324
|
+
type HTTPSubscriptionLinkOptions<
|
|
325
|
+
TRoot extends AnyClientTypes,
|
|
326
|
+
TEventSource extends EventSourceLike.AnyConstructor = typeof EventSource,
|
|
327
|
+
> = {
|
|
328
|
+
/**
|
|
329
|
+
* The URL to connect to (can be a function that returns a URL)
|
|
330
|
+
*/
|
|
331
|
+
url: string | (() => string | Promise<string>);
|
|
332
|
+
/**
|
|
333
|
+
* Connection params that are available in `createContext()`
|
|
334
|
+
* Serialized as part of the URL under the `connectionParams` query parameter
|
|
335
|
+
*/
|
|
336
|
+
connectionParams?:
|
|
337
|
+
| Record<string, string>
|
|
338
|
+
| null
|
|
339
|
+
| (() =>
|
|
340
|
+
| Record<string, string>
|
|
341
|
+
| null
|
|
342
|
+
| Promise<Record<string, string> | null>);
|
|
343
|
+
/**
|
|
344
|
+
* Data transformer
|
|
345
|
+
* @see https://trpc.io/docs/v11/data-transformers
|
|
346
|
+
*/
|
|
347
|
+
transformer?: DataTransformerOptions;
|
|
348
|
+
/**
|
|
349
|
+
* EventSource ponyfill
|
|
350
|
+
*/
|
|
351
|
+
EventSource?: TEventSource;
|
|
352
|
+
/**
|
|
353
|
+
* EventSource options or a callback that returns them
|
|
354
|
+
*/
|
|
355
|
+
eventSourceOptions?:
|
|
356
|
+
| EventSourceLike.InitDictOf<TEventSource>
|
|
357
|
+
| ((opts: {
|
|
358
|
+
op: Operation;
|
|
359
|
+
}) =>
|
|
360
|
+
| EventSourceLike.InitDictOf<TEventSource>
|
|
361
|
+
| Promise<EventSourceLike.InitDictOf<TEventSource>>);
|
|
362
|
+
};
|
|
363
|
+
```
|
|
364
|
+
|
|
365
|
+
## SSE Options on the server
|
|
366
|
+
|
|
367
|
+
```ts no-check
|
|
368
|
+
export interface SSEStreamProducerOptions<TValue = unknown> {
|
|
369
|
+
ping?: {
|
|
370
|
+
/**
|
|
371
|
+
* Enable ping comments sent from the server
|
|
372
|
+
* @default false
|
|
373
|
+
*/
|
|
374
|
+
enabled: boolean;
|
|
375
|
+
/**
|
|
376
|
+
* Interval in milliseconds
|
|
377
|
+
* @default 1000
|
|
378
|
+
*/
|
|
379
|
+
intervalMs?: number;
|
|
380
|
+
};
|
|
381
|
+
/**
|
|
382
|
+
* Maximum duration in milliseconds for the request before ending the stream
|
|
383
|
+
* @default undefined
|
|
384
|
+
*/
|
|
385
|
+
maxDurationMs?: number;
|
|
386
|
+
/**
|
|
387
|
+
* End the request immediately after data is sent
|
|
388
|
+
* Only useful for serverless runtimes that do not support streaming responses
|
|
389
|
+
* @default false
|
|
390
|
+
*/
|
|
391
|
+
emitAndEndImmediately?: boolean;
|
|
392
|
+
/**
|
|
393
|
+
* Client-specific options - these will be sent to the client as part of the first message
|
|
394
|
+
* @default {}
|
|
395
|
+
*/
|
|
396
|
+
client?: {
|
|
397
|
+
/**
|
|
398
|
+
* Timeout and reconnect after inactivity in milliseconds
|
|
399
|
+
* @default undefined
|
|
400
|
+
*/
|
|
401
|
+
reconnectAfterInactivityMs?: number;
|
|
402
|
+
};
|
|
403
|
+
}
|
|
404
|
+
```
|