@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,97 +1,170 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: adapter-aws-lambda
|
|
3
|
-
description:
|
|
4
|
-
Deploy tRPC on AWS Lambda with awsLambdaRequestHandler() from
|
|
5
|
-
@trpc/server/adapters/aws-lambda for API Gateway v1 (REST, APIGatewayProxyEvent)
|
|
6
|
-
and v2 (HTTP, APIGatewayProxyEventV2), and Lambda Function URLs. Enable response
|
|
7
|
-
streaming with awsLambdaStreamingRequestHandler() wrapped in
|
|
8
|
-
awslambda.streamifyResponse(). CreateAWSLambdaContextOptions provides event and
|
|
9
|
-
context for context creation.
|
|
10
|
-
type: core
|
|
11
|
-
library: trpc
|
|
12
|
-
library_version: '11.16.0'
|
|
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.
|
|
13
4
|
requires:
|
|
14
5
|
- server-setup
|
|
15
6
|
sources:
|
|
16
|
-
- www/docs/server/adapters/aws-lambda.md
|
|
17
|
-
-
|
|
18
|
-
|
|
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.23.0
|
|
19
13
|
---
|
|
20
14
|
|
|
21
|
-
|
|
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
|
|
22
66
|
|
|
23
|
-
|
|
67
|
+
Implement your tRPC router. A sample router is given below:
|
|
24
68
|
|
|
25
|
-
```ts
|
|
26
|
-
// server.ts
|
|
69
|
+
```ts no-check title="server.ts"
|
|
27
70
|
import { initTRPC } from '@trpc/server';
|
|
28
|
-
import type { CreateAWSLambdaContextOptions } from '@trpc/server/adapters/aws-lambda';
|
|
29
|
-
import { awsLambdaRequestHandler } from '@trpc/server/adapters/aws-lambda';
|
|
30
|
-
import type { APIGatewayProxyEventV2 } from 'aws-lambda';
|
|
31
71
|
import { z } from 'zod';
|
|
32
72
|
|
|
33
|
-
const t = initTRPC.create();
|
|
73
|
+
export const t = initTRPC.create();
|
|
34
74
|
|
|
35
75
|
const appRouter = t.router({
|
|
36
|
-
|
|
37
|
-
.input
|
|
38
|
-
|
|
76
|
+
getUser: t.procedure.input(z.string()).query((opts) => {
|
|
77
|
+
opts.input; // string
|
|
78
|
+
return { id: opts.input, name: 'Bilbo' };
|
|
79
|
+
}),
|
|
39
80
|
});
|
|
40
81
|
|
|
82
|
+
// export type definition of API
|
|
41
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';
|
|
42
95
|
|
|
96
|
+
// created for each request
|
|
43
97
|
const createContext = ({
|
|
44
98
|
event,
|
|
45
99
|
context,
|
|
46
|
-
}: CreateAWSLambdaContextOptions<APIGatewayProxyEventV2>) => ({
|
|
47
|
-
|
|
48
|
-
lambdaContext: context,
|
|
49
|
-
});
|
|
100
|
+
}: CreateAWSLambdaContextOptions<APIGatewayProxyEventV2>) => ({}); // no context
|
|
101
|
+
type Context = Awaited<ReturnType<typeof createContext>>;
|
|
50
102
|
|
|
51
103
|
export const handler = awsLambdaRequestHandler({
|
|
52
104
|
router: appRouter,
|
|
53
105
|
createContext,
|
|
54
|
-
})
|
|
106
|
+
})
|
|
55
107
|
```
|
|
56
108
|
|
|
57
|
-
|
|
109
|
+
`awsLambdaRequestHandler` accepts the [options every adapter takes](https://trpc.io/docs/server/adapters#common-options), like `onError` and `maxBatchSize`.
|
|
58
110
|
|
|
59
|
-
|
|
111
|
+
Build & deploy your code, now use your API Gateway URL to call your function.
|
|
60
112
|
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
import type { APIGatewayProxyEvent } from 'aws-lambda';
|
|
65
|
-
import { appRouter } from './router';
|
|
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. |
|
|
66
116
|
|
|
67
|
-
|
|
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({
|
|
68
128
|
event,
|
|
69
129
|
context,
|
|
70
|
-
}: CreateAWSLambdaContextOptions<APIGatewayProxyEvent>)
|
|
71
|
-
|
|
72
|
-
}
|
|
130
|
+
}: CreateAWSLambdaContextOptions<APIGatewayProxyEvent>) {
|
|
131
|
+
// ...
|
|
132
|
+
}
|
|
73
133
|
|
|
74
|
-
|
|
75
|
-
router: appRouter,
|
|
76
|
-
createContext,
|
|
77
|
-
});
|
|
134
|
+
// CreateAWSLambdaContextOptions<APIGatewayProxyEvent> or CreateAWSLambdaContextOptions<APIGatewayProxyEventV2>
|
|
78
135
|
```
|
|
79
136
|
|
|
80
|
-
|
|
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
|
|
81
146
|
|
|
82
|
-
|
|
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.
|
|
83
148
|
|
|
84
|
-
|
|
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"
|
|
85
154
|
/// <reference types="aws-lambda" />
|
|
155
|
+
import type { APIGatewayProxyEventV2 } from 'aws-lambda';
|
|
86
156
|
import type { CreateAWSLambdaContextOptions } from '@trpc/server/adapters/aws-lambda';
|
|
87
157
|
import { awsLambdaStreamingRequestHandler } from '@trpc/server/adapters/aws-lambda';
|
|
88
|
-
import type { APIGatewayProxyEventV2 } from 'aws-lambda';
|
|
89
158
|
import { appRouter } from './router';
|
|
90
159
|
|
|
160
|
+
// created for each request
|
|
91
161
|
const createContext = ({
|
|
92
162
|
event,
|
|
93
163
|
context,
|
|
94
|
-
}: CreateAWSLambdaContextOptions<APIGatewayProxyEventV2>) => ({
|
|
164
|
+
}: CreateAWSLambdaContextOptions<APIGatewayProxyEventV2>) => ({
|
|
165
|
+
// your context
|
|
166
|
+
});
|
|
167
|
+
type Context = Awaited<ReturnType<typeof createContext>>;
|
|
95
168
|
|
|
96
169
|
export const handler = awslambda.streamifyResponse(
|
|
97
170
|
awsLambdaStreamingRequestHandler({
|
|
@@ -101,103 +174,48 @@ export const handler = awslambda.streamifyResponse(
|
|
|
101
174
|
);
|
|
102
175
|
```
|
|
103
176
|
|
|
104
|
-
|
|
177
|
+
## Common mistakes
|
|
105
178
|
|
|
106
|
-
|
|
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.
|
|
107
182
|
|
|
108
|
-
|
|
109
|
-
import { initTRPC } from '@trpc/server';
|
|
183
|
+
## Common options
|
|
110
184
|
|
|
111
|
-
|
|
185
|
+
Every HTTP adapter accepts these options, next to its own (like `endpoint` for Fetch, or `basePath` for Standalone):
|
|
112
186
|
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
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`. |
|
|
122
196
|
|
|
123
|
-
|
|
197
|
+
The Node.js adapters (Standalone, Express and Next.js) also accept:
|
|
124
198
|
|
|
125
|
-
|
|
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).
|
|
126
201
|
|
|
127
|
-
```ts
|
|
128
|
-
import {
|
|
202
|
+
```ts no-check title="server.ts"
|
|
203
|
+
import { createHTTPServer } from '@trpc/server/adapters/standalone';
|
|
129
204
|
import { appRouter } from './router';
|
|
130
205
|
|
|
131
|
-
|
|
206
|
+
createHTTPServer({
|
|
132
207
|
router: appRouter,
|
|
133
|
-
createContext,
|
|
208
|
+
createContext: () => ({}),
|
|
209
|
+
onError({ error, path }) {
|
|
210
|
+
console.error(`tRPC error on '${path}':`, error);
|
|
211
|
+
},
|
|
134
212
|
maxBatchSize: 10,
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
Requests batching more than `maxBatchSize` operations are rejected with a `400 Bad Request` error. Set `maxItems` on your client's `httpBatchLink` to the same value to avoid exceeding the limit.
|
|
139
|
-
|
|
140
|
-
## Common Mistakes
|
|
141
|
-
|
|
142
|
-
### HIGH Using httpBatchLink with per-procedure API Gateway resources
|
|
143
|
-
|
|
144
|
-
Wrong:
|
|
145
|
-
|
|
146
|
-
```ts
|
|
147
|
-
// API Gateway has a separate resource for each procedure
|
|
148
|
-
// e.g., /getUser, /createUser
|
|
149
|
-
// Client uses:
|
|
150
|
-
import { httpBatchLink } from '@trpc/client';
|
|
151
|
-
|
|
152
|
-
httpBatchLink({ url: 'https://api.example.com' });
|
|
153
|
-
// Batch request to /getUser,createUser → 404
|
|
154
|
-
```
|
|
155
|
-
|
|
156
|
-
Correct:
|
|
157
|
-
|
|
158
|
-
```ts
|
|
159
|
-
import { httpBatchLink, httpLink } from '@trpc/client';
|
|
160
|
-
|
|
161
|
-
// Option A: Single catch-all resource (e.g., /{proxy+})
|
|
162
|
-
httpBatchLink({ url: 'https://api.example.com' });
|
|
163
|
-
|
|
164
|
-
// Option B: Per-procedure resources with httpLink (no batching)
|
|
165
|
-
httpLink({ url: 'https://api.example.com' });
|
|
166
|
-
```
|
|
167
|
-
|
|
168
|
-
`httpBatchLink` sends multiple procedure names in the URL path (e.g., `getUser,createUser`). If API Gateway routes are per-procedure, the combined path does not match any resource and returns 404. Use a single catch-all resource or switch to `httpLink`.
|
|
169
|
-
|
|
170
|
-
Source: www/docs/server/adapters/aws-lambda.md
|
|
171
|
-
|
|
172
|
-
### HIGH Forgetting streamifyResponse wrapper for streaming
|
|
173
|
-
|
|
174
|
-
Wrong:
|
|
175
|
-
|
|
176
|
-
```ts
|
|
177
|
-
export const handler = awsLambdaStreamingRequestHandler({
|
|
178
|
-
router: appRouter,
|
|
179
|
-
createContext,
|
|
180
|
-
});
|
|
213
|
+
maxBodySize: 1_000_000, // 1 MB
|
|
214
|
+
}).listen(3000);
|
|
181
215
|
```
|
|
182
216
|
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
```ts
|
|
186
|
-
export const handler = awslambda.streamifyResponse(
|
|
187
|
-
awsLambdaStreamingRequestHandler({
|
|
188
|
-
router: appRouter,
|
|
189
|
-
createContext,
|
|
190
|
-
}),
|
|
191
|
-
);
|
|
192
|
-
```
|
|
193
|
-
|
|
194
|
-
`awsLambdaStreamingRequestHandler` requires wrapping with `awslambda.streamifyResponse()` to enable Lambda response streaming. Without it, Lambda treats the handler as a standard buffered response.
|
|
195
|
-
|
|
196
|
-
Source: www/docs/server/adapters/aws-lambda.md
|
|
217
|
+
From https://trpc.io/docs/server/adapters#common-options
|
|
197
218
|
|
|
198
|
-
##
|
|
219
|
+
## Related skills
|
|
199
220
|
|
|
200
|
-
-
|
|
201
|
-
- **adapter-fetch** -- alternative for edge/serverless runtimes using Fetch API
|
|
202
|
-
- **links** -- `httpBatchLink` vs `httpLink` for API Gateway routing considerations
|
|
203
|
-
- AWS Lambda docs: https://docs.aws.amazon.com/lambda/latest/dg/welcome.html
|
|
221
|
+
- `server-setup` (https://trpc.io/docs/server/overview): `npx @tanstack/intent@latest load @trpc/server#server-setup`
|
|
@@ -1,101 +1,107 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: adapter-express
|
|
3
|
-
description:
|
|
4
|
-
Mount tRPC as Express middleware with createExpressMiddleware() from
|
|
5
|
-
@trpc/server/adapters/express. Access Express req/res in createContext via
|
|
6
|
-
CreateExpressContextOptions. Mount at a path prefix like app.use('/trpc', ...).
|
|
7
|
-
Avoid global express.json() conflicting with tRPC body parsing for FormData.
|
|
8
|
-
type: core
|
|
9
|
-
library: trpc
|
|
10
|
-
library_version: '11.16.0'
|
|
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."
|
|
11
4
|
requires:
|
|
12
5
|
- server-setup
|
|
13
6
|
sources:
|
|
14
|
-
- www/docs/server/adapters/express.md
|
|
15
|
-
-
|
|
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.23.0
|
|
16
13
|
---
|
|
17
14
|
|
|
18
|
-
|
|
15
|
+
<!-- Generated from www/v11/docs/server/adapters/express.md by www/build/skills.ts. Edit the docs instead. -->
|
|
19
16
|
|
|
20
|
-
|
|
17
|
+
# Express Adapter
|
|
21
18
|
|
|
22
|
-
|
|
23
|
-
// server.ts
|
|
24
|
-
import { initTRPC } from '@trpc/server';
|
|
25
|
-
import * as trpcExpress from '@trpc/server/adapters/express';
|
|
26
|
-
import express from 'express';
|
|
27
|
-
import { z } from 'zod';
|
|
19
|
+
From https://trpc.io/docs/server/adapters/express
|
|
28
20
|
|
|
29
|
-
|
|
30
|
-
req,
|
|
31
|
-
res,
|
|
32
|
-
}: trpcExpress.CreateExpressContextOptions) => {
|
|
33
|
-
return { req, res };
|
|
34
|
-
};
|
|
35
|
-
type Context = Awaited<ReturnType<typeof createContext>>;
|
|
21
|
+
## Example app
|
|
36
22
|
|
|
37
|
-
|
|
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>
|
|
38
42
|
|
|
39
|
-
|
|
40
|
-
greet: t.procedure
|
|
41
|
-
.input(z.object({ name: z.string() }))
|
|
42
|
-
.query(({ input }) => ({ greeting: `Hello, ${input.name}!` })),
|
|
43
|
-
});
|
|
43
|
+
## How to add tRPC to existing Express project
|
|
44
44
|
|
|
45
|
-
|
|
45
|
+
### 1. Install deps
|
|
46
46
|
|
|
47
|
-
|
|
47
|
+
```bash
|
|
48
|
+
yarn add @trpc/server zod
|
|
49
|
+
```
|
|
48
50
|
|
|
49
|
-
|
|
50
|
-
'/trpc',
|
|
51
|
-
trpcExpress.createExpressMiddleware({
|
|
52
|
-
router: appRouter,
|
|
53
|
-
createContext,
|
|
54
|
-
}),
|
|
55
|
-
);
|
|
51
|
+
> [Zod](https://github.com/colinhacks/zod) isn't a required dependency, but it's used in the sample router below.
|
|
56
52
|
|
|
57
|
-
|
|
58
|
-
console.log('Listening on http://localhost:4000');
|
|
59
|
-
});
|
|
60
|
-
```
|
|
53
|
+
### 2. Create a tRPC router
|
|
61
54
|
|
|
62
|
-
|
|
55
|
+
Implement your tRPC router. A sample router is given below:
|
|
63
56
|
|
|
64
|
-
|
|
57
|
+
```ts no-check title="server.ts"
|
|
58
|
+
import { initTRPC } from '@trpc/server';
|
|
59
|
+
import { z } from 'zod';
|
|
65
60
|
|
|
66
|
-
|
|
67
|
-
import * as trpcExpress from '@trpc/server/adapters/express';
|
|
61
|
+
export const t = initTRPC.create();
|
|
68
62
|
|
|
69
|
-
const
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
}
|
|
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
|
+
});
|
|
76
75
|
|
|
77
|
-
type
|
|
76
|
+
// export type definition of API
|
|
77
|
+
export type AppRouter = typeof appRouter;
|
|
78
78
|
```
|
|
79
79
|
|
|
80
|
-
|
|
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
81
|
|
|
82
|
-
###
|
|
82
|
+
### 3. Use the Express adapter
|
|
83
83
|
|
|
84
|
-
|
|
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';
|
|
85
88
|
import * as trpcExpress from '@trpc/server/adapters/express';
|
|
86
|
-
import cors from 'cors';
|
|
87
89
|
import express from 'express';
|
|
88
|
-
import { createContext } from './context';
|
|
89
|
-
import { appRouter } from './router';
|
|
90
|
-
|
|
91
|
-
const app = express();
|
|
92
90
|
|
|
93
|
-
|
|
91
|
+
// created for each request
|
|
92
|
+
const createContext = ({
|
|
93
|
+
req,
|
|
94
|
+
res,
|
|
95
|
+
}: trpcExpress.CreateExpressContextOptions) => ({}); // no context
|
|
96
|
+
type Context = Awaited<ReturnType<typeof createContext>>;
|
|
94
97
|
|
|
95
|
-
|
|
96
|
-
|
|
98
|
+
const t = initTRPC.context<Context>().create();
|
|
99
|
+
const appRouter = t.router({
|
|
100
|
+
// [...]
|
|
97
101
|
});
|
|
98
102
|
|
|
103
|
+
const app = express();
|
|
104
|
+
|
|
99
105
|
app.use(
|
|
100
106
|
'/trpc',
|
|
101
107
|
trpcExpress.createExpressMiddleware({
|
|
@@ -107,70 +113,78 @@ app.use(
|
|
|
107
113
|
app.listen(4000);
|
|
108
114
|
```
|
|
109
115
|
|
|
110
|
-
|
|
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:
|
|
111
128
|
|
|
112
|
-
|
|
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"
|
|
113
136
|
import * as trpcExpress from '@trpc/server/adapters/express';
|
|
114
137
|
import express from 'express';
|
|
115
|
-
import { createContext } from './context';
|
|
116
138
|
import { appRouter } from './router';
|
|
117
139
|
|
|
118
140
|
const app = express();
|
|
119
141
|
|
|
120
|
-
app.use(
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
}),
|
|
127
|
-
);
|
|
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 }));
|
|
128
148
|
|
|
129
149
|
app.listen(4000);
|
|
130
150
|
```
|
|
131
151
|
|
|
132
|
-
|
|
152
|
+
## Common options
|
|
133
153
|
|
|
134
|
-
|
|
154
|
+
Every HTTP adapter accepts these options, next to its own (like `endpoint` for Fetch, or `basePath` for Standalone):
|
|
135
155
|
|
|
136
|
-
|
|
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`. |
|
|
137
165
|
|
|
138
|
-
|
|
166
|
+
The Node.js adapters (Standalone, Express and Next.js) also accept:
|
|
139
167
|
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
app.use(express.json()); // global body parser
|
|
143
|
-
app.use(
|
|
144
|
-
'/trpc',
|
|
145
|
-
trpcExpress.createExpressMiddleware({
|
|
146
|
-
router: appRouter,
|
|
147
|
-
createContext,
|
|
148
|
-
}),
|
|
149
|
-
);
|
|
150
|
-
```
|
|
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).
|
|
151
170
|
|
|
152
|
-
|
|
171
|
+
```ts no-check title="server.ts"
|
|
172
|
+
import { createHTTPServer } from '@trpc/server/adapters/standalone';
|
|
173
|
+
import { appRouter } from './router';
|
|
153
174
|
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
}),
|
|
164
|
-
);
|
|
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);
|
|
165
184
|
```
|
|
166
185
|
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
Source: www/docs/server/non-json-content-types.md
|
|
186
|
+
From https://trpc.io/docs/server/adapters#common-options
|
|
170
187
|
|
|
171
|
-
##
|
|
188
|
+
## Related skills
|
|
172
189
|
|
|
173
|
-
-
|
|
174
|
-
- **adapter-standalone** -- simpler adapter when Express middleware ecosystem is not needed
|
|
175
|
-
- **auth** -- extracting JWT from `req.headers.authorization` in context
|
|
176
|
-
- Express docs: https://expressjs.com/en/guide/using-middleware.html
|
|
190
|
+
- `server-setup` (https://trpc.io/docs/server/overview): `npx @tanstack/intent@latest load @trpc/server#server-setup`
|