@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,378 +1,480 @@
1
1
  ---
2
2
  name: server-setup
3
- description: >
4
- Initialize tRPC with initTRPC.create(), define routers with t.router(),
5
- create procedures with .query()/.mutation()/.subscription(), configure context
6
- with createContext(), export AppRouter type, merge routers with t.mergeRouters(),
7
- lazy-load routers with lazy().
8
- type: core
9
- library: trpc
10
- library_version: '11.16.0'
11
- requires: []
3
+ description: Set up a tRPC server. Initialize tRPC once with initTRPC.context<Context>().create(), define routers with t.router() and procedures with .query()/.mutation(), build reusable base procedures such as publicProcedure and authedProcedure, type and create the request context with createContext() (inner/outer context for tests and server-side calls), export the AppRouter type, nest child routers or merge them with t.mergeRouters(), lazy-load routers with lazy().
12
4
  sources:
13
- - 'trpc/trpc:www/docs/server/overview.md'
14
- - 'trpc/trpc:www/docs/server/routers.md'
15
- - 'trpc/trpc:www/docs/server/procedures.md'
16
- - 'trpc/trpc:www/docs/server/context.md'
17
- - 'trpc/trpc:www/docs/server/merging-routers.md'
18
- - 'trpc/trpc:www/docs/main/quickstart.mdx'
19
- - 'trpc/trpc:packages/server/src/unstable-core-do-not-import/initTRPC.ts'
20
- - 'trpc/trpc:packages/server/src/unstable-core-do-not-import/router.ts'
5
+ - www/v11/docs/server/overview.md
6
+ - www/v11/docs/server/routers.md
7
+ - www/v11/docs/server/procedures.md
8
+ - www/v11/docs/server/context.md
9
+ - www/v11/docs/server/merging-routers.md
10
+ - www/v11/docs/server/metadata.md
11
+ metadata:
12
+ type: core
13
+ library: trpc
14
+ library_version: 11.23.0
21
15
  ---
22
16
 
23
- # tRPC -- Server Setup
17
+ <!-- Generated from www/v11/docs/server/overview.md by www/build/skills.ts. Edit the docs instead. -->
24
18
 
25
- ## Setup
19
+ # Backend Usage
26
20
 
27
- ```ts
28
- // server/trpc.ts
21
+ From https://trpc.io/docs/server/overview
22
+
23
+ This section covers everything you need to set up and configure your tRPC backend. You'll learn how to define [routers](https://trpc.io/docs/server/routers) and [procedures](https://trpc.io/docs/server/procedures), set up [context](https://trpc.io/docs/server/context), add [input validation](https://trpc.io/docs/server/validators), and use [middlewares](https://trpc.io/docs/server/middlewares) to extend your API.
24
+
25
+ Once your API is defined, you can host it using one of the available [adapters](https://trpc.io/docs/server/adapters) for platforms like Express, Fastify, Next.js, AWS Lambda, and more.
26
+
27
+ ## Initialize tRPC
28
+
29
+ You should initialize tRPC **exactly once** per application. Multiple instances of tRPC will cause issues: for example, `t.mergeRouters()` throws if the routers come from different instances that each set a [transformer](https://trpc.io/docs/server/data-transformers) or [error formatter](https://trpc.io/docs/server/error-formatting). Create `t` in one file and import your procedures and `router` from it everywhere.
30
+
31
+ ```ts no-check title="server/trpc.ts"
29
32
  import { initTRPC } from '@trpc/server';
30
33
 
34
+ // You can use any variable name you like.
35
+ // We use t to keep things simple.
31
36
  const t = initTRPC.create();
32
37
 
33
38
  export const router = t.router;
34
39
  export const publicProcedure = t.procedure;
35
40
  ```
36
41
 
37
- ```ts
38
- // server/appRouter.ts
39
- import { z } from 'zod';
40
- import { publicProcedure, router } from './trpc';
42
+ You'll notice we are exporting certain methods of the `t` variable here rather than `t` itself. This is to establish a certain set of procedures that we will use idiomatically in our codebase.
41
43
 
42
- type User = { id: string; name: string };
44
+ From https://trpc.io/docs/server/routers#initialize-trpc
43
45
 
44
- export const appRouter = router({
45
- userList: publicProcedure.query(async (): Promise<User[]> => {
46
- return [{ id: '1', name: 'Katt' }];
47
- }),
48
- userById: publicProcedure
49
- .input(z.string())
50
- .query(async ({ input }): Promise<User> => {
51
- return { id: input, name: 'Katt' };
52
- }),
53
- userCreate: publicProcedure
54
- .input(z.object({ name: z.string() }))
55
- .mutation(async ({ input }): Promise<User> => {
56
- return { id: '1', ...input };
57
- }),
58
- });
46
+ ## Defining a router
59
47
 
60
- export type AppRouter = typeof appRouter;
61
- ```
48
+ Next, let's define a router with a procedure to use in our application. We have now created an API "endpoint".
62
49
 
63
- ```ts
64
- // server/index.ts
65
- import { createHTTPServer } from '@trpc/server/adapters/standalone';
66
- import { appRouter } from './appRouter';
50
+ In order for these endpoints to be exposed to the frontend, your [Adapter](https://trpc.io/docs/server/adapters) should be configured with your `appRouter` instance.
67
51
 
68
- const server = createHTTPServer({ router: appRouter });
69
- server.listen(3000);
70
- ```
52
+ ```ts no-check title="server/_app.ts"
53
+ import { publicProcedure, router } from './trpc';
71
54
 
72
- ## Core Patterns
55
+ const appRouter = router({
56
+ greeting: publicProcedure.query(() => 'hello tRPC v11!'),
57
+ });
73
58
 
74
- ### Context with typed session
59
+ // Export only the type of a router!
60
+ // This prevents us from importing server code on the client.
61
+ export type AppRouter = typeof appRouter;
62
+ ```
75
63
 
76
- ```ts
77
- // server/context.ts
78
- import type { CreateHTTPContextOptions } from '@trpc/server/adapters/standalone';
64
+ On the client, import it with `import type { AppRouter } from '...'` and never import the `appRouter` value: a type-only import is always erased, so your server code can't end up in the client bundle.
79
65
 
80
- export async function createContext(opts: CreateHTTPContextOptions) {
81
- const token = opts.req.headers['authorization'];
82
- return { token };
83
- }
66
+ Procedures can't be named `then`, `call` or `apply`: `router()` throws if you use these names.
84
67
 
85
- export type Context = Awaited<ReturnType<typeof createContext>>;
86
- ```
68
+ From https://trpc.io/docs/server/routers#defining-a-router
87
69
 
88
- ```ts
89
- // server/trpc.ts
90
- import { initTRPC } from '@trpc/server';
91
- import type { Context } from './context';
70
+ ## Defining an inline sub-router
92
71
 
93
- const t = initTRPC.context<Context>().create();
72
+ When you define an inline sub-router, you can represent your router as a plain object.
94
73
 
95
- export const router = t.router;
96
- export const publicProcedure = t.procedure;
97
- ```
74
+ In the below example, `nested1` and `nested2` are equal:
98
75
 
99
- ```ts
100
- // server/index.ts
101
- import { createHTTPServer } from '@trpc/server/adapters/standalone';
102
- import { appRouter } from './appRouter';
103
- import { createContext } from './context';
76
+ ```ts no-check title="server/_app.ts"
77
+ import * as trpc from '@trpc/server';
78
+ import { publicProcedure, router } from './trpc';
104
79
 
105
- const server = createHTTPServer({
106
- router: appRouter,
107
- createContext,
80
+ const appRouter = router({
81
+ // Using the router() method
82
+ nested1: router({
83
+ proc: publicProcedure.query(() => '...'),
84
+ }),
85
+ // Using an inline sub-router
86
+ nested2: {
87
+ proc: publicProcedure.query(() => '...'),
88
+ },
108
89
  });
109
- server.listen(3000);
110
90
  ```
111
91
 
112
- ### Inner/outer context split for testability
92
+ From https://trpc.io/docs/server/routers#inline-sub-router
113
93
 
114
- ```ts
115
- // server/context.ts
116
- import type { CreateHTTPContextOptions } from '@trpc/server/adapters/standalone';
117
- import { db } from './db';
94
+ ## Writing procedures
118
95
 
119
- interface CreateInnerContextOptions {
120
- session: { user: { email: string } } | null;
121
- }
96
+ The `t` object you create during tRPC setup returns an initial `t.procedure` which all other procedures are built on:
122
97
 
123
- export async function createContextInner(opts?: CreateInnerContextOptions) {
124
- return {
125
- db,
126
- session: opts?.session ?? null,
127
- };
128
- }
98
+ ```ts no-check
99
+ import { initTRPC } from '@trpc/server';
100
+ import { z } from 'zod';
129
101
 
130
- export async function createContext(opts: CreateHTTPContextOptions) {
131
- const session = getSessionFromCookie(opts.req);
132
- const contextInner = await createContextInner({ session });
133
- return {
134
- ...contextInner,
135
- req: opts.req,
136
- res: opts.res,
137
- };
138
- }
102
+ const t = initTRPC.context<{ signGuestBook: () => Promise<void> }>().create();
139
103
 
140
- export type Context = Awaited<ReturnType<typeof createContextInner>>;
141
- ```
142
-
143
- Infer `Context` from `createContextInner` so server-side callers and tests never need HTTP request objects.
104
+ export const router = t.router;
105
+ export const publicProcedure = t.procedure;
144
106
 
145
- ### Merging child routers
107
+ const appRouter = router({
108
+ // Queries are the best place to fetch data
109
+ hello: publicProcedure.query(() => {
110
+ return {
111
+ message: 'hello world',
112
+ };
113
+ }),
146
114
 
147
- ```ts
148
- // server/routers/user.ts
149
- import { publicProcedure, router } from '../trpc';
115
+ // Mutations are the best place to do things like updating a database
116
+ goodbye: publicProcedure.mutation(async (opts) => {
117
+ await opts.ctx.signGuestBook();
150
118
 
151
- export const userRouter = router({
152
- list: publicProcedure.query(() => []),
119
+ return {
120
+ message: 'goodbye!',
121
+ };
122
+ }),
153
123
  });
154
124
  ```
155
125
 
156
- ```ts
157
- // server/routers/post.ts
158
- import { z } from 'zod';
159
- import { publicProcedure, router } from '../trpc';
126
+ From https://trpc.io/docs/server/procedures#writing-procedures
160
127
 
161
- export const postRouter = router({
162
- create: publicProcedure
163
- .input(z.object({ title: z.string() }))
164
- .mutation(({ input }) => ({ id: '1', ...input })),
165
- list: publicProcedure.query(() => []),
166
- });
167
- ```
128
+ ## Reusable "Base Procedures"
168
129
 
169
- ```ts
170
- // server/routers/_app.ts
171
- import { router } from '../trpc';
172
- import { postRouter } from './post';
173
- import { userRouter } from './user';
130
+ As a general pattern we recommend you rename and export `t.procedure` as `publicProcedure`, which then makes room for you to create other named procedures for specific use cases and export those too. This pattern is called "base procedures" and is a key pattern for code and behaviour re-use in tRPC; every application is likely to need it.
174
131
 
175
- export const appRouter = router({
176
- user: userRouter,
177
- post: postRouter,
178
- });
132
+ In the below code, we're using reusable base procedures to build common use-cases for our app - we're making a reusable base procedures for logged in users (`authedProcedure`) & another base procedure that takes an `organizationId` and validates that a user is part of that organization.
179
133
 
180
- export type AppRouter = typeof appRouter;
181
- ```
134
+ > This is a simplified example; in practice you may want to use some combination of [Headers](https://trpc.io/docs/client/headers), [Context](https://trpc.io/docs/server/context), [Middleware](https://trpc.io/docs/server/middlewares), and [Metadata](https://trpc.io/docs/server/metadata), to [authenticate](https://en.wikipedia.org/wiki/Authentication) and [authorize](https://trpc.io/docs/server/authorization) your users.
182
135
 
183
- ### Lazy-loaded routers for serverless cold starts
136
+ ```ts no-check
137
+ import { initTRPC, TRPCError } from '@trpc/server';
138
+ import { z } from 'zod';
184
139
 
185
- ```ts
186
- // server/routers/_app.ts
187
- import { lazy } from '@trpc/server';
188
- import { router } from '../trpc';
140
+ type Organization = {
141
+ id: string;
142
+ name: string;
143
+ };
144
+ type Membership = {
145
+ role: 'ADMIN' | 'MEMBER';
146
+ Organization: Organization;
147
+ };
148
+ type User = {
149
+ id: string;
150
+ memberships: Membership[];
151
+ };
152
+ type Context = {
153
+ /**
154
+ * User is nullable
155
+ */
156
+ user: User | null;
157
+ };
189
158
 
190
- export const appRouter = router({
191
- // Short-hand when the module has exactly one router exported
192
- greeting: lazy(() => import('./greeting.js')),
193
- // Use .then() to pick a named export when the module exports multiple routers
194
- user: lazy(() => import('./user.js').then((m) => m.userRouter)),
159
+ const t = initTRPC.context<Context>().create();
160
+
161
+ export const publicProcedure = t.procedure;
162
+
163
+ // procedure that asserts that the user is logged in
164
+ export const authedProcedure = t.procedure.use(async function isAuthed(opts) {
165
+ const { ctx } = opts;
166
+ // `ctx.user` is nullable
167
+ if (!ctx.user) {
168
+ throw new TRPCError({ code: 'UNAUTHORIZED' });
169
+ }
170
+
171
+ return opts.next({
172
+ ctx: {
173
+ // ✅ user value is known to be non-null now
174
+ user: ctx.user,
175
+ },
176
+ });
195
177
  });
196
178
 
197
- export type AppRouter = typeof appRouter;
179
+ // procedure that asserts a user is a member of a specific organization
180
+ export const organizationProcedure = authedProcedure
181
+ .input(z.object({ organizationId: z.string() }))
182
+ .use(function isMemberOfOrganization(opts) {
183
+ const membership = opts.ctx.user.memberships.find(
184
+ (m) => m.Organization.id === opts.input.organizationId,
185
+ );
186
+ if (!membership) {
187
+ throw new TRPCError({
188
+ code: 'FORBIDDEN',
189
+ });
190
+ }
191
+ return opts.next({
192
+ ctx: {
193
+ Organization: membership.Organization,
194
+ },
195
+ });
196
+ });
197
+
198
+ export const appRouter = t.router({
199
+ whoami: authedProcedure.query(async (opts) => {
200
+ // user is non-nullable here
201
+ const { ctx } = opts;
202
+ return ctx.user;
203
+ }),
204
+ addMember: organizationProcedure
205
+ .input(
206
+ z.object({
207
+ email: z.string().email(),
208
+ }),
209
+ )
210
+ .mutation((opts) => {
211
+ // ctx contains the non-nullable user & the organization being queried
212
+ const { ctx } = opts;
213
+
214
+ // input includes the validated email of the user being invited & the validated organizationId
215
+ const { input } = opts;
216
+
217
+ return '...';
218
+ }),
219
+ });
198
220
  ```
199
221
 
200
- ## Common Mistakes
222
+ From https://trpc.io/docs/server/procedures#reusable-base-procedures
201
223
 
202
- ### [CRITICAL] Calling initTRPC.create() more than once
224
+ ## Defining the context type
203
225
 
204
- Wrong:
226
+ When initializing tRPC using `initTRPC`, you should pipe `.context<TContext>()` to the `initTRPC` builder function before calling `.create()`. The type `TContext` can either be inferred from a function's return type or be explicitly defined.
205
227
 
206
- ```ts
207
- // file: userRouter.ts
208
- import { initTRPC } from '@trpc/server';
209
- const t = initTRPC.create();
210
- export const userRouter = t.router({});
228
+ This will make sure your context is properly typed in your procedures and middlewares.
211
229
 
212
- // file: postRouter.ts
230
+ ```ts no-check
213
231
  import { initTRPC } from '@trpc/server';
214
- const t2 = initTRPC.create();
215
- export const postRouter = t2.router({});
216
- ```
232
+ import type { CreateHTTPContextOptions } from '@trpc/server/adapters/standalone';
217
233
 
218
- Correct:
234
+ export const createContext = async (opts: CreateHTTPContextOptions) => {
235
+ // Example: extract a session token from the request headers
236
+ const token = opts.req.headers['authorization'];
219
237
 
220
- ```ts
221
- // file: trpc.ts (single file, created once)
222
- import { initTRPC } from '@trpc/server';
223
- import type { Context } from './context';
238
+ return {
239
+ token,
240
+ };
241
+ };
224
242
 
243
+ export type Context = Awaited<ReturnType<typeof createContext>>;
225
244
  const t = initTRPC.context<Context>().create();
226
245
 
227
- export const router = t.router;
228
- export const publicProcedure = t.procedure;
246
+ t.procedure.use((opts) => {
247
+ opts.ctx;
248
+
249
+ return opts.next();
250
+ });
229
251
  ```
230
252
 
231
- Multiple tRPC instances cause type mismatches and runtime errors when routers from different instances are merged.
253
+ From https://trpc.io/docs/server/context#defining-the-context-type
232
254
 
233
- Source: www/docs/server/routers.md
255
+ ## Creating the context
234
256
 
235
- ### [HIGH] Using reserved words as procedure names
257
+ The `createContext()` function must be passed to the handler mounting your appRouter. The handler may use HTTP or a [server-side call](https://trpc.io/docs/server/server-side-calls).
236
258
 
237
- Wrong:
259
+ `createContext()` is called once per request, so all procedures within a single batched request share the same context.
238
260
 
239
- ```ts
240
- import { publicProcedure, router } from './trpc';
261
+ ```ts no-check
262
+ // 1. HTTP request
263
+ import { createHTTPHandler } from '@trpc/server/adapters/standalone';
264
+ import { createContext } from './context';
265
+ import { appRouter } from './router';
241
266
 
242
- const appRouter = router({
243
- then: publicProcedure.query(() => 'hello'),
267
+ const handler = createHTTPHandler({
268
+ router: appRouter,
269
+ createContext,
244
270
  });
245
271
  ```
246
272
 
247
- Correct:
248
-
249
- ```ts
250
- import { publicProcedure, router } from './trpc';
273
+ ```ts no-check
274
+ // 2. Server-side call
275
+ import { createContext } from './context';
276
+ import { createCaller } from './router';
251
277
 
252
- const appRouter = router({
253
- next: publicProcedure.query(() => 'hello'),
254
- });
278
+ const caller = createCaller(await createContext());
255
279
  ```
256
280
 
257
- Router creation throws if procedure names are "then", "call", or "apply" because these conflict with JavaScript Proxy internals.
281
+ ```ts no-check
282
+ // 3. Server-side helpers (Next.js-specific, see /docs/client/nextjs/pages-router/server-side-helpers)
283
+ import { createServerSideHelpers } from '@trpc/react-query/server';
284
+ import { createContext } from './context';
285
+ import { appRouter } from './router';
258
286
 
259
- Source: packages/server/src/unstable-core-do-not-import/router.ts
287
+ const helpers = createServerSideHelpers({
288
+ router: appRouter,
289
+ ctx: await createContext(),
290
+ });
291
+ ```
260
292
 
261
- ### [CRITICAL] Importing AppRouter as a value import
293
+ From https://trpc.io/docs/server/context#creating-the-context
262
294
 
263
- Wrong:
295
+ ## Inner and outer context
264
296
 
265
- ```ts
266
- // client.ts
267
- import { AppRouter } from '../server/router';
268
- ```
297
+ In some scenarios it could make sense to split up your context into "inner" and "outer" functions.
269
298
 
270
- Correct:
299
+ **Inner context** is where you define context which doesn’t depend on the request, e.g. your database connection. You can use this function for integration testing or [server-side calls](https://trpc.io/docs/server/server-side-calls), where you don’t have a request object. Whatever is defined here will **always** be available in your procedures.
271
300
 
272
- ```ts
273
- // client.ts
274
- import type { AppRouter } from '../server/router';
275
- ```
301
+ > [!NOTE] Tradeoff for large clients in `createContextInner`
302
+ > Putting a database client such as `prisma` on `createContextInner` is convenient and common, but large generated clients (like Prisma) can increase type-checking overhead because they become part of your context type across procedures.
303
+ >
304
+ > If that overhead becomes noticeable, an alternative is to keep context smaller and import the client directly at call sites where needed.
276
305
 
277
- A non-type import pulls the entire server bundle into the client; use `import type` so it is stripped at build time.
278
306
 
279
- Source: www/docs/server/routers.md
307
+ **Outer context** is where you define context which depends on the request, e.g. for the user's session. Whatever is defined here is only available for procedures that are called via HTTP.
280
308
 
281
- ### [MEDIUM] Creating context without inner/outer split
309
+ ### Example for inner & outer context
282
310
 
283
- Wrong:
311
+ ```ts no-check
312
+ import type { CreateHTTPContextOptions } from '@trpc/server/adapters/standalone';
313
+ import { getSessionFromCookie, type Session } from './auth';
314
+ import { db } from './db';
284
315
 
285
- ```ts
286
- import type { CreateExpressContextOptions } from '@trpc/server/adapters/express';
316
+ /**
317
+ * Defines your inner context shape.
318
+ * Add fields here that the inner context brings.
319
+ */
320
+ interface CreateInnerContextOptions {
321
+ session: Session | null;
322
+ }
287
323
 
288
- export function createContext({ req }: CreateExpressContextOptions) {
289
- return { db: prisma, user: getUserFromReq(req) };
324
+ /**
325
+ * Inner context. Will always be available in your procedures, in contrast to the outer context.
326
+ *
327
+ * Also useful for:
328
+ * - testing, so you don't have to mock `req`/`res`
329
+ * - server-side calls where we don't have `req`/`res`
330
+ *
331
+ * @see https://trpc.io/docs/v11/context#inner-and-outer-context
332
+ */
333
+ export async function createContextInner(opts?: CreateInnerContextOptions) {
334
+ return {
335
+ db,
336
+ session: opts?.session,
337
+ };
290
338
  }
291
- ```
292
339
 
293
- Correct:
340
+ /**
341
+ * Outer context. Used in the routers and will e.g. bring `req` & `res` to the context as "not `undefined`".
342
+ *
343
+ * @see https://trpc.io/docs/v11/context#inner-and-outer-context
344
+ */
345
+ export async function createContext(opts: CreateHTTPContextOptions) {
346
+ const session = getSessionFromCookie(opts.req);
294
347
 
295
- ```ts
296
- import type { CreateExpressContextOptions } from '@trpc/server/adapters/express';
348
+ const contextInner = await createContextInner({ session });
297
349
 
298
- export function createContextInner(opts: { user?: User }) {
299
- return { db: prisma, user: opts.user ?? null };
350
+ return {
351
+ ...contextInner,
352
+ req: opts.req,
353
+ res: opts.res,
354
+ };
300
355
  }
301
356
 
302
- export function createContext({ req }: CreateExpressContextOptions) {
303
- return createContextInner({ user: getUserFromReq(req) });
304
- }
305
- ```
357
+ export type Context = Awaited<ReturnType<typeof createContextInner>>;
306
358
 
307
- Without an inner context factory, server-side callers and tests must construct HTTP request objects to get context.
359
+ // The usage in your router is the same as the example above.
360
+ ```
308
361
 
309
- Source: www/docs/server/context.md
362
+ It is important to infer your `Context` from the **inner** context, as only what is defined there is really always available in your procedures.
363
+
364
+ If you don't want to check `req` or `res` for `undefined` in your procedures all the time, you could build a small reusable procedure for that:
365
+
366
+ ```ts no-check
367
+ export const apiProcedure = publicProcedure.use((opts) => {
368
+ if (!opts.ctx.req || !opts.ctx.res) {
369
+ throw new Error('You are missing `req` or `res` in your call.');
370
+ }
371
+ return opts.next({
372
+ ctx: {
373
+ // We overwrite the context with the truthy `req` & `res`, which will also overwrite the types used in your procedure.
374
+ req: opts.ctx.req,
375
+ res: opts.ctx.res,
376
+ },
377
+ });
378
+ });
379
+ ```
310
380
 
311
- ### [HIGH] Merging routers with different transformers
381
+ From https://trpc.io/docs/server/context#inner-and-outer-context
312
382
 
313
- Wrong:
383
+ ## Merging with child routers
314
384
 
315
- ```ts
316
- import { initTRPC } from '@trpc/server';
317
- import superjson from 'superjson';
385
+ ```ts no-check title="routers/user.ts"
386
+ import { router, publicProcedure } from '../trpc';
387
+ import { z } from 'zod';
318
388
 
319
- const t1 = initTRPC.create({ transformer: superjson });
320
- const t2 = initTRPC.create();
389
+ export const userRouter = router({
390
+ list: publicProcedure.query(() => {
391
+ // [..]
392
+ return [];
393
+ }),
394
+ });
395
+ ```
321
396
 
322
- const router1 = t1.router({ a: t1.procedure.query(() => 'a') });
323
- const router2 = t2.router({ b: t2.procedure.query(() => 'b') });
397
+ ```ts no-check title="routers/post.ts"
398
+ import { router, publicProcedure } from '../trpc';
399
+ import { z } from 'zod';
324
400
 
325
- t1.mergeRouters(router1, router2);
401
+ export const postRouter = router({
402
+ create: publicProcedure
403
+ .input(
404
+ z.object({
405
+ title: z.string(),
406
+ }),
407
+ )
408
+ .mutation((opts) => {
409
+ const { input } = opts;
410
+ // [...]
411
+ }),
412
+ list: publicProcedure.query(() => {
413
+ // ...
414
+ return [];
415
+ }),
416
+ });
326
417
  ```
327
418
 
328
- Correct:
419
+ ```ts no-check title="routers/_app.ts"
420
+ import { router } from '../trpc';
329
421
 
330
- ```ts
331
- import { initTRPC } from '@trpc/server';
332
- import superjson from 'superjson';
422
+ import { userRouter } from './user';
423
+ import { postRouter } from './post';
333
424
 
334
- const t = initTRPC.create({ transformer: superjson });
425
+ const appRouter = router({
426
+ user: userRouter,
427
+ post: postRouter,
428
+ });
335
429
 
336
- const router1 = t.router({ a: t.procedure.query(() => 'a') });
337
- const router2 = t.router({ b: t.procedure.query(() => 'b') });
430
+ appRouter.user
338
431
 
339
- t.mergeRouters(router1, router2);
340
- ```
432
+ appRouter.post
341
433
 
342
- `t.mergeRouters()` throws at runtime if the routers were created with different transformer or errorFormatter configurations.
434
+ export type AppRouter = typeof appRouter;
435
+ ```
343
436
 
344
- Source: packages/server/src/unstable-core-do-not-import/router.ts
437
+ From https://trpc.io/docs/server/merging-routers#merging-with-child-routers
345
438
 
346
- ### [CRITICAL] Importing appRouter value into client code
439
+ ## Dynamically load routers
347
440
 
348
- Wrong:
441
+ You can use the `lazy` function to dynamically load your routers. This can be useful to reduce cold starts of your application. There's no difference in how you use the router after it's been lazy loaded vs. how you use a normal router.
349
442
 
350
- ```ts
351
- // client.ts
352
- import { appRouter } from '../server/router';
443
+ ```ts no-check title="routers/greeting.ts"
444
+ import { router, publicProcedure } from '../trpc';
353
445
 
354
- type AppRouter = typeof appRouter;
446
+ export const greetingRouter = router({
447
+ hello: publicProcedure.query(() => 'world'),
448
+ });
355
449
  ```
356
450
 
357
- Correct:
451
+ ```ts no-check title="routers/user.ts"
452
+ import { router, publicProcedure } from '../trpc';
358
453
 
359
- ```ts
360
- // client.ts
361
- import type { AppRouter } from '../server/router';
454
+ export const userRouter = router({
455
+ list: publicProcedure.query(() => ['John', 'Jane', 'Jim']),
456
+ });
457
+ ```
458
+
459
+ ```ts no-check title="routers/_app.ts"
460
+ import { lazy } from '@trpc/server';
461
+ import { router } from '../trpc';
362
462
 
363
- // server/router.ts
463
+ export const appRouter = router({
464
+ // Option 1: Short-hand when the module has exactly 1 router exported
465
+ greeting: lazy(() => import('./greeting.js')),
466
+ // Option 2: if exporting more than 1 router
467
+ user: lazy(() => import('./user.js').then((m) => m.userRouter)),
468
+ });
364
469
  export type AppRouter = typeof appRouter;
365
470
  ```
366
471
 
367
- Importing the appRouter value bundles the entire server into the client, even if you only use `typeof`.
368
-
369
- Source: www/docs/server/routers.md
472
+ From https://trpc.io/docs/server/merging-routers#lazy-load
370
473
 
371
- ## See Also
474
+ ## References
372
475
 
373
- - `middlewares` -- add auth, logging, context extension to procedures
374
- - `validators` -- add input/output validation with Zod
375
- - `error-handling` -- throw and format typed errors
376
- - `server-side-calls` -- call procedures from server code
377
- - `adapter-standalone` -- mount on Node.js HTTP server
378
- - `adapter-fetch` -- mount on edge runtimes
476
+ - [Define Routers](references/server-routers.md)
477
+ - [Define Procedures](references/server-procedures.md)
478
+ - [Context](references/server-context.md)
479
+ - [Merging Routers](references/server-merging-routers.md)
480
+ - [Metadata](references/server-metadata.md)