@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.
- package/README.md +0 -8
- package/dist/adapters/aws-lambda/index.cjs +1 -1
- package/dist/adapters/aws-lambda/index.d.cts.map +1 -1
- package/dist/adapters/aws-lambda/index.d.mts.map +1 -1
- package/dist/adapters/aws-lambda/index.mjs +1 -1
- package/dist/adapters/aws-lambda/index.mjs.map +1 -1
- package/dist/adapters/express.cjs +1 -1
- package/dist/adapters/express.mjs +1 -1
- package/dist/adapters/express.mjs.map +1 -1
- package/dist/adapters/fastify/index.cjs +3 -3
- package/dist/adapters/fastify/index.mjs +3 -3
- package/dist/adapters/fetch/index.cjs +1 -1
- package/dist/adapters/fetch/index.mjs +1 -1
- package/dist/adapters/next-app-dir.mjs.map +1 -1
- package/dist/adapters/next.cjs +1 -1
- package/dist/adapters/next.mjs +1 -1
- package/dist/adapters/next.mjs.map +1 -1
- package/dist/adapters/node-http/index.cjs +1 -1
- package/dist/adapters/node-http/index.mjs +1 -1
- package/dist/adapters/standalone.cjs +9 -3
- package/dist/adapters/standalone.d.cts +0 -1
- package/dist/adapters/standalone.d.cts.map +1 -1
- package/dist/adapters/standalone.d.mts +0 -1
- package/dist/adapters/standalone.d.mts.map +1 -1
- package/dist/adapters/standalone.mjs +9 -3
- package/dist/adapters/standalone.mjs.map +1 -1
- package/dist/adapters/ws.cjs +1 -1
- package/dist/adapters/ws.mjs +1 -1
- package/dist/asyncGeneratorDelegate-FcEJT04i.mjs.map +1 -1
- package/dist/codes-C9N0z0an.mjs.map +1 -1
- package/dist/getErrorShape-zlj81BiC.mjs.map +1 -1
- package/dist/http.cjs +1 -1
- package/dist/http.mjs +1 -1
- package/dist/initTRPC-RMeQIy9H.mjs.map +1 -1
- package/dist/{node-http-B5jkpWn7.mjs → node-http-ChhZEv1k.mjs} +2 -2
- package/dist/node-http-ChhZEv1k.mjs.map +1 -0
- package/dist/{node-http-BZ0HlzkC.cjs → node-http-X8RiQEuH.cjs} +1 -1
- package/dist/parseTRPCMessage-CJ4DJVBp.mjs.map +1 -1
- package/dist/{resolveResponse-b9D_SrLs.cjs → resolveResponse-CoGjFxK0.cjs} +8 -4
- package/dist/{resolveResponse-DH5L33sC.mjs → resolveResponse-DksrxZ2k.mjs} +9 -5
- package/dist/resolveResponse-DksrxZ2k.mjs.map +1 -0
- package/dist/unstable-core-do-not-import-B8epiErP.d.cts.map +1 -1
- package/dist/unstable-core-do-not-import-Dbo98mkh.d.mts.map +1 -1
- package/dist/unstable-core-do-not-import.cjs +1 -1
- package/dist/unstable-core-do-not-import.mjs +1 -1
- package/dist/unstable-core-do-not-import.mjs.map +1 -1
- package/dist/{ws-83TNWW-W.cjs → ws-7qWW7Uec.cjs} +2 -2
- package/dist/{ws-DJ2SSChC.mjs → ws-BYfo-HED.mjs} +3 -3
- package/dist/ws-BYfo-HED.mjs.map +1 -0
- package/package.json +9 -12
- package/skills/adapter-aws-lambda/SKILL.md +152 -134
- package/skills/adapter-express/SKILL.md +127 -113
- package/skills/adapter-fastify/SKILL.md +228 -136
- package/skills/adapter-fetch/SKILL.md +388 -111
- package/skills/adapter-standalone/SKILL.md +184 -94
- package/skills/auth/SKILL.md +327 -202
- package/skills/auth/references/client-cors.md +29 -0
- package/skills/caching/SKILL.md +58 -148
- package/skills/error-handling/SKILL.md +280 -174
- package/skills/middlewares/SKILL.md +320 -121
- package/skills/non-json-content-types/SKILL.md +149 -168
- package/skills/server-setup/SKILL.md +355 -253
- package/skills/server-setup/references/server-context.md +219 -0
- package/skills/server-setup/references/server-merging-routers.md +141 -0
- package/skills/server-setup/references/server-metadata.md +105 -0
- package/skills/server-setup/references/server-procedures.md +172 -0
- package/skills/server-setup/references/server-routers.md +123 -0
- package/skills/server-side-calls/SKILL.md +247 -152
- package/skills/service-oriented-architecture/SKILL.md +81 -177
- package/skills/subscriptions/SKILL.md +341 -297
- package/skills/subscriptions/references/client-links-httpSubscriptionLink.md +404 -0
- package/skills/subscriptions/references/client-links-wsLink.md +122 -0
- package/skills/subscriptions/references/server-websockets.md +297 -0
- package/skills/trpc-router/SKILL.md +156 -86
- package/skills/validators/SKILL.md +384 -128
- package/src/adapters/aws-lambda/getPlanner.ts +4 -3
- package/src/adapters/aws-lambda/index.ts +2 -1
- package/src/adapters/express.ts +1 -1
- package/src/adapters/next-app-dir/nextAppDirCaller.ts +4 -4
- package/src/adapters/next-app-dir/rethrowNextErrors.ts +1 -1
- package/src/adapters/next.ts +1 -1
- package/src/adapters/node-http/incomingMessageToRequest.ts +1 -1
- package/src/adapters/node-http/nodeHTTPRequestHandler.ts +1 -1
- package/src/adapters/node-http/types.ts +1 -1
- package/src/adapters/node-http/writeResponse.ts +1 -1
- package/src/adapters/standalone.ts +12 -6
- package/src/adapters/ws.ts +5 -5
- package/src/unstable-core-do-not-import/clientish/inferrable.ts +4 -1
- package/src/unstable-core-do-not-import/clientish/serialize.ts +4 -4
- package/src/unstable-core-do-not-import/error/TRPCError.ts +3 -3
- package/src/unstable-core-do-not-import/http/formDataToObject.ts +1 -1
- package/src/unstable-core-do-not-import/http/getHTTPStatusCode.ts +1 -1
- package/src/unstable-core-do-not-import/http/resolveResponse.ts +13 -2
- package/src/unstable-core-do-not-import/procedure.ts +5 -2
- package/src/unstable-core-do-not-import/procedureBuilder.ts +3 -2
- package/src/unstable-core-do-not-import/rootConfig.ts +2 -2
- package/src/unstable-core-do-not-import/router.ts +5 -2
- package/src/unstable-core-do-not-import/rpc/envelopes.ts +3 -2
- package/src/unstable-core-do-not-import/stream/jsonl.ts +2 -1
- package/src/unstable-core-do-not-import/stream/sse.types.ts +1 -1
- package/src/unstable-core-do-not-import/stream/utils/asyncIterable.ts +1 -1
- package/src/unstable-core-do-not-import/stream/utils/createDeferred.ts +1 -1
- package/src/unstable-core-do-not-import/stream/utils/disposable.ts +6 -6
- package/src/unstable-core-do-not-import/stream/utils/mergeAsyncIterables.ts +2 -2
- package/src/unstable-core-do-not-import/stream/utils/withPing.ts +3 -1
- package/src/unstable-core-do-not-import/transformer.ts +4 -1
- package/src/unstable-core-do-not-import/types.ts +3 -2
- package/src/unstable-core-do-not-import/utils.ts +1 -1
- package/src/vendor/standard-schema-v1/spec.ts +2 -2
- package/src/vendor/unpromise/unpromise.ts +1 -1
- package/bin/intent.js +0 -20
- package/dist/node-http-B5jkpWn7.mjs.map +0 -1
- package/dist/resolveResponse-DH5L33sC.mjs.map +0 -1
- 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
|
-
-
|
|
14
|
-
-
|
|
15
|
-
-
|
|
16
|
-
-
|
|
17
|
-
-
|
|
18
|
-
-
|
|
19
|
-
|
|
20
|
-
|
|
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
|
-
|
|
17
|
+
<!-- Generated from www/v11/docs/server/overview.md by www/build/skills.ts. Edit the docs instead. -->
|
|
24
18
|
|
|
25
|
-
|
|
19
|
+
# Backend Usage
|
|
26
20
|
|
|
27
|
-
|
|
28
|
-
|
|
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
|
-
|
|
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
|
-
|
|
44
|
+
From https://trpc.io/docs/server/routers#initialize-trpc
|
|
43
45
|
|
|
44
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
69
|
-
|
|
70
|
-
```
|
|
52
|
+
```ts no-check title="server/_app.ts"
|
|
53
|
+
import { publicProcedure, router } from './trpc';
|
|
71
54
|
|
|
72
|
-
|
|
55
|
+
const appRouter = router({
|
|
56
|
+
greeting: publicProcedure.query(() => 'hello tRPC v11!'),
|
|
57
|
+
});
|
|
73
58
|
|
|
74
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
86
|
-
```
|
|
68
|
+
From https://trpc.io/docs/server/routers#defining-a-router
|
|
87
69
|
|
|
88
|
-
|
|
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
|
-
|
|
72
|
+
When you define an inline sub-router, you can represent your router as a plain object.
|
|
94
73
|
|
|
95
|
-
|
|
96
|
-
export const publicProcedure = t.procedure;
|
|
97
|
-
```
|
|
74
|
+
In the below example, `nested1` and `nested2` are equal:
|
|
98
75
|
|
|
99
|
-
```ts
|
|
100
|
-
|
|
101
|
-
import {
|
|
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
|
|
106
|
-
router
|
|
107
|
-
|
|
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
|
-
|
|
92
|
+
From https://trpc.io/docs/server/routers#inline-sub-router
|
|
113
93
|
|
|
114
|
-
|
|
115
|
-
// server/context.ts
|
|
116
|
-
import type { CreateHTTPContextOptions } from '@trpc/server/adapters/standalone';
|
|
117
|
-
import { db } from './db';
|
|
94
|
+
## Writing procedures
|
|
118
95
|
|
|
119
|
-
|
|
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
|
-
|
|
124
|
-
|
|
125
|
-
|
|
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
|
-
|
|
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
|
|
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
|
-
|
|
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
|
-
|
|
148
|
-
|
|
149
|
-
|
|
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
|
-
|
|
152
|
-
|
|
119
|
+
return {
|
|
120
|
+
message: 'goodbye!',
|
|
121
|
+
};
|
|
122
|
+
}),
|
|
153
123
|
});
|
|
154
124
|
```
|
|
155
125
|
|
|
156
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
136
|
+
```ts no-check
|
|
137
|
+
import { initTRPC, TRPCError } from '@trpc/server';
|
|
138
|
+
import { z } from 'zod';
|
|
184
139
|
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
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
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
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
|
-
|
|
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
|
-
|
|
222
|
+
From https://trpc.io/docs/server/procedures#reusable-base-procedures
|
|
201
223
|
|
|
202
|
-
|
|
224
|
+
## Defining the context type
|
|
203
225
|
|
|
204
|
-
|
|
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
|
-
|
|
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
|
-
|
|
230
|
+
```ts no-check
|
|
213
231
|
import { initTRPC } from '@trpc/server';
|
|
214
|
-
|
|
215
|
-
export const postRouter = t2.router({});
|
|
216
|
-
```
|
|
232
|
+
import type { CreateHTTPContextOptions } from '@trpc/server/adapters/standalone';
|
|
217
233
|
|
|
218
|
-
|
|
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
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
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
|
-
|
|
228
|
-
|
|
246
|
+
t.procedure.use((opts) => {
|
|
247
|
+
opts.ctx;
|
|
248
|
+
|
|
249
|
+
return opts.next();
|
|
250
|
+
});
|
|
229
251
|
```
|
|
230
252
|
|
|
231
|
-
|
|
253
|
+
From https://trpc.io/docs/server/context#defining-the-context-type
|
|
232
254
|
|
|
233
|
-
|
|
255
|
+
## Creating the context
|
|
234
256
|
|
|
235
|
-
|
|
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
|
-
|
|
259
|
+
`createContext()` is called once per request, so all procedures within a single batched request share the same context.
|
|
238
260
|
|
|
239
|
-
```ts
|
|
240
|
-
|
|
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
|
|
243
|
-
|
|
267
|
+
const handler = createHTTPHandler({
|
|
268
|
+
router: appRouter,
|
|
269
|
+
createContext,
|
|
244
270
|
});
|
|
245
271
|
```
|
|
246
272
|
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
import {
|
|
273
|
+
```ts no-check
|
|
274
|
+
// 2. Server-side call
|
|
275
|
+
import { createContext } from './context';
|
|
276
|
+
import { createCaller } from './router';
|
|
251
277
|
|
|
252
|
-
const
|
|
253
|
-
next: publicProcedure.query(() => 'hello'),
|
|
254
|
-
});
|
|
278
|
+
const caller = createCaller(await createContext());
|
|
255
279
|
```
|
|
256
280
|
|
|
257
|
-
|
|
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
|
-
|
|
287
|
+
const helpers = createServerSideHelpers({
|
|
288
|
+
router: appRouter,
|
|
289
|
+
ctx: await createContext(),
|
|
290
|
+
});
|
|
291
|
+
```
|
|
260
292
|
|
|
261
|
-
|
|
293
|
+
From https://trpc.io/docs/server/context#creating-the-context
|
|
262
294
|
|
|
263
|
-
|
|
295
|
+
## Inner and outer context
|
|
264
296
|
|
|
265
|
-
|
|
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
|
-
|
|
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
|
-
|
|
273
|
-
|
|
274
|
-
|
|
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
|
-
|
|
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
|
-
###
|
|
309
|
+
### Example for inner & outer context
|
|
282
310
|
|
|
283
|
-
|
|
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
|
-
|
|
286
|
-
|
|
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
|
-
|
|
289
|
-
|
|
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
|
-
|
|
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
|
-
|
|
296
|
-
import type { CreateExpressContextOptions } from '@trpc/server/adapters/express';
|
|
348
|
+
const contextInner = await createContextInner({ session });
|
|
297
349
|
|
|
298
|
-
|
|
299
|
-
|
|
350
|
+
return {
|
|
351
|
+
...contextInner,
|
|
352
|
+
req: opts.req,
|
|
353
|
+
res: opts.res,
|
|
354
|
+
};
|
|
300
355
|
}
|
|
301
356
|
|
|
302
|
-
export
|
|
303
|
-
return createContextInner({ user: getUserFromReq(req) });
|
|
304
|
-
}
|
|
305
|
-
```
|
|
357
|
+
export type Context = Awaited<ReturnType<typeof createContextInner>>;
|
|
306
358
|
|
|
307
|
-
|
|
359
|
+
// The usage in your router is the same as the example above.
|
|
360
|
+
```
|
|
308
361
|
|
|
309
|
-
|
|
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
|
-
|
|
381
|
+
From https://trpc.io/docs/server/context#inner-and-outer-context
|
|
312
382
|
|
|
313
|
-
|
|
383
|
+
## Merging with child routers
|
|
314
384
|
|
|
315
|
-
```ts
|
|
316
|
-
import {
|
|
317
|
-
import
|
|
385
|
+
```ts no-check title="routers/user.ts"
|
|
386
|
+
import { router, publicProcedure } from '../trpc';
|
|
387
|
+
import { z } from 'zod';
|
|
318
388
|
|
|
319
|
-
const
|
|
320
|
-
|
|
389
|
+
export const userRouter = router({
|
|
390
|
+
list: publicProcedure.query(() => {
|
|
391
|
+
// [..]
|
|
392
|
+
return [];
|
|
393
|
+
}),
|
|
394
|
+
});
|
|
395
|
+
```
|
|
321
396
|
|
|
322
|
-
|
|
323
|
-
|
|
397
|
+
```ts no-check title="routers/post.ts"
|
|
398
|
+
import { router, publicProcedure } from '../trpc';
|
|
399
|
+
import { z } from 'zod';
|
|
324
400
|
|
|
325
|
-
|
|
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
|
-
|
|
419
|
+
```ts no-check title="routers/_app.ts"
|
|
420
|
+
import { router } from '../trpc';
|
|
329
421
|
|
|
330
|
-
|
|
331
|
-
import {
|
|
332
|
-
import superjson from 'superjson';
|
|
422
|
+
import { userRouter } from './user';
|
|
423
|
+
import { postRouter } from './post';
|
|
333
424
|
|
|
334
|
-
const
|
|
425
|
+
const appRouter = router({
|
|
426
|
+
user: userRouter,
|
|
427
|
+
post: postRouter,
|
|
428
|
+
});
|
|
335
429
|
|
|
336
|
-
|
|
337
|
-
const router2 = t.router({ b: t.procedure.query(() => 'b') });
|
|
430
|
+
appRouter.user
|
|
338
431
|
|
|
339
|
-
|
|
340
|
-
```
|
|
432
|
+
appRouter.post
|
|
341
433
|
|
|
342
|
-
|
|
434
|
+
export type AppRouter = typeof appRouter;
|
|
435
|
+
```
|
|
343
436
|
|
|
344
|
-
|
|
437
|
+
From https://trpc.io/docs/server/merging-routers#merging-with-child-routers
|
|
345
438
|
|
|
346
|
-
|
|
439
|
+
## Dynamically load routers
|
|
347
440
|
|
|
348
|
-
|
|
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
|
-
|
|
352
|
-
import { appRouter } from '../server/router';
|
|
443
|
+
```ts no-check title="routers/greeting.ts"
|
|
444
|
+
import { router, publicProcedure } from '../trpc';
|
|
353
445
|
|
|
354
|
-
|
|
446
|
+
export const greetingRouter = router({
|
|
447
|
+
hello: publicProcedure.query(() => 'world'),
|
|
448
|
+
});
|
|
355
449
|
```
|
|
356
450
|
|
|
357
|
-
|
|
451
|
+
```ts no-check title="routers/user.ts"
|
|
452
|
+
import { router, publicProcedure } from '../trpc';
|
|
358
453
|
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
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
|
-
|
|
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
|
-
|
|
368
|
-
|
|
369
|
-
Source: www/docs/server/routers.md
|
|
472
|
+
From https://trpc.io/docs/server/merging-routers#lazy-load
|
|
370
473
|
|
|
371
|
-
##
|
|
474
|
+
## References
|
|
372
475
|
|
|
373
|
-
-
|
|
374
|
-
-
|
|
375
|
-
-
|
|
376
|
-
-
|
|
377
|
-
-
|
|
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)
|