@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,31 +1,44 @@
1
1
  ---
2
2
  name: service-oriented-architecture
3
- description: >
4
- Break a tRPC backend into multiple services with custom routing links that
5
- split on the first path segment (op.path.split('.')) to route to different
6
- backend service URLs. Define a faux gateway router that merges service routers
7
- for the AppRouter type without running them in the same process. Share
8
- procedure and router definitions via a server-lib package with a single
9
- initTRPC instance. Each service runs its own standalone/Express/Fastify server.
10
- type: composition
11
- library: trpc
12
- library_version: '11.16.0'
3
+ description: Break a tRPC backend into multiple services with custom routing links that split on the first path segment (op.path.split('.')) to route to different backend service URLs. Define a faux gateway router that merges service routers for the AppRouter type without running them in the same process. Share procedure and router definitions via a server-lib package with a single initTRPC instance. Each service runs its own standalone/Express/Fastify server.
13
4
  requires:
14
5
  - server-setup
15
6
  - client-setup
16
7
  - links
17
8
  sources:
18
- - examples/soa/
9
+ - www/v11/docs/server/service-oriented-architecture.md
10
+ metadata:
11
+ type: composition
12
+ library: trpc
13
+ library_version: 11.23.0
19
14
  ---
20
15
 
21
- # tRPC — Service-Oriented Architecture
16
+ <!-- Generated from www/v11/docs/server/service-oriented-architecture.md by www/build/skills.ts. Edit the docs instead. -->
22
17
 
23
- ## Setup
18
+ # Service-Oriented Architecture
24
19
 
25
- ### Shared library (single initTRPC instance)
20
+ From https://trpc.io/docs/server/service-oriented-architecture
26
21
 
27
- ```ts
28
- // packages/server-lib/index.ts
22
+ A tRPC backend doesn't have to run as one server. You can split your routers across several services, each deployed on its own, and still call them all through one fully typed client.
23
+
24
+ > [!WARNING] Caution
25
+ > You probably don't need this. Splitting a tRPC API into services adds moving parts, and every service still has to share the same context type, error formatter and transformer. If you're not sure you need it, stick to a single router and [merge routers](https://trpc.io/docs/server/merging-routers) instead.
26
+
27
+
28
+ The setup has four parts:
29
+
30
+ - a **shared library** that creates the one tRPC instance every service uses
31
+ - the **services**, each with its own router and server
32
+ - a **faux gateway**, which merges the service routers into one `AppRouter` type but never runs
33
+ - a **client** with a custom terminating link that sends each call to the service that owns it
34
+
35
+ A runnable version is in the [SOA example](https://github.com/trpc/trpc/tree/main/examples/soa).
36
+
37
+ ## 1. Share one tRPC instance
38
+
39
+ Put `initTRPC` in a library that every service imports. This is what guarantees that the services agree on context, error formatting and transformer, so their routers can be typed together.
40
+
41
+ ```ts no-check title="server-lib/index.ts"
29
42
  import { initTRPC } from '@trpc/server';
30
43
 
31
44
  type Context = {
@@ -36,212 +49,103 @@ const t = initTRPC.context<Context>().create();
36
49
 
37
50
  export const router = t.router;
38
51
  export const publicProcedure = t.procedure;
39
- export const mergeRouters = t.mergeRouters;
40
52
  ```
41
53
 
42
- ### Service A (own server)
54
+ ## 2. Build and serve each service
55
+
56
+ Each service defines its own router with the shared helpers and runs its own server. Here they use the [standalone adapter](https://trpc.io/docs/server/adapters/standalone), but any adapter works.
43
57
 
44
- ```ts
45
- // services/service-a/router.ts
46
- import { publicProcedure, router } from '@myorg/server-lib';
58
+ ```ts no-check title="server-a/router.ts"
47
59
  import { z } from 'zod';
60
+ import { publicProcedure, router } from '../server-lib';
48
61
 
49
- export const serviceARouter = router({
62
+ export const serverARouter = router({
50
63
  greet: publicProcedure
51
- .input(z.object({ name: z.string() }))
52
- .query(({ input }) => ({ greeting: `Hello, ${input.name}!` })),
64
+ .input(z.string())
65
+ .query(({ input }) => ({ greeting: `hello, ${input}!` })),
53
66
  });
54
67
  ```
55
68
 
56
- ```ts
57
- // services/service-a/index.ts
69
+ ```ts no-check title="server-a/index.ts"
58
70
  import { createHTTPServer } from '@trpc/server/adapters/standalone';
59
- import { serviceARouter } from './router';
71
+ import { serverARouter } from './router';
60
72
 
61
73
  createHTTPServer({
62
- router: serviceARouter,
74
+ router: serverARouter,
63
75
  createContext() {
64
76
  return {};
65
77
  },
66
78
  }).listen(2021);
67
79
  ```
68
80
 
69
- ### Service B (own server)
81
+ `server-b` looks the same, with its own router, `serverBRouter`, listening on port 2022.
70
82
 
71
- ```ts
72
- // services/service-b/router.ts
73
- import { publicProcedure, router } from '@myorg/server-lib';
83
+ ## 3. Combine the types in a faux gateway
74
84
 
75
- export const serviceBRouter = router({
76
- status: publicProcedure.query(() => ({ status: 'ok' })),
77
- });
78
- ```
85
+ The gateway merges the service routers under one name each, and exports the result's type. It's never deployed or run: the client only imports its `AppRouter` type, so none of the services' code ends up in the client.
79
86
 
80
- ```ts
81
- // services/service-b/index.ts
82
- import { createHTTPServer } from '@trpc/server/adapters/standalone';
83
- import { serviceBRouter } from './router';
84
-
85
- createHTTPServer({
86
- router: serviceBRouter,
87
- createContext() {
88
- return {};
89
- },
90
- }).listen(2022);
91
- ```
92
-
93
- ### Gateway (type-only, not a running server)
94
-
95
- ```ts
96
- // gateway/index.ts
97
- import { router } from '@myorg/server-lib';
98
- import { serviceARouter } from '../services/service-a/router';
99
- import { serviceBRouter } from '../services/service-b/router';
87
+ ```ts no-check title="faux-gateway/index.ts"
88
+ import { serverARouter } from '../server-a/router';
89
+ import { serverBRouter } from '../server-b/router';
90
+ import { router } from '../server-lib';
100
91
 
101
92
  const appRouter = router({
102
- serviceA: serviceARouter,
103
- serviceB: serviceBRouter,
93
+ serverA: serverARouter,
94
+ serverB: serverBRouter,
104
95
  });
105
96
 
106
97
  export type AppRouter = typeof appRouter;
107
98
  ```
108
99
 
109
- The gateway merges routers only for type inference. It does not run as a server process. The client uses the `AppRouter` type for full type safety.
110
-
111
- ### Client with custom routing link
112
-
113
- ```ts
114
- // client/client.ts
115
- import { createTRPCClient, httpBatchLink } from '@trpc/client';
116
- import type { AppRouter } from '../gateway';
117
-
118
- export const client = createTRPCClient<AppRouter>({
119
- links: [
120
- (runtime) => {
121
- const servers = {
122
- serviceA: httpBatchLink({ url: 'http://localhost:2021' })(runtime),
123
- serviceB: httpBatchLink({ url: 'http://localhost:2022' })(runtime),
124
- };
125
-
126
- return (ctx) => {
127
- const { op } = ctx;
128
- const pathParts = op.path.split('.');
129
- const serverName = pathParts.shift() as keyof typeof servers;
130
- const path = pathParts.join('.');
131
-
132
- const link = servers[serverName];
133
- if (!link) {
134
- throw new Error(
135
- `Unknown service: ${String(serverName)}. Known: ${Object.keys(servers).join(', ')}`,
136
- );
137
- }
138
- return link({
139
- ...ctx,
140
- op: { ...op, path },
141
- });
142
- };
143
- },
144
- ],
145
- });
146
- ```
147
-
148
- ```ts
149
- // Usage
150
- const greeting = await client.serviceA.greet.query({ name: 'World' });
151
- const status = await client.serviceB.status.query();
152
- ```
100
+ ## 4. Route calls to the right service
153
101
 
154
- ## Core Patterns
102
+ On the client, a [custom link](https://trpc.io/docs/client/links#creating-a-custom-link) reads the first segment of each procedure path, `serverA` in `serverA.greet`, and forwards the call to that service's link with the segment removed, since the service itself only knows `greet`.
155
103
 
156
- ### Path-based routing convention
104
+ ```ts no-check title="client/client.ts"
105
+ import { createTRPCClient, httpBatchLink, type TRPCLink } from '@trpc/client';
106
+ import type { AppRouter } from '../faux-gateway';
157
107
 
158
- ```ts
159
- (runtime) => {
160
- const servers = {
161
- users: httpBatchLink({ url: 'http://users-service:3000' })(runtime),
162
- billing: httpBatchLink({ url: 'http://billing-service:3000' })(runtime),
163
- notifications: httpBatchLink({ url: 'http://notifications-service:3000' })(
164
- runtime,
165
- ),
108
+ const serviceLink: TRPCLink<AppRouter> = (runtime) => {
109
+ // Created once, so calls to the same service are batched together
110
+ const services = {
111
+ serverA: httpBatchLink<AppRouter>({ url: 'http://localhost:2021' })(runtime),
112
+ serverB: httpBatchLink<AppRouter>({ url: 'http://localhost:2022' })(runtime),
166
113
  };
167
114
 
168
115
  return (ctx) => {
169
- const { op } = ctx;
170
- const [serverName, ...rest] = op.path.split('.');
171
- const link = servers[serverName as keyof typeof servers];
172
-
116
+ const [name, ...rest] = ctx.op.path.split('.');
117
+ const link = services[name as keyof typeof services];
173
118
  if (!link) {
174
- throw new Error(`Unknown service: ${serverName}`);
119
+ throw new Error(`No service for procedure "${ctx.op.path}"`);
175
120
  }
176
-
177
- return link({
178
- ...ctx,
179
- op: { ...op, path: rest.join('.') },
180
- });
121
+ return link({ ...ctx, op: { ...ctx.op, path: rest.join('.') } });
181
122
  };
182
123
  };
183
- ```
184
124
 
185
- The first segment of the procedure path (before the first `.`) maps to a service name. The remaining path is forwarded to the target service.
186
-
187
- ### Adding shared headers across services
188
-
189
- ```ts
190
- (runtime) => {
191
- const servers = {
192
- serviceA: httpBatchLink({
193
- url: 'http://localhost:2021',
194
- headers() {
195
- return { 'x-request-id': crypto.randomUUID() };
196
- },
197
- })(runtime),
198
- serviceB: httpBatchLink({
199
- url: 'http://localhost:2022',
200
- headers() {
201
- return { 'x-request-id': crypto.randomUUID() };
202
- },
203
- })(runtime),
204
- };
205
-
206
- return (ctx) => {
207
- const [serverName, ...rest] = ctx.op.path.split('.');
208
- return servers[serverName as keyof typeof servers]({
209
- ...ctx,
210
- op: { ...ctx.op, path: rest.join('.') },
211
- });
212
- };
213
- };
125
+ export const client = createTRPCClient<AppRouter>({
126
+ links: [serviceLink],
127
+ });
214
128
  ```
215
129
 
216
- ## Common Mistakes
217
-
218
- ### MEDIUM Path routing assumes first segment is server name
219
-
220
- Wrong:
221
-
222
- ```ts
223
- const serverName = op.path.split('.').shift();
224
- // Breaks if router structure changes or has nested namespaces
225
- ```
130
+ Each service gets its own link, so each can have its own options, such as [headers](https://trpc.io/docs/client/headers). Calls are fully typed through the gateway's `AppRouter`:
226
131
 
227
- Correct:
132
+ ```ts no-check title="client/index.ts"
133
+ import { client } from './client';
228
134
 
229
- ```ts
230
- const [serverName, ...rest] = op.path.split('.');
231
- const link = servers[serverName as keyof typeof servers];
232
- if (!link) {
233
- throw new Error(`Unknown service: ${serverName}. Known: ${Object.keys(servers).join(', ')}`);
234
- }
235
- return link({ ...ctx, op: { ...op, path: rest.join('.') } });
135
+ const { greeting } = await client.serverA.greet.query('tRPC');
136
+ const status = await client.serverB.status.query();
236
137
  ```
237
138
 
238
- Custom routing links that split on the first path segment break silently if the router structure changes. Add validation and clear error messages when the server name is unrecognized. The path convention must be documented and enforced across teams.
139
+ ## Common mistakes
239
140
 
240
- Source: examples/soa/client/client.ts
141
+ - **Forwarding the full path.** If the link doesn't strip the service name, the service is asked for `serverA.greet` and answers with `No procedure found on path "serverA.greet"`.
142
+ - **Creating the service links per call.** `httpBatchLink(...)(runtime)` sets up a new batch queue each time it runs, so create the service links once, in the setup function, as shown above. Otherwise nothing gets batched.
143
+ - **Using a separate `initTRPC` in each service.** The gateway's `AppRouter` can only describe one context, error shape and transformer, so give every service the same instance from the shared library.
144
+ - **Leaving the router type off the service links.** Links created inside a custom link aren't checked against your router. Pass `<AppRouter>`, as in `httpBatchLink<AppRouter>(...)`, so TypeScript still requires a [transformer](https://trpc.io/docs/server/data-transformers) when you use one.
145
+ - **Running the gateway.** The faux gateway only exists for its type. Each service serves its own router, and the client talks to the services directly.
241
146
 
242
- ## See Also
147
+ ## Related skills
243
148
 
244
- - **server-setup** -- single `initTRPC.create()` instance shared across services
245
- - **links** -- `httpBatchLink`, custom link authoring
246
- - **client-setup** -- `createTRPCClient`, type-safe client with `AppRouter`
247
- - **adapter-standalone** -- running individual service servers
149
+ - `server-setup` (https://trpc.io/docs/server/overview): `npx @tanstack/intent@latest load @trpc/server#server-setup`
150
+ - `client-setup` (https://trpc.io/docs/client/vanilla/setup): `npx @tanstack/intent@latest load @trpc/client#client-setup`
151
+ - `links` (https://trpc.io/docs/client/links): `npx @tanstack/intent@latest load @trpc/client#links`