@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,122 +1,253 @@
1
1
  ---
2
2
  name: auth
3
- description: >
4
- Implement JWT/cookie authentication and authorization in tRPC using createContext
5
- for user extraction, t.middleware with opts.next({ ctx }) for context narrowing to
6
- non-null user, protectedProcedure base pattern, client-side Authorization headers
7
- via httpBatchLink headers(), WebSocket connectionParams, and SSE auth via cookies
8
- or EventSource polyfill custom headers.
9
- type: composition
10
- library: trpc
11
- library_version: '11.16.0'
3
+ description: Implement JWT/cookie authentication and authorization in tRPC using createContext for user extraction, t.middleware with opts.next({ ctx }) for context narrowing to non-null user, protectedProcedure base pattern, client-side Authorization headers via httpBatchLink headers(), WebSocket connectionParams, and SSE auth via cookies or EventSource polyfill custom headers. UNAUTHORIZED vs FORBIDDEN, role checks stacked on protectedProcedure, and why createContext shouldn't throw for a bad token.
12
4
  requires:
13
5
  - server-setup
14
6
  - middlewares
15
7
  - client-setup
16
8
  sources:
17
- - www/docs/server/authorization.md
18
- - www/docs/client/headers.md
19
- - www/docs/client/links/httpSubscriptionLink.md
20
- - www/docs/server/websockets.md
9
+ - www/v11/docs/server/authorization.md
10
+ - www/v11/docs/client/headers.md
11
+ - www/v11/docs/client/links/httpSubscriptionLink.md
12
+ - www/v11/docs/server/websockets.md
13
+ - www/v11/docs/client/cors.md
14
+ metadata:
15
+ type: composition
16
+ library: trpc
17
+ library_version: 11.23.0
21
18
  ---
22
19
 
23
- # tRPC — Auth
20
+ <!-- Generated from www/v11/docs/server/authorization.md by www/build/skills.ts. Edit the docs instead. -->
24
21
 
25
- ## Setup
22
+ # Authorization
26
23
 
27
- ```ts
28
- // server/trpc.ts
29
- import { initTRPC, TRPCError } from '@trpc/server';
24
+ From https://trpc.io/docs/server/authorization
25
+
26
+ The `createContext` function is called for each incoming request, so here you can add contextual information about the calling user from the request object.
27
+
28
+ ## Create context from request headers
29
+
30
+ ```ts no-check title="server/context.ts"
30
31
  import type { CreateHTTPContextOptions } from '@trpc/server/adapters/standalone';
32
+ import { decodeAndVerifyJwtToken } from './utils';
33
+
34
+ export async function createContext({ req, res }: CreateHTTPContextOptions) {
35
+ // Create your context based on the request object
36
+ // Will be available as `ctx` in all your resolvers
31
37
 
32
- export async function createContext({ req }: CreateHTTPContextOptions) {
38
+ // This is just an example of something you might want to do in your ctx fn
33
39
  async function getUserFromHeader() {
34
- const token = req.headers.authorization?.split(' ')[1];
35
- if (token) {
36
- const user = await verifyJwt(token); // your JWT verification
37
- return user; // e.g. { id: string; name: string; role: string }
40
+ if (req.headers.authorization) {
41
+ const user = await decodeAndVerifyJwtToken(
42
+ req.headers.authorization.split(' ')[1],
43
+ );
44
+ return user;
38
45
  }
39
46
  return null;
40
47
  }
41
- return { user: await getUserFromHeader() };
42
- }
48
+ const user = await getUserFromHeader();
43
49
 
50
+ return {
51
+ user,
52
+ };
53
+ }
44
54
  export type Context = Awaited<ReturnType<typeof createContext>>;
55
+ ```
45
56
 
46
- const t = initTRPC.context<Context>().create();
57
+ ## Option 1: Authorize using resolver
58
+
59
+ ```ts no-check title="server/routers/_app.ts"
60
+ import { initTRPC, TRPCError } from '@trpc/server';
61
+ import { z } from 'zod';
47
62
 
48
- export const publicProcedure = t.procedure;
63
+ type Context = { user: { name: string } | null };
49
64
 
65
+ export const t = initTRPC.context<Context>().create();
66
+
67
+ const appRouter = t.router({
68
+ // open for anyone
69
+ hello: t.procedure
70
+ .input(z.string().nullish())
71
+ .query((opts) => `hello ${opts.input ?? opts.ctx.user?.name ?? 'world'}`),
72
+ // checked in resolver
73
+ secret: t.procedure.query((opts) => {
74
+ if (!opts.ctx.user) {
75
+ throw new TRPCError({ code: 'UNAUTHORIZED' });
76
+ }
77
+ return {
78
+ secret: 'sauce',
79
+ };
80
+ }),
81
+ });
82
+ ```
83
+
84
+ ## Option 2: Authorize using middleware
85
+
86
+ ```ts no-check title="server/routers/_app.ts"
87
+ import { initTRPC, TRPCError } from '@trpc/server';
88
+ import { z } from 'zod';
89
+
90
+ type Context = { user: { name: string } | null };
91
+
92
+ export const t = initTRPC.context<Context>().create();
93
+
94
+ // you can reuse this for any procedure
50
95
  export const protectedProcedure = t.procedure.use(
51
96
  async function isAuthed(opts) {
52
97
  const { ctx } = opts;
98
+ // `ctx.user` is nullable
53
99
  if (!ctx.user) {
54
100
  throw new TRPCError({ code: 'UNAUTHORIZED' });
55
101
  }
102
+
56
103
  return opts.next({
57
104
  ctx: {
58
- user: ctx.user, // narrows user to non-null
105
+ // ✅ user value is known to be non-null now
106
+ user: ctx.user,
59
107
  },
60
108
  });
61
109
  },
62
110
  );
63
111
 
64
- export const router = t.router;
112
+ t.router({
113
+ // this is accessible for everyone
114
+ hello: t.procedure
115
+ .input(z.string().nullish())
116
+ .query((opts) => `hello ${opts.input ?? opts.ctx.user?.name ?? 'world'}`),
117
+ admin: t.router({
118
+ // this is accessible only to admins
119
+ secret: protectedProcedure.query((opts) => {
120
+ return {
121
+ secret: 'sauce',
122
+ };
123
+ }),
124
+ }),
125
+ });
126
+ ```
127
+
128
+ ## Building on a protected procedure
129
+
130
+ Since a procedure's middlewares run in order, you can add more checks on top of `protectedProcedure`, where `ctx.user` is already non-null:
131
+
132
+ ```ts no-check title="server/trpc.ts"
133
+ import { initTRPC, TRPCError } from '@trpc/server';
134
+
135
+ type Context = { user: { name: string; role: 'admin' | 'user' } | null };
136
+
137
+ export const t = initTRPC.context<Context>().create();
138
+
139
+ export const protectedProcedure = t.procedure.use(async (opts) => {
140
+ if (!opts.ctx.user) {
141
+ throw new TRPCError({ code: 'UNAUTHORIZED' });
142
+ }
143
+ return opts.next({ ctx: { user: opts.ctx.user } });
144
+ });
145
+
146
+ export const adminProcedure = protectedProcedure.use(async (opts) => {
147
+ if (opts.ctx.user.role !== 'admin') {
148
+ throw new TRPCError({ code: 'FORBIDDEN' });
149
+ }
150
+ return opts.next();
151
+ });
65
152
  ```
66
153
 
67
- ```ts
68
- // client/trpc.ts
154
+ Throw `UNAUTHORIZED` (401) when the caller isn't signed in, and `FORBIDDEN` (403) when they are, but aren't allowed to do this.
155
+
156
+ ## Sending credentials from the client
157
+
158
+ - **Cookies** are sent with every request when the client and server are on the same origin. For another origin, see [CORS & Cookies](https://trpc.io/docs/client/cors).
159
+ - **Headers** like `Authorization` can be set on any HTTP link with the [`headers`](https://trpc.io/docs/client/headers) option.
160
+ - **Subscriptions** over SSE can't send custom headers with the browser's `EventSource`. See [`httpSubscriptionLink`](https://trpc.io/docs/client/links/httpSubscriptionLink#headers-and-authorization--authentication) for the options.
161
+ - **WebSockets** send [connection params](https://trpc.io/docs/server/websockets#connectionParams) when the connection opens, which `createContext` reads from `opts.info.connectionParams`.
162
+
163
+ ## Common mistakes
164
+
165
+ - **Calling `opts.next()` without the narrowed `ctx`.** Procedures after the middleware still see `ctx.user` as nullable. Pass `opts.next({ ctx: { user: opts.ctx.user } })`, as in [Option 2](https://trpc.io/docs/server/authorization#option-2-authorize-using-middleware).
166
+ - **Throwing in `createContext` for a missing or invalid token.** That fails every procedure in the request, public ones too. Return `user: null` instead, and let a middleware reject the procedures that need a user.
167
+ - **Putting tokens in `httpSubscriptionLink`'s `connectionParams`.** They are sent in the URL, where servers and proxies may log them. Prefer cookies, or headers through an `EventSource` ponyfill.
168
+
169
+ ## Headers
170
+
171
+ From https://trpc.io/docs/client/headers
172
+
173
+ The headers option may be used with any of our HTTP links: [`httpBatchLink`](https://trpc.io/docs/client/links/httpBatchLink), [`httpBatchStreamLink`](https://trpc.io/docs/client/links/httpBatchStreamLink), [`httpLink`](https://trpc.io/docs/client/links/httpLink), or [`httpSubscriptionLink`](https://trpc.io/docs/client/links/httpSubscriptionLink).
174
+
175
+ `headers` can be both an object or a function. If it's a function it will get called dynamically for every HTTP request.
176
+
177
+ ```ts no-check title="utils/trpc.ts"
69
178
  import { createTRPCClient, httpBatchLink } from '@trpc/client';
70
- import type { AppRouter } from '../server/router';
179
+ import type { AppRouter } from './server';
71
180
 
72
- let token = '';
73
- export function setToken(t: string) {
74
- token = t;
181
+ let token: string;
182
+
183
+ export function setToken(newToken: string) {
184
+ /**
185
+ * You can also save the token to cookies, and initialize from
186
+ * cookies above.
187
+ */
188
+ token = newToken;
75
189
  }
76
190
 
77
191
  export const trpc = createTRPCClient<AppRouter>({
78
192
  links: [
79
193
  httpBatchLink({
80
- url: 'http://localhost:3000/trpc',
194
+ url: 'http://localhost:3000',
195
+ /**
196
+ * Headers will be called on each request.
197
+ */
81
198
  headers() {
82
- return { Authorization: `Bearer ${token}` };
199
+ return {
200
+ Authorization: token,
201
+ };
83
202
  },
84
203
  }),
85
204
  ],
86
205
  });
87
206
  ```
88
207
 
89
- ## Core Patterns
208
+ ### Example with auth login
90
209
 
91
- ### Context narrowing with auth middleware
210
+ ```ts no-check title="auth.ts"
211
+ const result = await trpc.auth.login.mutate({ username: 'user', password: 'pass' });
212
+ setToken(result.accessToken);
213
+ ```
92
214
 
93
- ```ts
94
- import { initTRPC, TRPCError } from '@trpc/server';
215
+ The `token` can be whatever you want it to be. It's entirely up to you whether that's just a client-side
216
+ variable that you update the value of on success or whether you store the token and pull it from local storage.
95
217
 
96
- type Context = { user: { id: string; role: string } | null };
97
- const t = initTRPC.context<Context>().create();
218
+ ## Headers and authorization / authentication
98
219
 
99
- const isAuthed = t.middleware(async ({ ctx, next }) => {
100
- if (!ctx.user) {
101
- throw new TRPCError({ code: 'UNAUTHORIZED' });
102
- }
103
- return next({ ctx: { user: ctx.user } });
104
- });
220
+ ### Web apps
105
221
 
106
- const isAdmin = t.middleware(async ({ ctx, next }) => {
107
- if (!ctx.user || ctx.user.role !== 'admin') {
108
- throw new TRPCError({ code: 'FORBIDDEN' });
109
- }
110
- return next({ ctx: { user: ctx.user } });
111
- });
222
+ #### Same domain
223
+
224
+ 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.
225
+
226
+ #### Cross-domain
112
227
 
113
- export const protectedProcedure = t.procedure.use(isAuthed);
114
- export const adminProcedure = t.procedure.use(isAdmin);
228
+ 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)).
229
+
230
+ **Example:**
231
+
232
+ ```tsx no-check
233
+ // [...]
234
+ httpSubscriptionLink({
235
+ url: 'https://example.com/api/trpc',
236
+ eventSourceOptions() {
237
+ return {
238
+ withCredentials: true, // <---
239
+ };
240
+ },
241
+ });
115
242
  ```
116
243
 
117
- ### SSE subscription auth with EventSource polyfill
244
+ ### Custom headers through ponyfill
245
+
246
+ **Recommended for non-web environments**
247
+
248
+ You can ponyfill `EventSource` and use the `eventSourceOptions` -callback to populate headers.
118
249
 
119
- ```ts
250
+ ```tsx no-check
120
251
  import {
121
252
  createTRPCClient,
122
253
  httpBatchLink,
@@ -124,219 +255,213 @@ import {
124
255
  splitLink,
125
256
  } from '@trpc/client';
126
257
  import { EventSourcePolyfill } from 'event-source-polyfill';
127
- import type { AppRouter } from '../server/router';
258
+ import type { AppRouter } from './server';
128
259
 
260
+ // Initialize the tRPC client
129
261
  const trpc = createTRPCClient<AppRouter>({
130
262
  links: [
131
263
  splitLink({
132
264
  condition: (op) => op.type === 'subscription',
133
265
  true: httpSubscriptionLink({
134
- url: 'http://localhost:3000/trpc',
266
+ url: 'http://localhost:3000',
267
+ // ponyfill EventSource
135
268
  EventSource: EventSourcePolyfill,
136
- eventSourceOptions: async () => {
269
+ // options to pass to the EventSourcePolyfill constructor
270
+ eventSourceOptions: async ({ op }) => {
271
+ // ^ Includes the operation that's being executed
272
+ // you can use this to generate a signature for the operation
273
+ const signature = await getSignature(op);
137
274
  return {
138
275
  headers: {
139
- authorization: `Bearer ${getToken()}`,
276
+ authorization: 'Bearer supersecret',
277
+ 'x-signature': signature,
140
278
  },
141
279
  };
142
280
  },
143
281
  }),
144
282
  false: httpBatchLink({
145
- url: 'http://localhost:3000/trpc',
146
- headers() {
147
- return { Authorization: `Bearer ${getToken()}` };
148
- },
283
+ url: 'http://localhost:3000',
149
284
  }),
150
285
  }),
151
286
  ],
152
287
  });
153
288
  ```
154
289
 
155
- ### WebSocket auth with connectionParams
156
-
157
- ```ts
158
- // server/context.ts
159
- import type { CreateWSSContextFnOptions } from '@trpc/server/adapters/ws';
160
-
161
- export const createContext = async (opts: CreateWSSContextFnOptions) => {
162
- const token = opts.info.connectionParams?.token;
163
- const user = token ? await verifyJwt(token) : null;
164
- return { user };
165
- };
166
- ```
290
+ ### Updating configuration on an active connection
167
291
 
168
- ```ts
169
- // client/trpc.ts
170
- import { createTRPCClient, createWSClient, wsLink } from '@trpc/client';
171
- import type { AppRouter } from '../server/router';
292
+ `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.
172
293
 
173
- const wsClient = createWSClient({
174
- url: 'ws://localhost:3001',
175
- connectionParams: async () => ({
176
- token: getToken(),
177
- }),
178
- });
294
+ 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.
179
295
 
180
- const trpc = createTRPCClient<AppRouter>({
181
- links: [wsLink({ client: wsClient })],
182
- });
183
- ```
296
+ > [!WARNING] Caution
297
+ > Please note that restarting the connection will result in the `EventSource` being recreated from scratch, which means any previously tracked events will be lost.
184
298
 
185
- ### SSE auth with cookies (same domain)
186
299
 
187
- ```ts
300
+ ```tsx no-check
188
301
  import {
189
302
  createTRPCClient,
190
303
  httpBatchLink,
191
304
  httpSubscriptionLink,
305
+ retryLink,
192
306
  splitLink,
193
307
  } from '@trpc/client';
194
- import type { AppRouter } from '../server/router';
308
+ import {
309
+ EventSourcePolyfill,
310
+ EventSourcePolyfillInit,
311
+ } from 'event-source-polyfill';
312
+ import type { AppRouter } from './server';
195
313
 
314
+ // Initialize the tRPC client
196
315
  const trpc = createTRPCClient<AppRouter>({
197
316
  links: [
198
317
  splitLink({
199
318
  condition: (op) => op.type === 'subscription',
200
- true: httpSubscriptionLink({
201
- url: '/api/trpc',
202
- eventSourceOptions() {
203
- return { withCredentials: true };
204
- },
319
+ false: httpBatchLink({
320
+ url: 'http://localhost:3000',
205
321
  }),
206
- false: httpBatchLink({ url: '/api/trpc' }),
322
+ true: [
323
+ retryLink({
324
+ retry: (opts) => {
325
+ opts.op.type;
326
+ const code = opts.error.data?.code;
327
+ if (!code) {
328
+ // This shouldn't happen as our httpSubscriptionLink will automatically retry within when there's a non-parsable response
329
+ console.error('No error code found, retrying', opts);
330
+ return true;
331
+ }
332
+ if (code === 'UNAUTHORIZED' || code === 'FORBIDDEN') {
333
+ console.log('Retrying due to 401/403 error');
334
+ return true;
335
+ }
336
+ return false;
337
+ },
338
+ }),
339
+ httpSubscriptionLink({
340
+ url: async () => {
341
+ // calculate the latest URL if needed...
342
+ return getAuthenticatedUri();
343
+ },
344
+ // ponyfill EventSource
345
+ EventSource: EventSourcePolyfill,
346
+ eventSourceOptions: async () => {
347
+ // ...or maybe renew an access token
348
+ const token = await auth.getOrRenewToken();
349
+
350
+ return {
351
+ headers: {
352
+ authorization: `Bearer ${token}`,
353
+ },
354
+ };
355
+ },
356
+ }),
357
+ ],
207
358
  }),
208
359
  ],
209
360
  });
210
361
  ```
211
362
 
212
- ## Common Mistakes
363
+ ### Connection params
213
364
 
214
- ### HIGH Not narrowing user type in auth middleware
365
+ 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.
215
366
 
216
- Wrong:
217
-
218
- ```ts
219
- const authMiddleware = t.middleware(async ({ ctx, next }) => {
220
- if (!ctx.user) throw new TRPCError({ code: 'UNAUTHORIZED' });
221
- return next(); // user still nullable downstream
222
- });
223
- ```
224
-
225
- Correct:
226
-
227
- ```ts
228
- const authMiddleware = t.middleware(async ({ ctx, next }) => {
229
- if (!ctx.user) throw new TRPCError({ code: 'UNAUTHORIZED' });
230
- return next({ ctx: { user: ctx.user } }); // narrows to non-null
231
- });
232
- ```
233
-
234
- Without `opts.next({ ctx })`, downstream procedures still see `user` as `{ id: string } | null`, requiring redundant null checks.
367
+ ```ts no-check title="server/context.ts"
368
+ import type { CreateHTTPContextOptions } from '@trpc/server/adapters/standalone';
235
369
 
236
- Source: www/docs/server/authorization.md
370
+ export const createContext = async (opts: CreateHTTPContextOptions) => {
371
+ const token = opts.info.connectionParams?.token;
237
372
 
238
- ### HIGH SSE auth via URL query params exposes tokens
373
+ // [... authenticate]
239
374
 
240
- Wrong:
375
+ return {};
376
+ };
241
377
 
242
- ```ts
243
- httpSubscriptionLink({
244
- url: 'http://localhost:3000/trpc',
245
- connectionParams: async () => ({
246
- token: 'my-secret-jwt',
247
- }),
248
- });
378
+ export type Context = Awaited<ReturnType<typeof createContext>>;
249
379
  ```
250
380
 
251
- Correct:
252
-
253
- ```ts
254
- import { EventSourcePolyfill } from 'event-source-polyfill';
381
+ ```ts no-check title="client/trpc.ts"
382
+ import {
383
+ createTRPCClient,
384
+ httpBatchLink,
385
+ httpSubscriptionLink,
386
+ splitLink,
387
+ } from '@trpc/client';
388
+ import type { AppRouter } from './server';
255
389
 
256
- httpSubscriptionLink({
257
- url: 'http://localhost:3000/trpc',
258
- EventSource: EventSourcePolyfill,
259
- eventSourceOptions: async () => ({
260
- headers: { authorization: 'Bearer my-secret-jwt' },
261
- }),
390
+ // Initialize the tRPC client
391
+ const trpc = createTRPCClient<AppRouter>({
392
+ links: [
393
+ splitLink({
394
+ condition: (op) => op.type === 'subscription',
395
+ true: httpSubscriptionLink({
396
+ url: 'http://localhost:3000',
397
+ connectionParams: async () => {
398
+ // Will be serialized as part of the URL
399
+ return {
400
+ token: 'supersecret',
401
+ };
402
+ },
403
+ }),
404
+ false: httpBatchLink({
405
+ url: 'http://localhost:3000',
406
+ }),
407
+ }),
408
+ ],
262
409
  });
263
410
  ```
264
411
 
265
- `connectionParams` are serialized as URL query strings for SSE, exposing tokens in server logs and browser history. Use cookies for same-domain or custom headers via an EventSource polyfill instead.
266
-
267
- Source: www/docs/client/links/httpSubscriptionLink.md
412
+ From https://trpc.io/docs/client/links/httpSubscriptionLink#headers-and-authorization--authentication
268
413
 
269
- ### MEDIUM Async headers causing stuck isFetching
414
+ ## Authentication / connection params
270
415
 
271
- Wrong:
272
-
273
- ```ts
274
- httpBatchLink({
275
- url: '/api/trpc',
276
- async headers() {
277
- const token = await refreshToken(); // can race
278
- return { Authorization: `Bearer ${token}` };
279
- },
280
- });
281
- ```
416
+ > [!TIP]
417
+ > If you're doing a web application, you can ignore this section as the cookies are sent as part of the request.
282
418
 
283
- Correct:
284
419
 
285
- ```ts
286
- let cachedToken: string | null = null;
420
+ In order to authenticate with WebSockets, you can define `connectionParams` to `createWSClient`. This will be sent as the first message when the client establishes a WebSocket connection.
287
421
 
288
- async function ensureToken() {
289
- if (!cachedToken) cachedToken = await refreshToken();
290
- return cachedToken;
291
- }
422
+ ```ts no-check title="server/context.ts"
423
+ import type { CreateWSSContextFnOptions } from '@trpc/server/adapters/ws';
292
424
 
293
- httpBatchLink({
294
- url: '/api/trpc',
295
- async headers() {
296
- return { Authorization: `Bearer ${await ensureToken()}` };
297
- },
298
- });
299
- ```
425
+ export const createContext = async (opts: CreateWSSContextFnOptions) => {
426
+ const token = opts.info.connectionParams?.token;
300
427
 
301
- When the headers function is async (e.g., refreshing auth tokens), React Query's `isFetching` can get stuck permanently in certain race conditions.
428
+ // [... authenticate]
302
429
 
303
- Source: https://github.com/trpc/trpc/issues/7001
430
+ return {};
431
+ };
304
432
 
305
- ### HIGH Skipping auth or opening CORS too wide in prototypes
433
+ export type Context = Awaited<ReturnType<typeof createContext>>;
434
+ ```
306
435
 
307
- Wrong:
436
+ ```ts no-check title="client/trpc.ts"
437
+ import { createTRPCClient, createWSClient, wsLink } from '@trpc/client';
438
+ import type { AppRouter } from './server';
439
+ import superjson from 'superjson';
308
440
 
309
- ```ts
310
- import cors from 'cors';
441
+ const wsClient = createWSClient({
442
+ url: `ws://localhost:3000`,
311
443
 
312
- createHTTPServer({
313
- middleware: cors(), // origin: '*' by default
314
- router: appRouter,
315
- createContext() {
316
- return {};
317
- }, // no auth
318
- }).listen(3000);
444
+ connectionParams: async () => {
445
+ return {
446
+ token: 'supersecret',
447
+ };
448
+ },
449
+ });
450
+ export const trpc = createTRPCClient<AppRouter>({
451
+ links: [wsLink({ client: wsClient, transformer: superjson })],
452
+ });
319
453
  ```
320
454
 
321
- Correct:
455
+ `createContext` runs once per connection (after the connection params arrive, if you send them), and every call over that connection shares its result. If it throws, the server sends the error and closes the connection. A token is only checked when the connection opens, so it stays accepted on that connection after it expires.
322
456
 
323
- ```ts
324
- import cors from 'cors';
325
-
326
- createHTTPServer({
327
- middleware: cors({ origin: 'https://myapp.com' }),
328
- router: appRouter,
329
- createContext,
330
- }).listen(3000);
331
- ```
457
+ From https://trpc.io/docs/server/websockets#connectionParams
332
458
 
333
- Wildcard CORS and missing auth middleware are acceptable only during local development. Always restrict CORS origins and add auth before deploying.
459
+ ## References
334
460
 
335
- Source: maintainer interview
461
+ - [Send cookies cross-origin](references/client-cors.md)
336
462
 
337
- ## See Also
463
+ ## Related skills
338
464
 
339
- - **middlewares** -- context narrowing, `.use()`, `.concat()`, base procedure patterns
340
- - **subscriptions** -- SSE and WebSocket transport setup for authenticated subscriptions
341
- - **client-setup** -- `createTRPCClient`, link chain, `headers` option
342
- - **links** -- `splitLink`, `httpSubscriptionLink`, `wsLink` configuration
465
+ - `server-setup` (https://trpc.io/docs/server/overview): `npx @tanstack/intent@latest load @trpc/server#server-setup`
466
+ - `middlewares` (https://trpc.io/docs/server/middlewares): `npx @tanstack/intent@latest load @trpc/server#middlewares`
467
+ - `client-setup` (https://trpc.io/docs/client/vanilla/setup): `npx @tanstack/intent@latest load @trpc/client#client-setup`