@trpc/server 11.22.2-canary.19.b9321728b → 11.22.2-canary.42.d3cd94bdd
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/package.json +9 -3
- package/skills/adapter-aws-lambda/SKILL.md +221 -0
- package/skills/adapter-express/SKILL.md +190 -0
- package/skills/adapter-fastify/SKILL.md +313 -0
- package/skills/adapter-fetch/SKILL.md +476 -0
- package/skills/adapter-standalone/SKILL.md +288 -0
- package/skills/auth/SKILL.md +467 -0
- package/skills/auth/references/client-cors.md +29 -0
- package/skills/caching/SKILL.md +115 -0
- package/skills/error-handling/SKILL.md +359 -0
- package/skills/middlewares/SKILL.md +441 -0
- package/skills/non-json-content-types/SKILL.md +246 -0
- package/skills/server-setup/SKILL.md +480 -0
- 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 +344 -0
- package/skills/service-oriented-architecture/SKILL.md +151 -0
- package/skills/subscriptions/SKILL.md +450 -0
- 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 +221 -0
- package/skills/validators/SKILL.md +484 -0
package/package.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"name": "@trpc/server",
|
|
3
3
|
"type": "module",
|
|
4
4
|
"sideEffects": false,
|
|
5
|
-
"version": "11.22.2-canary.
|
|
5
|
+
"version": "11.22.2-canary.42.d3cd94bdd",
|
|
6
6
|
"description": "The tRPC server library",
|
|
7
7
|
"author": "KATT",
|
|
8
8
|
"license": "MIT",
|
|
@@ -17,6 +17,7 @@
|
|
|
17
17
|
},
|
|
18
18
|
"scripts": {
|
|
19
19
|
"build": "tsdown",
|
|
20
|
+
"prepack": "node ../../www/build/skills.ts --package .",
|
|
20
21
|
"dev": "tsdown --watch",
|
|
21
22
|
"benchmark": "tsc --project tsconfig.benchmark.json",
|
|
22
23
|
"lint": "oxlint src",
|
|
@@ -187,7 +188,8 @@
|
|
|
187
188
|
"shared",
|
|
188
189
|
"unstable-core-do-not-import",
|
|
189
190
|
"!**/*.test.*",
|
|
190
|
-
"!**/__tests__"
|
|
191
|
+
"!**/__tests__",
|
|
192
|
+
"skills"
|
|
191
193
|
],
|
|
192
194
|
"publishConfig": {
|
|
193
195
|
"access": "public"
|
|
@@ -195,6 +197,7 @@
|
|
|
195
197
|
"devDependencies": {
|
|
196
198
|
"@fastify/websocket": "^11.3.0",
|
|
197
199
|
"@oxc-project/runtime": "0.152.0",
|
|
200
|
+
"@tanstack/intent": "0.5.6",
|
|
198
201
|
"@tanstack/react-query": "^5.105.0",
|
|
199
202
|
"@types/aws-lambda": "^8.10.149",
|
|
200
203
|
"@types/express": "^5.0.0",
|
|
@@ -251,5 +254,8 @@
|
|
|
251
254
|
"optional": true
|
|
252
255
|
}
|
|
253
256
|
},
|
|
254
|
-
"
|
|
257
|
+
"keywords": [
|
|
258
|
+
"tanstack-intent"
|
|
259
|
+
],
|
|
260
|
+
"gitHead": "d3cd94bddefd974b0e1f9ae8298f9764c44bf410"
|
|
255
261
|
}
|
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: adapter-aws-lambda
|
|
3
|
+
description: Deploy tRPC on AWS Lambda with awsLambdaRequestHandler() from @trpc/server/adapters/aws-lambda for API Gateway v1 (REST, APIGatewayProxyEvent) and v2 (HTTP, APIGatewayProxyEventV2), and Lambda Function URLs. Enable response streaming with awsLambdaStreamingRequestHandler() wrapped in awslambda.streamifyResponse(). CreateAWSLambdaContextOptions provides event and context for context creation. Use one {proxy+} resource for httpBatchLink, or httpLink for a resource per procedure.
|
|
4
|
+
requires:
|
|
5
|
+
- server-setup
|
|
6
|
+
sources:
|
|
7
|
+
- www/v11/docs/server/adapters/aws-lambda.md
|
|
8
|
+
- www/v11/docs/server/adapters.md
|
|
9
|
+
metadata:
|
|
10
|
+
type: core
|
|
11
|
+
library: trpc
|
|
12
|
+
library_version: 11.22.2-canary.42.d3cd94bdd
|
|
13
|
+
---
|
|
14
|
+
|
|
15
|
+
<!-- Generated from www/v11/docs/server/adapters/aws-lambda.md by www/build/skills.ts. Edit the docs instead. -->
|
|
16
|
+
|
|
17
|
+
# AWS Lambda + API Gateway Adapter
|
|
18
|
+
|
|
19
|
+
From https://trpc.io/docs/server/adapters/aws-lambda
|
|
20
|
+
|
|
21
|
+
## AWS Lambda adapter
|
|
22
|
+
|
|
23
|
+
The AWS Lambda adapter is supported for API Gateway [REST API(v1)](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-rest-api.html) and [HTTP API(v2)](https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api.html), and [Lambda Function URL](https://docs.aws.amazon.com/lambda/latest/dg/urls-configuration.html) use cases.
|
|
24
|
+
|
|
25
|
+
> `httpBatchLink` requires the router to work on a single API Gateway Resource (as shown in the [example](https://github.com/trpc/trpc/tree/main/examples/lambda-api-gateway)).
|
|
26
|
+
> If you'd like to have a Resource per procedure, you can use the `httpLink` instead ([more info](https://github.com/trpc/trpc/issues/5738#issuecomment-2130001522)).
|
|
27
|
+
|
|
28
|
+
## Example apps
|
|
29
|
+
|
|
30
|
+
<table>
|
|
31
|
+
<thead>
|
|
32
|
+
<tr>
|
|
33
|
+
<th>Description</th>
|
|
34
|
+
<th>Links</th>
|
|
35
|
+
</tr>
|
|
36
|
+
</thead>
|
|
37
|
+
<tbody>
|
|
38
|
+
<tr>
|
|
39
|
+
<td>API Gateway with NodeJS client.</td>
|
|
40
|
+
<td>
|
|
41
|
+
<ul>
|
|
42
|
+
<li><a href="https://github.com/trpc/trpc/tree/main/examples/lambda-api-gateway">Source</a></li>
|
|
43
|
+
</ul>
|
|
44
|
+
</td>
|
|
45
|
+
</tr>
|
|
46
|
+
<tr>
|
|
47
|
+
<td>API Gateway REST API with response streaming.</td>
|
|
48
|
+
<td>
|
|
49
|
+
<ul>
|
|
50
|
+
<li><a href="https://github.com/trpc/trpc/tree/main/examples/lambda-api-gateway-streaming">Source</a></li>
|
|
51
|
+
</ul>
|
|
52
|
+
</td>
|
|
53
|
+
</tr>
|
|
54
|
+
</tbody>
|
|
55
|
+
</table>
|
|
56
|
+
|
|
57
|
+
## How to add tRPC
|
|
58
|
+
|
|
59
|
+
### 1. Install deps
|
|
60
|
+
|
|
61
|
+
```bash
|
|
62
|
+
yarn add @trpc/server
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
### 2. Create a tRPC router
|
|
66
|
+
|
|
67
|
+
Implement your tRPC router. A sample router is given below:
|
|
68
|
+
|
|
69
|
+
```ts no-check title="server.ts"
|
|
70
|
+
import { initTRPC } from '@trpc/server';
|
|
71
|
+
import { z } from 'zod';
|
|
72
|
+
|
|
73
|
+
export const t = initTRPC.create();
|
|
74
|
+
|
|
75
|
+
const appRouter = t.router({
|
|
76
|
+
getUser: t.procedure.input(z.string()).query((opts) => {
|
|
77
|
+
opts.input; // string
|
|
78
|
+
return { id: opts.input, name: 'Bilbo' };
|
|
79
|
+
}),
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
// export type definition of API
|
|
83
|
+
export type AppRouter = typeof appRouter;
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
### 3. Use the Amazon API Gateway adapter
|
|
87
|
+
|
|
88
|
+
tRPC includes an adapter for API Gateway out of the box. This adapter lets you run your routes through the API Gateway handler.
|
|
89
|
+
|
|
90
|
+
```ts no-check title="server.ts"
|
|
91
|
+
import type { APIGatewayProxyEventV2 } from 'aws-lambda';
|
|
92
|
+
import type { CreateAWSLambdaContextOptions } from '@trpc/server/adapters/aws-lambda';
|
|
93
|
+
import { awsLambdaRequestHandler } from '@trpc/server/adapters/aws-lambda';
|
|
94
|
+
import { appRouter } from './router';
|
|
95
|
+
|
|
96
|
+
// created for each request
|
|
97
|
+
const createContext = ({
|
|
98
|
+
event,
|
|
99
|
+
context,
|
|
100
|
+
}: CreateAWSLambdaContextOptions<APIGatewayProxyEventV2>) => ({}); // no context
|
|
101
|
+
type Context = Awaited<ReturnType<typeof createContext>>;
|
|
102
|
+
|
|
103
|
+
export const handler = awsLambdaRequestHandler({
|
|
104
|
+
router: appRouter,
|
|
105
|
+
createContext,
|
|
106
|
+
})
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
`awsLambdaRequestHandler` accepts the [options every adapter takes](https://trpc.io/docs/server/adapters#common-options), like `onError` and `maxBatchSize`.
|
|
110
|
+
|
|
111
|
+
Build & deploy your code, now use your API Gateway URL to call your function.
|
|
112
|
+
|
|
113
|
+
| Endpoint | HTTP URI |
|
|
114
|
+
| --------- | ------------------------------------------------------------------------------------------------------------ |
|
|
115
|
+
| `getUser` | `GET https://<execution-api-link>/getUser?input=INPUT` <br/><br/>where `INPUT` is a URI-encoded JSON string. |
|
|
116
|
+
|
|
117
|
+
#### A word about payload format version
|
|
118
|
+
|
|
119
|
+
API Gateway has two different event data formats when it invokes a Lambda. For REST APIs they should be version "1.0"(`APIGatewayProxyEvent`), but you can choose which for HTTP APIs by stating either version "1.0" or "2.0".
|
|
120
|
+
|
|
121
|
+
- Version 1.0: `APIGatewayProxyEvent`
|
|
122
|
+
- Version 2.0: `APIGatewayProxyEventV2`
|
|
123
|
+
|
|
124
|
+
To infer what version you might have, supply the context as following:
|
|
125
|
+
|
|
126
|
+
```ts no-check
|
|
127
|
+
function createContext({
|
|
128
|
+
event,
|
|
129
|
+
context,
|
|
130
|
+
}: CreateAWSLambdaContextOptions<APIGatewayProxyEvent>) {
|
|
131
|
+
// ...
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
// CreateAWSLambdaContextOptions<APIGatewayProxyEvent> or CreateAWSLambdaContextOptions<APIGatewayProxyEventV2>
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
[Read more here about payload format version](https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-develop-integrations-lambda.html)
|
|
138
|
+
|
|
139
|
+
## AWS Lambda Response Streaming Adapter
|
|
140
|
+
|
|
141
|
+
AWS Lambda supports streaming responses to clients with both Lambda Function URLs and API Gateway REST APIs.
|
|
142
|
+
|
|
143
|
+
> Response streaming is supported for Lambda Function URLs and API Gateway REST APIs. For API Gateway REST APIs, you need to configure the integration with `responseTransferMode: STREAM`. [Read more about Lambda response streaming](https://aws.amazon.com/blogs/compute/introducing-aws-lambda-response-streaming/) and [API Gateway response streaming](https://aws.amazon.com/blogs/compute/building-responsive-apis-with-amazon-api-gateway-response-streaming/).
|
|
144
|
+
|
|
145
|
+
### Response Streaming
|
|
146
|
+
|
|
147
|
+
The signature of a streaming handler is different from the default handler. The streaming handler additionally receives a writable stream parameter, `responseStream`, besides the default node handler parameters, `event` and `context`. To indicate that Lambda should stream your responses, you must wrap your function handler with the `awslambda.streamifyResponse()` decorator.
|
|
148
|
+
|
|
149
|
+
> Note that the `awslambda` namespace is automatically provided by the Lambda execution environment. You can import the types from `@types/aws-lambda` to augment the global namespace with the `awslambda` namespace.
|
|
150
|
+
|
|
151
|
+
With streaming, a procedure that returns an async generator, like `iterable` below, sends each value as it's yielded to clients using [`httpBatchStreamLink`](https://trpc.io/docs/client/links/httpBatchStreamLink).
|
|
152
|
+
|
|
153
|
+
```ts no-check title="server.ts"
|
|
154
|
+
/// <reference types="aws-lambda" />
|
|
155
|
+
import type { APIGatewayProxyEventV2 } from 'aws-lambda';
|
|
156
|
+
import type { CreateAWSLambdaContextOptions } from '@trpc/server/adapters/aws-lambda';
|
|
157
|
+
import { awsLambdaStreamingRequestHandler } from '@trpc/server/adapters/aws-lambda';
|
|
158
|
+
import { appRouter } from './router';
|
|
159
|
+
|
|
160
|
+
// created for each request
|
|
161
|
+
const createContext = ({
|
|
162
|
+
event,
|
|
163
|
+
context,
|
|
164
|
+
}: CreateAWSLambdaContextOptions<APIGatewayProxyEventV2>) => ({
|
|
165
|
+
// your context
|
|
166
|
+
});
|
|
167
|
+
type Context = Awaited<ReturnType<typeof createContext>>;
|
|
168
|
+
|
|
169
|
+
export const handler = awslambda.streamifyResponse(
|
|
170
|
+
awsLambdaStreamingRequestHandler({
|
|
171
|
+
router: appRouter,
|
|
172
|
+
createContext,
|
|
173
|
+
}),
|
|
174
|
+
);
|
|
175
|
+
```
|
|
176
|
+
|
|
177
|
+
## Common mistakes
|
|
178
|
+
|
|
179
|
+
- **Using `httpBatchLink` with a resource per procedure.** A batch request puts several procedures in one path, like `/getUser,createUser`, which none of those resources match. Use one greedy resource like `/trpc/{proxy+}`, which tRPC reads the procedure path from, or switch to `httpLink`.
|
|
180
|
+
- **Forgetting `awslambda.streamifyResponse()`.** Without it, Lambda calls `awsLambdaStreamingRequestHandler` as a regular handler, which has no response stream to write to.
|
|
181
|
+
- **Expecting the default handler to stream.** `awsLambdaRequestHandler` buffers the whole response before returning it, so `httpBatchStreamLink` responses arrive all at once. Use the [streaming handler](https://trpc.io/docs/server/adapters/aws-lambda#response-streaming) instead.
|
|
182
|
+
|
|
183
|
+
## Common options
|
|
184
|
+
|
|
185
|
+
Every HTTP adapter accepts these options, next to its own (like `endpoint` for Fetch, or `basePath` for Standalone):
|
|
186
|
+
|
|
187
|
+
| Option | Description |
|
|
188
|
+
| --------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
189
|
+
| `router` | Your app router. Required. |
|
|
190
|
+
| `createContext` | Creates the [context](https://trpc.io/docs/server/context) for each request. It receives the adapter's own objects (e.g. `req` and `res`) plus `info`. |
|
|
191
|
+
| `onError` | Called with `{ error, type, path, input, ctx, req }` for every error, e.g. to report it. See [Error handling](https://trpc.io/docs/server/error-handling#handling-errors). |
|
|
192
|
+
| `responseMeta` | Returns `{ status, headers }` for the response, e.g. for [caching](https://trpc.io/docs/server/caching). |
|
|
193
|
+
| `allowBatching` | Set to `false` to reject batch requests. Defaults to `true`. |
|
|
194
|
+
| `maxBatchSize` | Rejects batch requests with more calls than this with a `400 Bad Request`. Set `maxItems` on your batch link to the same or a lower value. |
|
|
195
|
+
| `allowMethodOverride` | Accepts queries sent as `POST`, for clients that set `methodOverride: 'POST'` on their link. Defaults to `false`. |
|
|
196
|
+
|
|
197
|
+
The Node.js adapters (Standalone, Express and Next.js) also accept:
|
|
198
|
+
|
|
199
|
+
- `maxBodySize`: the largest request body in bytes; larger ones are rejected with `413 PAYLOAD_TOO_LARGE`.
|
|
200
|
+
- `middleware`: a connect-style `(req, res, next)` function that runs before tRPC, e.g. [`cors()`](https://trpc.io/docs/server/adapters/standalone#handling-cors--options).
|
|
201
|
+
|
|
202
|
+
```ts no-check title="server.ts"
|
|
203
|
+
import { createHTTPServer } from '@trpc/server/adapters/standalone';
|
|
204
|
+
import { appRouter } from './router';
|
|
205
|
+
|
|
206
|
+
createHTTPServer({
|
|
207
|
+
router: appRouter,
|
|
208
|
+
createContext: () => ({}),
|
|
209
|
+
onError({ error, path }) {
|
|
210
|
+
console.error(`tRPC error on '${path}':`, error);
|
|
211
|
+
},
|
|
212
|
+
maxBatchSize: 10,
|
|
213
|
+
maxBodySize: 1_000_000, // 1 MB
|
|
214
|
+
}).listen(3000);
|
|
215
|
+
```
|
|
216
|
+
|
|
217
|
+
From https://trpc.io/docs/server/adapters#common-options
|
|
218
|
+
|
|
219
|
+
## Related skills
|
|
220
|
+
|
|
221
|
+
- `server-setup` (https://trpc.io/docs/server/overview): `npx @tanstack/intent@latest load @trpc/server#server-setup`
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: adapter-express
|
|
3
|
+
description: "Mount tRPC as Express middleware with createExpressMiddleware() from @trpc/server/adapters/express. Access Express req/res in createContext via CreateExpressContextOptions. Mount at a path prefix like app.use('/trpc', ...). Adapter options: onError, maxBatchSize, maxBodySize, middleware. Body parsers registered before tRPC (Express 4's express.json(), or express.raw()) break FormData and binary inputs, so scope them to non-tRPC routes."
|
|
4
|
+
requires:
|
|
5
|
+
- server-setup
|
|
6
|
+
sources:
|
|
7
|
+
- www/v11/docs/server/adapters/express.md
|
|
8
|
+
- www/v11/docs/server/adapters.md
|
|
9
|
+
metadata:
|
|
10
|
+
type: core
|
|
11
|
+
library: trpc
|
|
12
|
+
library_version: 11.22.2-canary.42.d3cd94bdd
|
|
13
|
+
---
|
|
14
|
+
|
|
15
|
+
<!-- Generated from www/v11/docs/server/adapters/express.md by www/build/skills.ts. Edit the docs instead. -->
|
|
16
|
+
|
|
17
|
+
# Express Adapter
|
|
18
|
+
|
|
19
|
+
From https://trpc.io/docs/server/adapters/express
|
|
20
|
+
|
|
21
|
+
## Example app
|
|
22
|
+
|
|
23
|
+
<table>
|
|
24
|
+
<thead>
|
|
25
|
+
<tr>
|
|
26
|
+
<th>Description</th>
|
|
27
|
+
<th>Links</th>
|
|
28
|
+
</tr>
|
|
29
|
+
</thead>
|
|
30
|
+
<tbody>
|
|
31
|
+
<tr>
|
|
32
|
+
<td>Express server & procedure calls with Node.js.</td>
|
|
33
|
+
<td>
|
|
34
|
+
<ul>
|
|
35
|
+
<li><a href="https://githubbox.com/trpc/trpc/tree/main/examples/express-server">CodeSandbox</a></li>
|
|
36
|
+
<li><a href="https://github.com/trpc/trpc/tree/main/examples/express-server">Source</a></li>
|
|
37
|
+
</ul>
|
|
38
|
+
</td>
|
|
39
|
+
</tr>
|
|
40
|
+
</tbody>
|
|
41
|
+
</table>
|
|
42
|
+
|
|
43
|
+
## How to add tRPC to existing Express project
|
|
44
|
+
|
|
45
|
+
### 1. Install deps
|
|
46
|
+
|
|
47
|
+
```bash
|
|
48
|
+
yarn add @trpc/server zod
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
> [Zod](https://github.com/colinhacks/zod) isn't a required dependency, but it's used in the sample router below.
|
|
52
|
+
|
|
53
|
+
### 2. Create a tRPC router
|
|
54
|
+
|
|
55
|
+
Implement your tRPC router. A sample router is given below:
|
|
56
|
+
|
|
57
|
+
```ts no-check title="server.ts"
|
|
58
|
+
import { initTRPC } from '@trpc/server';
|
|
59
|
+
import { z } from 'zod';
|
|
60
|
+
|
|
61
|
+
export const t = initTRPC.create();
|
|
62
|
+
|
|
63
|
+
export const appRouter = t.router({
|
|
64
|
+
getUser: t.procedure.input(z.string()).query((opts) => {
|
|
65
|
+
opts.input; // string
|
|
66
|
+
return { id: opts.input, name: 'Bilbo' };
|
|
67
|
+
}),
|
|
68
|
+
createUser: t.procedure
|
|
69
|
+
.input(z.object({ name: z.string().min(5) }))
|
|
70
|
+
.mutation(async (opts) => {
|
|
71
|
+
// use your ORM of choice
|
|
72
|
+
return { id: '1', ...opts.input };
|
|
73
|
+
}),
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
// export type definition of API
|
|
77
|
+
export type AppRouter = typeof appRouter;
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
If your router file starts getting too big, split your router into several subrouters each implemented in its own file. Then [merge them](https://trpc.io/docs/server/merging-routers) into a single root `appRouter`.
|
|
81
|
+
|
|
82
|
+
### 3. Use the Express adapter
|
|
83
|
+
|
|
84
|
+
tRPC includes an adapter for Express out of the box. This adapter lets you convert your tRPC router into an Express middleware.
|
|
85
|
+
|
|
86
|
+
```ts no-check title="server.ts"
|
|
87
|
+
import { initTRPC } from '@trpc/server';
|
|
88
|
+
import * as trpcExpress from '@trpc/server/adapters/express';
|
|
89
|
+
import express from 'express';
|
|
90
|
+
|
|
91
|
+
// created for each request
|
|
92
|
+
const createContext = ({
|
|
93
|
+
req,
|
|
94
|
+
res,
|
|
95
|
+
}: trpcExpress.CreateExpressContextOptions) => ({}); // no context
|
|
96
|
+
type Context = Awaited<ReturnType<typeof createContext>>;
|
|
97
|
+
|
|
98
|
+
const t = initTRPC.context<Context>().create();
|
|
99
|
+
const appRouter = t.router({
|
|
100
|
+
// [...]
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
const app = express();
|
|
104
|
+
|
|
105
|
+
app.use(
|
|
106
|
+
'/trpc',
|
|
107
|
+
trpcExpress.createExpressMiddleware({
|
|
108
|
+
router: appRouter,
|
|
109
|
+
createContext,
|
|
110
|
+
}),
|
|
111
|
+
);
|
|
112
|
+
|
|
113
|
+
app.listen(4000);
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
Your endpoints are now available via HTTP!
|
|
117
|
+
|
|
118
|
+
| Endpoint | HTTP URI |
|
|
119
|
+
| ------------ | ---------------------------------------------------------------------------------------------------------- |
|
|
120
|
+
| `getUser` | `GET http://localhost:4000/trpc/getUser?input=INPUT` <br/><br/>where `INPUT` is a URI-encoded JSON string. |
|
|
121
|
+
| `createUser` | `POST http://localhost:4000/trpc/createUser` <br/><br/>with `req.body` of type `{name: string}` |
|
|
122
|
+
|
|
123
|
+
`createContext` receives Express's `req` and `res`, so you can, for example, read `req.headers.authorization` to [authorize the user](https://trpc.io/docs/server/authorization). The middleware accepts the [options every adapter takes](https://trpc.io/docs/server/adapters#common-options), like `onError` and `maxBatchSize`, plus `middleware` and `maxBodySize`.
|
|
124
|
+
|
|
125
|
+
## Body parsers
|
|
126
|
+
|
|
127
|
+
tRPC parses request bodies itself, so tRPC routes don't need `express.json()`. If a body parser runs before tRPC anyway, tRPC uses the `req.body` it parsed, which works for JSON. For [FormData and binary inputs](https://trpc.io/docs/server/non-json-content-types) it depends on your Express version:
|
|
128
|
+
|
|
129
|
+
- **Express 5**: `express.json()` and `express.urlencoded()` leave other content types unread, so tRPC still reads them.
|
|
130
|
+
- **Express 4**: the parsers set `req.body` to `{}` on content types they skip, so tRPC receives `{}` instead of the form data or file.
|
|
131
|
+
- In both versions, a parser that reads the body you upload, like `express.raw()` for `application/octet-stream`, breaks binary inputs.
|
|
132
|
+
|
|
133
|
+
To be safe, register body parsers only on the routes that need them:
|
|
134
|
+
|
|
135
|
+
```ts no-check title="server.ts"
|
|
136
|
+
import * as trpcExpress from '@trpc/server/adapters/express';
|
|
137
|
+
import express from 'express';
|
|
138
|
+
import { appRouter } from './router';
|
|
139
|
+
|
|
140
|
+
const app = express();
|
|
141
|
+
|
|
142
|
+
app.use('/api', express.json()); // only for your own `/api/*` routes
|
|
143
|
+
app.post('/api/webhook', (req, res) => {
|
|
144
|
+
res.json({ received: req.body });
|
|
145
|
+
});
|
|
146
|
+
|
|
147
|
+
app.use('/trpc', trpcExpress.createExpressMiddleware({ router: appRouter }));
|
|
148
|
+
|
|
149
|
+
app.listen(4000);
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
## Common options
|
|
153
|
+
|
|
154
|
+
Every HTTP adapter accepts these options, next to its own (like `endpoint` for Fetch, or `basePath` for Standalone):
|
|
155
|
+
|
|
156
|
+
| Option | Description |
|
|
157
|
+
| --------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
158
|
+
| `router` | Your app router. Required. |
|
|
159
|
+
| `createContext` | Creates the [context](https://trpc.io/docs/server/context) for each request. It receives the adapter's own objects (e.g. `req` and `res`) plus `info`. |
|
|
160
|
+
| `onError` | Called with `{ error, type, path, input, ctx, req }` for every error, e.g. to report it. See [Error handling](https://trpc.io/docs/server/error-handling#handling-errors). |
|
|
161
|
+
| `responseMeta` | Returns `{ status, headers }` for the response, e.g. for [caching](https://trpc.io/docs/server/caching). |
|
|
162
|
+
| `allowBatching` | Set to `false` to reject batch requests. Defaults to `true`. |
|
|
163
|
+
| `maxBatchSize` | Rejects batch requests with more calls than this with a `400 Bad Request`. Set `maxItems` on your batch link to the same or a lower value. |
|
|
164
|
+
| `allowMethodOverride` | Accepts queries sent as `POST`, for clients that set `methodOverride: 'POST'` on their link. Defaults to `false`. |
|
|
165
|
+
|
|
166
|
+
The Node.js adapters (Standalone, Express and Next.js) also accept:
|
|
167
|
+
|
|
168
|
+
- `maxBodySize`: the largest request body in bytes; larger ones are rejected with `413 PAYLOAD_TOO_LARGE`.
|
|
169
|
+
- `middleware`: a connect-style `(req, res, next)` function that runs before tRPC, e.g. [`cors()`](https://trpc.io/docs/server/adapters/standalone#handling-cors--options).
|
|
170
|
+
|
|
171
|
+
```ts no-check title="server.ts"
|
|
172
|
+
import { createHTTPServer } from '@trpc/server/adapters/standalone';
|
|
173
|
+
import { appRouter } from './router';
|
|
174
|
+
|
|
175
|
+
createHTTPServer({
|
|
176
|
+
router: appRouter,
|
|
177
|
+
createContext: () => ({}),
|
|
178
|
+
onError({ error, path }) {
|
|
179
|
+
console.error(`tRPC error on '${path}':`, error);
|
|
180
|
+
},
|
|
181
|
+
maxBatchSize: 10,
|
|
182
|
+
maxBodySize: 1_000_000, // 1 MB
|
|
183
|
+
}).listen(3000);
|
|
184
|
+
```
|
|
185
|
+
|
|
186
|
+
From https://trpc.io/docs/server/adapters#common-options
|
|
187
|
+
|
|
188
|
+
## Related skills
|
|
189
|
+
|
|
190
|
+
- `server-setup` (https://trpc.io/docs/server/overview): `npx @tanstack/intent@latest load @trpc/server#server-setup`
|