@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
@@ -0,0 +1,219 @@
1
+ # Context
2
+
3
+ From https://trpc.io/docs/server/context
4
+
5
+ Your context holds data that all of your tRPC procedures will have access to, and is a great place to put things like authentication information.
6
+
7
+ Setting up the context is done in 2 steps, defining the type during initialization and then creating the runtime context for each request.
8
+
9
+ ## Defining the context type
10
+
11
+ 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.
12
+
13
+ This will make sure your context is properly typed in your procedures and middlewares.
14
+
15
+ ```ts no-check
16
+ import { initTRPC } from '@trpc/server';
17
+ import type { CreateHTTPContextOptions } from '@trpc/server/adapters/standalone';
18
+
19
+ export const createContext = async (opts: CreateHTTPContextOptions) => {
20
+ // Example: extract a session token from the request headers
21
+ const token = opts.req.headers['authorization'];
22
+
23
+ return {
24
+ token,
25
+ };
26
+ };
27
+
28
+ export type Context = Awaited<ReturnType<typeof createContext>>;
29
+ const t = initTRPC.context<Context>().create();
30
+
31
+ t.procedure.use((opts) => {
32
+ opts.ctx;
33
+
34
+ return opts.next();
35
+ });
36
+ ```
37
+
38
+ ## Creating the context
39
+
40
+ 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).
41
+
42
+ `createContext()` is called once per request, so all procedures within a single batched request share the same context.
43
+
44
+ ```ts no-check
45
+ // 1. HTTP request
46
+ import { createHTTPHandler } from '@trpc/server/adapters/standalone';
47
+ import { createContext } from './context';
48
+ import { appRouter } from './router';
49
+
50
+ const handler = createHTTPHandler({
51
+ router: appRouter,
52
+ createContext,
53
+ });
54
+ ```
55
+
56
+ ```ts no-check
57
+ // 2. Server-side call
58
+ import { createContext } from './context';
59
+ import { createCaller } from './router';
60
+
61
+ const caller = createCaller(await createContext());
62
+ ```
63
+
64
+ ```ts no-check
65
+ // 3. Server-side helpers (Next.js-specific, see /docs/client/nextjs/pages-router/server-side-helpers)
66
+ import { createServerSideHelpers } from '@trpc/react-query/server';
67
+ import { createContext } from './context';
68
+ import { appRouter } from './router';
69
+
70
+ const helpers = createServerSideHelpers({
71
+ router: appRouter,
72
+ ctx: await createContext(),
73
+ });
74
+ ```
75
+
76
+ ## Example code
77
+
78
+
79
+ ```ts no-check
80
+ // -------------------------------------------------
81
+ // -------------------------------------------------
82
+ import type { CreateHTTPContextOptions } from '@trpc/server/adapters/standalone';
83
+
84
+ /**
85
+ * Creates context for an incoming request
86
+ * @see https://trpc.io/docs/v11/context
87
+ */
88
+ export async function createContext(opts: CreateHTTPContextOptions) {
89
+ const token = opts.req.headers['authorization'];
90
+
91
+ // In a real app, you would verify the token and look up the user
92
+ const user = token ? { email: 'user@example.com' } : null;
93
+
94
+ return {
95
+ user,
96
+ };
97
+ }
98
+
99
+ export type Context = Awaited<ReturnType<typeof createContext>>;
100
+
101
+ // -------------------------------------------------
102
+ // -------------------------------------------------
103
+ import { initTRPC, TRPCError } from '@trpc/server';
104
+ import { Context } from './context';
105
+
106
+ const t = initTRPC.context<Context>().create();
107
+
108
+
109
+ export const router = t.router;
110
+
111
+ /**
112
+ * Unprotected procedure
113
+ */
114
+ export const publicProcedure = t.procedure;
115
+
116
+ /**
117
+ * Protected procedure
118
+ */
119
+ export const protectedProcedure = t.procedure.use(function isAuthed(opts) {
120
+ if (!opts.ctx.user?.email) {
121
+ throw new TRPCError({
122
+ code: 'UNAUTHORIZED',
123
+ });
124
+ }
125
+ return opts.next({
126
+ ctx: {
127
+ // Infers the `user` as non-nullable
128
+ user: opts.ctx.user,
129
+ },
130
+ });
131
+ });
132
+ ```
133
+
134
+
135
+ ## Inner and outer context
136
+
137
+ In some scenarios it could make sense to split up your context into "inner" and "outer" functions.
138
+
139
+ **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.
140
+
141
+ > [!NOTE] Tradeoff for large clients in `createContextInner`
142
+ > 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.
143
+ >
144
+ > If that overhead becomes noticeable, an alternative is to keep context smaller and import the client directly at call sites where needed.
145
+
146
+
147
+ **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.
148
+
149
+ ### Example for inner & outer context
150
+
151
+ ```ts no-check
152
+ import type { CreateHTTPContextOptions } from '@trpc/server/adapters/standalone';
153
+ import { getSessionFromCookie, type Session } from './auth';
154
+ import { db } from './db';
155
+
156
+ /**
157
+ * Defines your inner context shape.
158
+ * Add fields here that the inner context brings.
159
+ */
160
+ interface CreateInnerContextOptions {
161
+ session: Session | null;
162
+ }
163
+
164
+ /**
165
+ * Inner context. Will always be available in your procedures, in contrast to the outer context.
166
+ *
167
+ * Also useful for:
168
+ * - testing, so you don't have to mock `req`/`res`
169
+ * - server-side calls where we don't have `req`/`res`
170
+ *
171
+ * @see https://trpc.io/docs/v11/context#inner-and-outer-context
172
+ */
173
+ export async function createContextInner(opts?: CreateInnerContextOptions) {
174
+ return {
175
+ db,
176
+ session: opts?.session,
177
+ };
178
+ }
179
+
180
+ /**
181
+ * Outer context. Used in the routers and will e.g. bring `req` & `res` to the context as "not `undefined`".
182
+ *
183
+ * @see https://trpc.io/docs/v11/context#inner-and-outer-context
184
+ */
185
+ export async function createContext(opts: CreateHTTPContextOptions) {
186
+ const session = getSessionFromCookie(opts.req);
187
+
188
+ const contextInner = await createContextInner({ session });
189
+
190
+ return {
191
+ ...contextInner,
192
+ req: opts.req,
193
+ res: opts.res,
194
+ };
195
+ }
196
+
197
+ export type Context = Awaited<ReturnType<typeof createContextInner>>;
198
+
199
+ // The usage in your router is the same as the example above.
200
+ ```
201
+
202
+ It is important to infer your `Context` from the **inner** context, as only what is defined there is really always available in your procedures.
203
+
204
+ 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:
205
+
206
+ ```ts no-check
207
+ export const apiProcedure = publicProcedure.use((opts) => {
208
+ if (!opts.ctx.req || !opts.ctx.res) {
209
+ throw new Error('You are missing `req` or `res` in your call.');
210
+ }
211
+ return opts.next({
212
+ ctx: {
213
+ // We overwrite the context with the truthy `req` & `res`, which will also overwrite the types used in your procedure.
214
+ req: opts.ctx.req,
215
+ res: opts.ctx.res,
216
+ },
217
+ });
218
+ });
219
+ ```
@@ -0,0 +1,141 @@
1
+ # Merging Routers
2
+
3
+ From https://trpc.io/docs/server/merging-routers
4
+
5
+ Writing all API-code in the same file can become unwieldy. It's easy to merge routers together in order to break them up.
6
+
7
+ ## Merging with child routers
8
+
9
+ ```ts no-check title="routers/user.ts"
10
+ import { router, publicProcedure } from '../trpc';
11
+ import { z } from 'zod';
12
+
13
+ export const userRouter = router({
14
+ list: publicProcedure.query(() => {
15
+ // [..]
16
+ return [];
17
+ }),
18
+ });
19
+ ```
20
+
21
+ ```ts no-check title="routers/post.ts"
22
+ import { router, publicProcedure } from '../trpc';
23
+ import { z } from 'zod';
24
+
25
+ export const postRouter = router({
26
+ create: publicProcedure
27
+ .input(
28
+ z.object({
29
+ title: z.string(),
30
+ }),
31
+ )
32
+ .mutation((opts) => {
33
+ const { input } = opts;
34
+ // [...]
35
+ }),
36
+ list: publicProcedure.query(() => {
37
+ // ...
38
+ return [];
39
+ }),
40
+ });
41
+ ```
42
+
43
+ ```ts no-check title="routers/_app.ts"
44
+ import { router } from '../trpc';
45
+
46
+ import { userRouter } from './user';
47
+ import { postRouter } from './post';
48
+
49
+ const appRouter = router({
50
+ user: userRouter,
51
+ post: postRouter,
52
+ });
53
+
54
+ appRouter.user
55
+
56
+ appRouter.post
57
+
58
+ export type AppRouter = typeof appRouter;
59
+ ```
60
+
61
+ ## Merging with `t.mergeRouters`
62
+
63
+ If you prefer having all procedures flat in one single namespace, you can instead use `t.mergeRouters`. It throws if two routers define the same procedure path, so keep the names unique. Merge routers from the same [`t`](https://trpc.io/docs/server/routers#initialize-trpc): it also throws if they come from separate tRPC instances that each set a transformer or error formatter.
64
+
65
+ ```ts no-check title="routers/user.ts"
66
+ import { router, publicProcedure } from '../trpc';
67
+ import { z } from 'zod';
68
+
69
+ export const userRouter = router({
70
+ userList: publicProcedure.query(() => {
71
+ // [..]
72
+ return [];
73
+ }),
74
+ });
75
+ ```
76
+
77
+ ```ts no-check title="routers/post.ts"
78
+ import { router, publicProcedure } from '../trpc';
79
+ import { z } from 'zod';
80
+
81
+ export const postRouter = router({
82
+ postCreate: publicProcedure
83
+ .input(
84
+ z.object({
85
+ title: z.string(),
86
+ }),
87
+ )
88
+ .mutation((opts) => {
89
+ const { input } = opts;
90
+ // [...]
91
+ }),
92
+ postList: publicProcedure.query(() => {
93
+ // ...
94
+ return [];
95
+ }),
96
+ });
97
+ ```
98
+
99
+ ```ts no-check title="routers/_app.ts"
100
+ import { mergeRouters } from '../trpc';
101
+
102
+ import { userRouter } from './user';
103
+ import { postRouter } from './post';
104
+
105
+ const appRouter = mergeRouters(userRouter, postRouter);
106
+
107
+ export type AppRouter = typeof appRouter;
108
+ ```
109
+
110
+ ## Dynamically load routers
111
+
112
+ 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.
113
+
114
+ ```ts no-check title="routers/greeting.ts"
115
+ import { router, publicProcedure } from '../trpc';
116
+
117
+ export const greetingRouter = router({
118
+ hello: publicProcedure.query(() => 'world'),
119
+ });
120
+ ```
121
+
122
+ ```ts no-check title="routers/user.ts"
123
+ import { router, publicProcedure } from '../trpc';
124
+
125
+ export const userRouter = router({
126
+ list: publicProcedure.query(() => ['John', 'Jane', 'Jim']),
127
+ });
128
+ ```
129
+
130
+ ```ts no-check title="routers/_app.ts"
131
+ import { lazy } from '@trpc/server';
132
+ import { router } from '../trpc';
133
+
134
+ export const appRouter = router({
135
+ // Option 1: Short-hand when the module has exactly 1 router exported
136
+ greeting: lazy(() => import('./greeting.js')),
137
+ // Option 2: if exporting more than 1 router
138
+ user: lazy(() => import('./user.js').then((m) => m.userRouter)),
139
+ });
140
+ export type AppRouter = typeof appRouter;
141
+ ```
@@ -0,0 +1,105 @@
1
+ # Metadata
2
+
3
+ From https://trpc.io/docs/server/metadata
4
+
5
+ Procedure metadata allows you to add an optional procedure specific `meta` property which will be available in all [middleware](https://trpc.io/docs/server/middlewares) function parameters.
6
+
7
+ > [!TIP]
8
+ > Use metadata together with [`trpc-openapi`](https://github.com/jlalmes/trpc-openapi) if you want to expose REST-compatible endpoints for your application.
9
+
10
+
11
+ ## Create router with typed metadata
12
+
13
+ ```tsx no-check
14
+ import { initTRPC } from '@trpc/server';
15
+
16
+ type Context = { user: { name: string } | null };
17
+
18
+ interface Meta {
19
+ authRequired: boolean;
20
+ }
21
+
22
+ export const t = initTRPC.context<Context>().meta<Meta>().create();
23
+
24
+ export const appRouter = t.router({
25
+ // [...]
26
+ });
27
+ ```
28
+
29
+ ## Example with per route authentication settings
30
+
31
+ ```tsx no-check title="server.ts"
32
+ import { initTRPC, TRPCError } from '@trpc/server';
33
+
34
+ type Context = { user: { name: string } | null };
35
+
36
+ interface Meta {
37
+ authRequired: boolean;
38
+ }
39
+
40
+ export const t = initTRPC.context<Context>().meta<Meta>().create();
41
+
42
+ export const authedProcedure = t.procedure.use(async (opts) => {
43
+ const { meta, next, ctx } = opts;
44
+ // only check authorization if enabled
45
+ if (meta?.authRequired && !ctx.user) {
46
+ throw new TRPCError({ code: 'UNAUTHORIZED' });
47
+ }
48
+ return next();
49
+ });
50
+
51
+ export const appRouter = t.router({
52
+ hello: authedProcedure.meta({ authRequired: false }).query(() => {
53
+ return {
54
+ greeting: 'hello world',
55
+ };
56
+ }),
57
+ protectedHello: authedProcedure.meta({ authRequired: true }).query(() => {
58
+ return {
59
+ greeting: 'hello-world',
60
+ };
61
+ }),
62
+ });
63
+ ```
64
+
65
+ ## Default meta, chaining, and shallow merging
66
+
67
+ You can set default values for your meta type, and if you chain meta on top of a base procedure it will be shallow merged.
68
+
69
+ ```tsx no-check
70
+ import { initTRPC } from '@trpc/server';
71
+
72
+ type Context = { user: { name: string } | null };
73
+
74
+ interface Meta {
75
+ authRequired?: boolean;
76
+ role?: 'user' | 'admin'
77
+ }
78
+
79
+ export const t = initTRPC
80
+ .context<Context>()
81
+ .meta<Meta>()
82
+ .create({
83
+ // Set a default value
84
+ defaultMeta: { authRequired: false }
85
+ });
86
+
87
+ const authMiddleware = t.middleware((opts) => opts.next());
88
+
89
+ const publicProcedure = t.procedure
90
+ // ^ Default Meta: { authRequired: false }
91
+
92
+ const authProcedure = publicProcedure
93
+ .use(authMiddleware)
94
+ .meta({
95
+ authRequired: true,
96
+ role: 'user'
97
+ });
98
+ // ^ Meta: { authRequired: true, role: 'user' }
99
+
100
+ const adminProcedure = authProcedure
101
+ .meta({
102
+ role: 'admin'
103
+ });
104
+ // ^ Meta: { authRequired: true, role: 'admin' }
105
+ ```
@@ -0,0 +1,172 @@
1
+ # Define Procedures
2
+
3
+ From https://trpc.io/docs/server/procedures
4
+
5
+ A procedure is a function which is exposed to the client, it can be one of:
6
+
7
+ - a `Query` - used to fetch data, generally does not change any data
8
+ - a `Mutation` - used to send data, often for create/update/delete purposes
9
+ - a `Subscription` - you might not need this, and we have [dedicated documentation](https://trpc.io/docs/server/subscriptions)
10
+
11
+ Procedures in tRPC are very flexible primitives to create backend functions. They use an immutable builder pattern, which means you can [create reusable base procedures](https://trpc.io/docs/server/procedures#reusable-base-procedures) that share functionality among multiple procedures.
12
+
13
+ ## Writing procedures
14
+
15
+ The `t` object you create during tRPC setup returns an initial `t.procedure` which all other procedures are built on:
16
+
17
+ ```ts no-check
18
+ import { initTRPC } from '@trpc/server';
19
+ import { z } from 'zod';
20
+
21
+ const t = initTRPC.context<{ signGuestBook: () => Promise<void> }>().create();
22
+
23
+ export const router = t.router;
24
+ export const publicProcedure = t.procedure;
25
+
26
+ const appRouter = router({
27
+ // Queries are the best place to fetch data
28
+ hello: publicProcedure.query(() => {
29
+ return {
30
+ message: 'hello world',
31
+ };
32
+ }),
33
+
34
+ // Mutations are the best place to do things like updating a database
35
+ goodbye: publicProcedure.mutation(async (opts) => {
36
+ await opts.ctx.signGuestBook();
37
+
38
+ return {
39
+ message: 'goodbye!',
40
+ };
41
+ }),
42
+ });
43
+ ```
44
+
45
+ ## Reusable "Base Procedures"
46
+
47
+ 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.
48
+
49
+ 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.
50
+
51
+ > 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.
52
+
53
+ ```ts no-check
54
+ import { initTRPC, TRPCError } from '@trpc/server';
55
+ import { z } from 'zod';
56
+
57
+ type Organization = {
58
+ id: string;
59
+ name: string;
60
+ };
61
+ type Membership = {
62
+ role: 'ADMIN' | 'MEMBER';
63
+ Organization: Organization;
64
+ };
65
+ type User = {
66
+ id: string;
67
+ memberships: Membership[];
68
+ };
69
+ type Context = {
70
+ /**
71
+ * User is nullable
72
+ */
73
+ user: User | null;
74
+ };
75
+
76
+ const t = initTRPC.context<Context>().create();
77
+
78
+ export const publicProcedure = t.procedure;
79
+
80
+ // procedure that asserts that the user is logged in
81
+ export const authedProcedure = t.procedure.use(async function isAuthed(opts) {
82
+ const { ctx } = opts;
83
+ // `ctx.user` is nullable
84
+ if (!ctx.user) {
85
+ throw new TRPCError({ code: 'UNAUTHORIZED' });
86
+ }
87
+
88
+ return opts.next({
89
+ ctx: {
90
+ // ✅ user value is known to be non-null now
91
+ user: ctx.user,
92
+ },
93
+ });
94
+ });
95
+
96
+ // procedure that asserts a user is a member of a specific organization
97
+ export const organizationProcedure = authedProcedure
98
+ .input(z.object({ organizationId: z.string() }))
99
+ .use(function isMemberOfOrganization(opts) {
100
+ const membership = opts.ctx.user.memberships.find(
101
+ (m) => m.Organization.id === opts.input.organizationId,
102
+ );
103
+ if (!membership) {
104
+ throw new TRPCError({
105
+ code: 'FORBIDDEN',
106
+ });
107
+ }
108
+ return opts.next({
109
+ ctx: {
110
+ Organization: membership.Organization,
111
+ },
112
+ });
113
+ });
114
+
115
+ export const appRouter = t.router({
116
+ whoami: authedProcedure.query(async (opts) => {
117
+ // user is non-nullable here
118
+ const { ctx } = opts;
119
+ return ctx.user;
120
+ }),
121
+ addMember: organizationProcedure
122
+ .input(
123
+ z.object({
124
+ email: z.string().email(),
125
+ }),
126
+ )
127
+ .mutation((opts) => {
128
+ // ctx contains the non-nullable user & the organization being queried
129
+ const { ctx } = opts;
130
+
131
+ // input includes the validated email of the user being invited & the validated organizationId
132
+ const { input } = opts;
133
+
134
+ return '...';
135
+ }),
136
+ });
137
+ ```
138
+
139
+ ## Inferring the options type of a "Base Procedure"
140
+
141
+ In addition to being able to [infer the input and output types](https://trpc.io/docs/client/vanilla/infer-types#inferring-input--output-types) of a procedure, you can also infer the options type of a specific procedure builder (or base procedure) using `inferProcedureBuilderResolverOptions`.
142
+
143
+ This type helper is useful for declaring a type to a function's parameters. Like for example, separating the procedure's handler (main execution code) from its definition at the router, or for creating a helper function that works with multiple procedures.
144
+
145
+ ```ts no-check
146
+ async function getMembersOfOrganization(
147
+ opts: inferProcedureBuilderResolverOptions<typeof organizationProcedure>,
148
+ ) {
149
+ // input and ctx are now correctly typed!
150
+ const { ctx, input } = opts;
151
+
152
+ return await prisma.user.findMany({
153
+ where: {
154
+ membership: {
155
+ organizationId: ctx.Organization.id,
156
+ },
157
+ },
158
+ });
159
+ }
160
+ export const appRouter = t.router({
161
+ listMembers: organizationProcedure.query(async (opts) => {
162
+ // use helper function!
163
+ const members = await getMembersOfOrganization(opts);
164
+
165
+ return members;
166
+ }),
167
+ });
168
+ ```
169
+
170
+ ## Subscriptions
171
+
172
+ For information on subscriptions, see [our subscriptions guide](https://trpc.io/docs/server/subscriptions).