@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.
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,60 +1,46 @@
1
1
  ---
2
2
  name: middlewares
3
- description: >
4
- Create and compose tRPC middleware with t.procedure.use(), extend context via
5
- opts.next({ ctx }), build reusable middleware with .concat() and .unstable_pipe(),
6
- define base procedures like publicProcedure and authedProcedure. Access raw input
7
- with getRawInput(). Logging, timing, OTEL tracing patterns.
8
- type: core
9
- library: trpc
10
- library_version: '11.16.0'
3
+ description: Create and compose tRPC middleware with t.procedure.use(), extend context via opts.next({ ctx }), build reusable middleware with .concat() and .unstable_pipe(), define base procedures like adminProcedure and protectedProcedure. Read unvalidated input with opts.getRawInput() before .input(), check result.ok from opts.next(). Authorization, logging and timing patterns.
11
4
  requires:
12
5
  - server-setup
13
6
  sources:
14
- - 'trpc/trpc:www/docs/server/middlewares.md'
15
- - 'trpc/trpc:www/docs/server/authorization.md'
16
- - 'trpc/trpc:packages/server/src/unstable-core-do-not-import/middleware.ts'
17
- - 'trpc/trpc:packages/server/src/unstable-core-do-not-import/procedureBuilder.ts'
7
+ - www/v11/docs/server/middlewares.md
8
+ metadata:
9
+ type: core
10
+ library: trpc
11
+ library_version: 11.23.0
18
12
  ---
19
13
 
20
- # tRPC -- Middlewares
14
+ <!-- Generated from www/v11/docs/server/middlewares.md by www/build/skills.ts. Edit the docs instead. -->
21
15
 
22
- ## Setup
16
+ # Middlewares
23
17
 
24
- ```ts
25
- // server/trpc.ts
26
- import { initTRPC, TRPCError } from '@trpc/server';
18
+ From https://trpc.io/docs/server/middlewares
27
19
 
28
- type Context = {
29
- user?: { id: string; isAdmin: boolean };
30
- };
20
+ You can add middleware(s) to a procedure with the `t.procedure.use()` method. The middleware(s) will wrap the invocation of the procedure and must call `opts.next()` and return its result.
31
21
 
32
- const t = initTRPC.context<Context>().create();
22
+ ## Authorization
33
23
 
34
- export const router = t.router;
35
- export const publicProcedure = t.procedure;
36
- export const middleware = t.middleware;
37
- ```
24
+ In the example below, any call to a `adminProcedure` will ensure that the user is an "admin" before executing.
38
25
 
39
- ## Core Patterns
26
+ ```ts no-check
27
+ import { TRPCError, initTRPC } from '@trpc/server';
40
28
 
41
- ### Auth middleware that narrows context type
42
-
43
- ```ts
44
- // server/trpc.ts
45
- import { initTRPC, TRPCError } from '@trpc/server';
46
-
47
- type Context = {
48
- user?: { id: string; isAdmin: boolean };
49
- };
29
+ interface Context {
30
+ user?: {
31
+ id: string;
32
+ isAdmin: boolean;
33
+ // [..]
34
+ };
35
+ }
50
36
 
51
37
  const t = initTRPC.context<Context>().create();
52
-
53
38
  export const publicProcedure = t.procedure;
39
+ export const router = t.router;
54
40
 
55
- export const authedProcedure = t.procedure.use(async (opts) => {
41
+ export const adminProcedure = publicProcedure.use(async (opts) => {
56
42
  const { ctx } = opts;
57
- if (!ctx.user) {
43
+ if (!ctx.user?.isAdmin) {
58
44
  throw new TRPCError({ code: 'UNAUTHORIZED' });
59
45
  }
60
46
  return opts.next({
@@ -63,31 +49,31 @@ export const authedProcedure = t.procedure.use(async (opts) => {
63
49
  },
64
50
  });
65
51
  });
52
+ ```
66
53
 
67
- export const adminProcedure = t.procedure.use(async (opts) => {
68
- const { ctx } = opts;
69
- if (!ctx.user?.isAdmin) {
70
- throw new TRPCError({ code: 'UNAUTHORIZED' });
71
- }
72
- return opts.next({
73
- ctx: {
74
- user: ctx.user,
75
- },
76
- });
54
+ ```ts no-check
55
+ import { adminProcedure, publicProcedure, router } from './trpc';
56
+
57
+ const adminRouter = router({
58
+ secretPlace: adminProcedure.query(() => 'a key'),
59
+ });
60
+
61
+ export const appRouter = router({
62
+ foo: publicProcedure.query(() => 'bar'),
63
+ admin: adminRouter,
77
64
  });
78
65
  ```
79
66
 
80
- After the middleware, `ctx.user` is non-nullable in downstream procedures.
67
+ > [!TIP]
68
+ > See [Error Handling](https://trpc.io/docs/server/error-handling) to learn more about the `TRPCError` thrown in the above example.
81
69
 
82
- ### Logging and timing middleware
83
70
 
84
- ```ts
85
- // server/trpc.ts
86
- import { initTRPC } from '@trpc/server';
71
+ ## Logging
87
72
 
88
- const t = initTRPC.create();
73
+ In the example below timings for queries are logged automatically.
89
74
 
90
- export const loggedProcedure = t.procedure.use(async (opts) => {
75
+ ```ts no-check
76
+ export const loggedProcedure = publicProcedure.use(async (opts) => {
91
77
  const start = Date.now();
92
78
 
93
79
  const result = await opts.next();
@@ -103,16 +89,108 @@ export const loggedProcedure = t.procedure.use(async (opts) => {
103
89
  });
104
90
  ```
105
91
 
106
- ### Reusable middleware with .concat()
92
+ ```ts no-check
93
+ import { loggedProcedure, router } from './trpc';
107
94
 
108
- ```ts
109
- // myPlugin.ts
110
- import { initTRPC } from '@trpc/server';
95
+ export const appRouter = router({
96
+ foo: loggedProcedure.query(() => 'bar'),
97
+ abc: loggedProcedure.query(() => 'def'),
98
+ });
99
+ ```
100
+
101
+ ## Context Extension
102
+
103
+ "Context Extension" enables middlewares to dynamically add and override keys on a base procedure's context in a typesafe manner.
104
+
105
+ Below we have an example of a middleware that changes properties of a context, the changes are then available to all chained consumers, such as other middlewares and procedures:
106
+
107
+ ```ts no-check
108
+ type Context = {
109
+ // user is nullable
110
+ user?: {
111
+ id: string;
112
+ };
113
+ };
114
+
115
+ const protectedProcedure = publicProcedure.use(async function isAuthed(opts) {
116
+ const { ctx } = opts;
117
+ // `ctx.user` is nullable
118
+ if (!ctx.user) {
119
+ throw new TRPCError({ code: 'UNAUTHORIZED' });
120
+ }
121
+
122
+ return opts.next({
123
+ ctx: {
124
+ // ✅ user value is known to be non-null now
125
+ user: ctx.user,
126
+ },
127
+ });
128
+ });
129
+
130
+ protectedProcedure.query((opts) => {
131
+ const { ctx } = opts;
132
+ return ctx.user;
133
+ });
134
+ ```
135
+
136
+ The `ctx` you pass to `opts.next()` is merged into the existing context, so you only need to pass the keys you add or override.
137
+
138
+ ## Middleware order and input
139
+
140
+ Middlewares run in the order they're chained, and the parser you pass to `.input()` runs at its position in that chain. A middleware chained before `.input()` gets `opts.input` as `undefined`; it can read the unvalidated input with `opts.getRawInput()` instead.
141
+
142
+ ```ts no-check
143
+ const auditedProcedure = publicProcedure.use(async (opts) => {
144
+ const rawInput = await opts.getRawInput();
145
+ console.log(`${opts.type} ${opts.path}`, rawInput);
146
+ return opts.next();
147
+ });
148
+
149
+ auditedProcedure
150
+ .input(z.object({ id: z.string() }))
151
+ .use((opts) => {
152
+ // after `.input()`, `opts.input` is parsed and typed
153
+ console.log(opts.input.id);
154
+ return opts.next();
155
+ })
156
+ .query((opts) => opts.input.id);
157
+ ```
158
+
159
+ Besides `ctx`, `input`, `getRawInput` and `next`, a middleware receives the procedure's `path`, `type` (`'query'`, `'mutation'` or `'subscription'`), [`meta`](https://trpc.io/docs/server/metadata), and the request's `signal`.
160
+
161
+ ## Using `.concat()` to create reusable middlewares and plugins
162
+
163
+ > [!TIP]
164
+ >
165
+ > - Creating middlewares using `t.middleware` has the limitation that the `Context` type is tied to the `Context` type of the tRPC instance.
166
+ > - Creating middlewares with `experimental_standaloneMiddleware()` has the limitation that you cannot define input parsers and similar tied to your module.
167
+
168
+
169
+ tRPC has an API called `.concat()` which allows you to independently define a partial procedure that can be used with any tRPC instance that matches the context and metadata of the plugin.
170
+
171
+ This helper primarily targets creating plugins and libraries with tRPC.
172
+
173
+
174
+ ```ts no-check
175
+ // ------------------------------------------------
176
+ // 🧩🧩🧩 a library creating a reusable plugin 🧩🧩🧩
177
+
178
+ import { initTRPC, TRPCError } from '@trpc/server';
111
179
 
112
180
  export function createMyPlugin() {
113
- const t = initTRPC.context<{}>().meta<{}>().create();
181
+ // When creating a plugin for tRPC, you use the same API as creating any other tRPC-app
182
+ // this is the plugin's root `t`-object
183
+ const t = initTRPC
184
+ .context<{
185
+ // the procedure using the plugin will need to extend this context
186
+ }>()
187
+ .meta<{
188
+ // the base `initTRPC`-object of the application using this needs to extend this meta
189
+ }>()
190
+ .create();
114
191
 
115
192
  return {
193
+ // you can also add `.input()` if you want your plugin to do input validation
116
194
  pluginProc: t.procedure.use((opts) => {
117
195
  return opts.next({
118
196
  ctx: {
@@ -122,121 +200,242 @@ export function createMyPlugin() {
122
200
  }),
123
201
  };
124
202
  }
125
- ```
126
-
127
- ```ts
128
- // server/trpc.ts
129
- import { initTRPC } from '@trpc/server';
203
+ // ------------------------------------
204
+ // 🚀🚀🚀 the app using the plugin 🚀🚀🚀
130
205
  import { createMyPlugin } from './myPlugin';
206
+ import { initTRPC, TRPCError } from '@trpc/server';
207
+
208
+
209
+ // the app's root `t`-object
210
+ const t = initTRPC
211
+ .context<{
212
+ // ...
213
+ }>()
214
+ .create();
131
215
 
132
- const t = initTRPC.context<{}>().create();
133
- const plugin = createMyPlugin();
134
216
 
135
217
  export const publicProcedure = t.procedure;
218
+ export const router = t.router;
219
+
220
+ // initialize the plugin (a real-world example would likely take options here)
221
+ const plugin = createMyPlugin();
136
222
 
137
- export const procedureWithPlugin = publicProcedure.concat(plugin.pluginProc);
223
+ // create a base procedure using the plugin
224
+ const procedureWithPlugin = publicProcedure
225
+ .concat(
226
+ plugin.pluginProc,
227
+ )
228
+ .use(opts => {
229
+ const { ctx } = opts;
230
+ return opts.next()
231
+ })
232
+
233
+
234
+ export const appRouter = router({
235
+ hello: procedureWithPlugin.query(opts => {
236
+ return opts.ctx.fromPlugin;
237
+ })
238
+ })
138
239
  ```
139
240
 
140
- `.concat()` merges a partial procedure (from any tRPC instance) into your procedure chain, as long as context and meta types overlap.
241
+ ## Extending middlewares
141
242
 
142
- ### Extending middlewares with .unstable_pipe()
243
+ > [!NOTE] Info
244
+ > We have prefixed this as `unstable_` as it's a new API, but you're safe to use it! [Read more](https://trpc.io/docs/faq#unstable).
143
245
 
144
- ```ts
145
- import { initTRPC } from '@trpc/server';
146
246
 
147
- const t = initTRPC.create();
247
+ We have a powerful feature called `.pipe()` which allows you to extend middlewares in a typesafe manner.
248
+
249
+ Below we have an example of a middleware that extends a base middleware(foo). Like the context extension example above, piping middlewares will change properties of the context, and procedures will receive the new context value.
148
250
 
251
+ ```ts no-check
149
252
  const fooMiddleware = t.middleware((opts) => {
150
253
  return opts.next({
151
- ctx: { foo: 'foo' as const },
254
+ ctx: {
255
+ foo: 'foo' as const,
256
+ },
152
257
  });
153
258
  });
154
259
 
155
260
  const barMiddleware = fooMiddleware.unstable_pipe((opts) => {
156
- console.log(opts.ctx.foo);
261
+ const { ctx } = opts;
262
+ ctx.foo;
157
263
  return opts.next({
158
- ctx: { bar: 'bar' as const },
264
+ ctx: {
265
+ bar: 'bar' as const,
266
+ },
159
267
  });
160
268
  });
161
269
 
162
- const barProcedure = t.procedure.use(barMiddleware);
270
+ const barProcedure = publicProcedure.use(barMiddleware);
271
+ barProcedure.query((opts) => {
272
+ const { ctx } = opts;
273
+ return ctx.bar;
274
+ });
163
275
  ```
164
276
 
165
- Piped middlewares run in order and each receives the context from the previous middleware.
277
+ Beware that the order in which you pipe your middlewares matter and that the context must overlap. An example of a forbidden pipe is shown below. Here, the `fooMiddleware` overrides the `ctx.a` while `barMiddleware` still expects the root context from the initialization in `initTRPC` - so piping `fooMiddleware` with `barMiddleware` would not work, while piping `barMiddleware` with `fooMiddleware` does work.
166
278
 
167
- ## Common Mistakes
279
+ ```ts no-check
280
+ import { initTRPC } from '@trpc/server';
168
281
 
169
- ### [CRITICAL] Forgetting to call and return opts.next()
282
+ const t = initTRPC
283
+ .context<{
284
+ a: {
285
+ b: 'a';
286
+ };
287
+ }>()
288
+ .create();
170
289
 
171
- Wrong:
290
+ const fooMiddleware = t.middleware((opts) => {
291
+ const { ctx } = opts;
292
+ ctx.a; // 👈 fooMiddleware expects `ctx.a` to be an object
293
+ return opts.next({
294
+ ctx: {
295
+ a: 'a' as const, // 👈 `ctx.a` is no longer an object
296
+ },
297
+ });
298
+ });
172
299
 
173
- ```ts
174
- import { initTRPC } from '@trpc/server';
300
+ const barMiddleware = t.middleware((opts) => {
301
+ const { ctx } = opts;
302
+ ctx.a; // 👈 barMiddleware expects `ctx.a` to be an object
303
+ return opts.next({
304
+ ctx: {
305
+ foo: 'foo' as const,
306
+ },
307
+ });
308
+ });
175
309
 
176
- const t = initTRPC.create();
310
+ // ❌ `ctx.a` does not overlap from `fooMiddleware` to `barMiddleware`
311
+ fooMiddleware.unstable_pipe(barMiddleware);
177
312
 
178
- const logMiddleware = t.middleware(async (opts) => {
179
- console.log('request started');
180
- // forgot to call opts.next()
181
- });
313
+ // ✅ `ctx.a` overlaps from `barMiddleware` and `fooMiddleware`
314
+ barMiddleware.unstable_pipe(fooMiddleware);
182
315
  ```
183
316
 
184
- Correct:
185
-
186
- ```ts
187
- import { initTRPC } from '@trpc/server';
317
+ ## Common mistakes
188
318
 
189
- const t = initTRPC.create();
319
+ - **Not returning `opts.next()`.** Every middleware must call `opts.next()` and return its result. Otherwise TypeScript reports an error, and at runtime the call fails with an `INTERNAL_SERVER_ERROR` ("No result from middlewares - did you forget to `return next()`?").
320
+ - **Wrapping `opts.next()` in `try`/`catch`.** `opts.next()` doesn't throw when a later middleware or the procedure fails: it resolves to a result with `ok: false` and the `TRPCError`. Check `result.ok`, like the [logging example](https://trpc.io/docs/server/middlewares#logging) does:
190
321
 
191
- const logMiddleware = t.middleware(async (opts) => {
192
- console.log('request started');
322
+ ```ts no-check
323
+ const reportedProcedure = publicProcedure.use(async (opts) => {
193
324
  const result = await opts.next();
194
- console.log('request ended');
325
+ if (!result.ok) {
326
+ console.error(`${opts.path} failed`, result.error);
327
+ }
195
328
  return result;
196
329
  });
197
330
  ```
198
331
 
199
- Middleware must call `opts.next()` and return its result; forgetting this silently drops the request with an INTERNAL_SERVER_ERROR because no middleware marker is returned.
332
+ ## Experimental: standalone middlewares
200
333
 
201
- Source: packages/server/src/unstable-core-do-not-import/procedureBuilder.ts
334
+ > [!WARNING] Deprecated
335
+ > This has been deprecated in favor of [`.concat()`](https://trpc.io/docs/server/middlewares#concat). Use `.concat()` for new code.
202
336
 
203
- ### [HIGH] Extending context with wrong type in opts.next()
204
337
 
205
- Wrong:
338
+ tRPC has an experimental API called `experimental_standaloneMiddleware` which allows you to independently define a middleware that can be used with any tRPC instance. Creating middlewares using `t.middleware` has the limitation that
339
+ the `Context` type is tied to the `Context` type of the tRPC instance. This means that you cannot use the same middleware with multiple tRPC instances that have different `Context` types.
206
340
 
207
- ```ts
208
- import { initTRPC } from '@trpc/server';
341
+ Using `experimental_standaloneMiddleware` you can create a middleware that explicitly defines its requirements, i.e. the Context, Input and Meta types:
209
342
 
210
- const t = initTRPC.create();
343
+ ```ts no-check
344
+ import {
345
+ experimental_standaloneMiddleware,
346
+ initTRPC,
347
+ TRPCError,
348
+ } from '@trpc/server';
349
+ import * as z from 'zod';
350
+
351
+ const projectAccessMiddleware = experimental_standaloneMiddleware<{
352
+ ctx: { allowedProjects: string[] }; // defaults to 'object' if not defined
353
+ input: { projectId: string }; // defaults to 'unknown' if not defined
354
+ // 'meta', not defined here, defaults to 'object | undefined'
355
+ }>().create((opts) => {
356
+ if (!opts.ctx.allowedProjects.includes(opts.input.projectId)) {
357
+ throw new TRPCError({
358
+ code: 'FORBIDDEN',
359
+ message: 'Not allowed',
360
+ });
361
+ }
211
362
 
212
- const middleware = t.middleware(async (opts) => {
213
- return opts.next({ ctx: 'not-an-object' });
363
+ return opts.next();
214
364
  });
365
+
366
+ const t1 = initTRPC
367
+ .context<{
368
+ allowedProjects: string[];
369
+ }>()
370
+ .create();
371
+
372
+ // ✅ `ctx.allowedProjects` satisfies "string[]" and `input.projectId` satisfies "string"
373
+ const accessControlledProcedure = t1.procedure
374
+ .input(z.object({ projectId: z.string() }))
375
+ .use(projectAccessMiddleware);
376
+
377
+ // ❌ `ctx.allowedProjects` satisfies "string[]" but `input.projectId` does not satisfy "string"
378
+ const accessControlledProcedure2 = t1.procedure
379
+ .input(z.object({ projectId: z.number() }))
380
+ .use(projectAccessMiddleware);
381
+
382
+ // ❌ `ctx.allowedProjects` does not satisfy "string[]" even though `input.projectId` satisfies "string"
383
+ const t2 = initTRPC
384
+ .context<{
385
+ allowedProjects: number[];
386
+ }>()
387
+ .create();
388
+
389
+ const accessControlledProcedure3 = t2.procedure
390
+ .input(z.object({ projectId: z.string() }))
391
+ .use(projectAccessMiddleware);
215
392
  ```
216
393
 
217
- Correct:
394
+ Here is an example with multiple standalone middlewares:
218
395
 
219
- ```ts
220
- import { initTRPC } from '@trpc/server';
396
+ ```ts no-check
397
+ import { experimental_standaloneMiddleware, initTRPC } from '@trpc/server';
398
+ import * as z from 'zod';
221
399
 
222
400
  const t = initTRPC.create();
401
+ const schemaA = z.object({ valueA: z.string() });
402
+ const schemaB = z.object({ valueB: z.string() });
223
403
 
224
- async function getUser() {
225
- return { id: '1', name: 'Katt' };
226
- }
404
+ const valueAUppercaserMiddleware = experimental_standaloneMiddleware<{
405
+ input: z.infer<typeof schemaA>;
406
+ }>().create((opts) => {
407
+ return opts.next({
408
+ ctx: { valueAUppercase: opts.input.valueA.toUpperCase() },
409
+ });
410
+ });
227
411
 
228
- const middleware = t.middleware(async (opts) => {
229
- return opts.next({ ctx: { user: await getUser() } });
412
+ const valueBUppercaserMiddleware = experimental_standaloneMiddleware<{
413
+ input: z.infer<typeof schemaB>;
414
+ }>().create((opts) => {
415
+ return opts.next({
416
+ ctx: { valueBUppercase: opts.input.valueB.toUpperCase() },
417
+ });
230
418
  });
231
- ```
232
419
 
233
- Context extension in `opts.next({ ctx })` must be an object; passing non-object values or overwriting required keys breaks downstream procedures.
420
+ const combinedInputThatSatisfiesBothMiddlewares = z.object({
421
+ valueA: z.string(),
422
+ valueB: z.string(),
423
+ extraProp: z.string(),
424
+ });
234
425
 
235
- Source: www/docs/server/middlewares.md
426
+ t.procedure
427
+ .input(combinedInputThatSatisfiesBothMiddlewares)
428
+ .use(valueAUppercaserMiddleware)
429
+ .use(valueBUppercaserMiddleware)
430
+ .query(
431
+ ({
432
+ input: { valueA, valueB, extraProp },
433
+ ctx: { valueAUppercase, valueBUppercase },
434
+ }) =>
435
+ `valueA: ${valueA}, valueB: ${valueB}, extraProp: ${extraProp}, valueAUppercase: ${valueAUppercase}, valueBUppercase: ${valueBUppercase}`,
436
+ );
437
+ ```
236
438
 
237
- ## See Also
439
+ ## Related skills
238
440
 
239
- - `server-setup` -- initTRPC, routers, procedures, context
240
- - `validators` -- input/output validation with Zod
241
- - `error-handling` -- TRPCError codes used in auth middleware
242
- - `auth` -- full auth patterns combining middleware + client headers
441
+ - `server-setup` (https://trpc.io/docs/server/overview): `npx @tanstack/intent@latest load @trpc/server#server-setup`