@trpc/server 11.22.2-canary.16.ea96ec538 → 11.22.2-canary.37.6d6969c7c
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/dist/adapters/standalone.cjs +8 -2
- 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 +8 -2
- package/dist/adapters/standalone.mjs.map +1 -1
- 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/src/adapters/standalone.ts +11 -5
|
@@ -15,13 +15,19 @@ http = require_rolldown_runtime.__toESM(http, 1);
|
|
|
15
15
|
* import type { HTTPBaseHandlerOptions } from '@trpc/server/http'
|
|
16
16
|
* ```
|
|
17
17
|
*/
|
|
18
|
+
const trimSlashes = (path) => {
|
|
19
|
+
path = path.startsWith("/") ? path.slice(1) : path;
|
|
20
|
+
path = path.endsWith("/") ? path.slice(0, -1) : path;
|
|
21
|
+
return path;
|
|
22
|
+
};
|
|
18
23
|
function createHandler(opts) {
|
|
19
24
|
var _opts$basePath;
|
|
20
|
-
const
|
|
25
|
+
const basePath = trimSlashes((_opts$basePath = opts.basePath) !== null && _opts$basePath !== void 0 ? _opts$basePath : "/");
|
|
21
26
|
return (req, res) => {
|
|
22
27
|
let path = "";
|
|
23
28
|
require_codes.run(async () => {
|
|
24
|
-
|
|
29
|
+
const url = require_node_http.createURL(req);
|
|
30
|
+
path = trimSlashes(trimSlashes(url.pathname).slice(basePath.length));
|
|
25
31
|
await require_node_http.nodeHTTPRequestHandler(require_getErrorShape._objectSpread2(require_getErrorShape._objectSpread2({}, opts), {}, {
|
|
26
32
|
req,
|
|
27
33
|
res,
|
|
@@ -7,7 +7,6 @@ type StandaloneHandlerOptions<TRouter extends AnyRouter, TRequest extends NodeHT
|
|
|
7
7
|
/**
|
|
8
8
|
* The base path to handle requests for.
|
|
9
9
|
* This will be sliced from the beginning of the request path
|
|
10
|
-
* (Do not miss including the trailing slash)
|
|
11
10
|
* @default '/'
|
|
12
11
|
* @example '/trpc/'
|
|
13
12
|
* @example '/trpc/api/'
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"standalone.d.cts","names":[],"sources":["../../src/adapters/standalone.ts"],"mappings":";;;;;
|
|
1
|
+
{"version":3,"file":"standalone.d.cts","names":[],"sources":["../../src/adapters/standalone.ts"],"mappings":";;;;;KAqCK,yBACH,gBAAgB,WAChB,iBAAiB,iBACjB,kBAAkB,oBAChB,uBAAuB,SAAS,UAAU;;;;;;;;EAQ5C;;YAIU,yBAAyB,gBAAgB,aACnD,yBAAyB,SAAS,KAAK,iBAAiB,KAAK;YAEnD,2BAA2B,+BACrC,KAAK,iBACL,KAAK;;;;wBAyCS,kBAAkB,gBAAgB,WAChD,MAAM,yBAAyB,WAC9B,KAAK;wBAIQ,iBAAiB,gBAAgB,WAC/C,MAAM,yBAAyB,WAAQ,KAAA,cAAA,KAAA,wBAAA,KAAA;YAM7B,0BAA0B,gBAAgB,aACpD,yBACE,SACA,MAAM,oBACN,MAAM;YAGE,4BAA4B,+BACtC,MAAM,oBACN,MAAM;wBAGQ,mBAAmB,MAAM,0BAA0B,cAAU,KAAA,MAAA,oBAAA,KAAA,MAAA,oBAAA,MAAA"}
|
|
@@ -7,7 +7,6 @@ type StandaloneHandlerOptions<TRouter extends AnyRouter, TRequest extends NodeHT
|
|
|
7
7
|
/**
|
|
8
8
|
* The base path to handle requests for.
|
|
9
9
|
* This will be sliced from the beginning of the request path
|
|
10
|
-
* (Do not miss including the trailing slash)
|
|
11
10
|
* @default '/'
|
|
12
11
|
* @example '/trpc/'
|
|
13
12
|
* @example '/trpc/api/'
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"standalone.d.mts","names":[],"sources":["../../src/adapters/standalone.ts"],"mappings":";;;;;
|
|
1
|
+
{"version":3,"file":"standalone.d.mts","names":[],"sources":["../../src/adapters/standalone.ts"],"mappings":";;;;;KAqCK,yBACH,gBAAgB,WAChB,iBAAiB,iBACjB,kBAAkB,oBAChB,uBAAuB,SAAS,UAAU;;;;;;;;EAQ5C;;YAIU,yBAAyB,gBAAgB,aACnD,yBAAyB,SAAS,KAAK,iBAAiB,KAAK;YAEnD,2BAA2B,+BACrC,KAAK,iBACL,KAAK;;;;wBAyCS,kBAAkB,gBAAgB,WAChD,MAAM,yBAAyB,WAC9B,KAAK;wBAIQ,iBAAiB,gBAAgB,WAC/C,MAAM,yBAAyB,WAAQ,KAAA,cAAA,KAAA,wBAAA,KAAA;YAM7B,0BAA0B,gBAAgB,aACpD,yBACE,SACA,MAAM,oBACN,MAAM;YAGE,4BAA4B,+BACtC,MAAM,oBACN,MAAM;wBAGQ,mBAAmB,MAAM,0BAA0B,cAAU,KAAA,MAAA,oBAAA,KAAA,MAAA,oBAAA,MAAA"}
|
|
@@ -12,13 +12,19 @@ import http from "http";
|
|
|
12
12
|
* import type { HTTPBaseHandlerOptions } from '@trpc/server/http'
|
|
13
13
|
* ```
|
|
14
14
|
*/
|
|
15
|
+
const trimSlashes = (path) => {
|
|
16
|
+
path = path.startsWith("/") ? path.slice(1) : path;
|
|
17
|
+
path = path.endsWith("/") ? path.slice(0, -1) : path;
|
|
18
|
+
return path;
|
|
19
|
+
};
|
|
15
20
|
function createHandler(opts) {
|
|
16
21
|
var _opts$basePath;
|
|
17
|
-
const
|
|
22
|
+
const basePath = trimSlashes((_opts$basePath = opts.basePath) !== null && _opts$basePath !== void 0 ? _opts$basePath : "/");
|
|
18
23
|
return (req, res) => {
|
|
19
24
|
let path = "";
|
|
20
25
|
run(async () => {
|
|
21
|
-
|
|
26
|
+
const url = createURL(req);
|
|
27
|
+
path = trimSlashes(trimSlashes(url.pathname).slice(basePath.length));
|
|
22
28
|
await nodeHTTPRequestHandler(_objectSpread2(_objectSpread2({}, opts), {}, {
|
|
23
29
|
req,
|
|
24
30
|
res,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"standalone.mjs","names":[],"sources":["../../src/adapters/standalone.ts"],"sourcesContent":["/**\n * If you're making an adapter for tRPC and looking at this file for reference, you should import types and functions from `@trpc/server` and `@trpc/server/http`\n *\n * @example\n * ```ts\n * import type { AnyTRPCRouter } from '@trpc/server'\n * import type { HTTPBaseHandlerOptions } from '@trpc/server/http'\n * ```\n */\n\nimport http from 'http';\n// --- http2 ---\nimport type * as http2 from 'http2';\n// @trpc/server\nimport { type AnyRouter } from '../@trpc/server';\n// oxlint-disable-next-line no-restricted-imports\nimport { run } from '../unstable-core-do-not-import';\nimport type {\n NodeHTTPCreateContextFnOptions,\n NodeHTTPHandlerOptions,\n NodeHTTPRequest,\n NodeHTTPResponse,\n} from './node-http';\nimport {\n createURL,\n internal_exceptionHandler,\n nodeHTTPRequestHandler,\n} from './node-http';\n\ntype StandaloneHandlerOptions<\n TRouter extends AnyRouter,\n TRequest extends NodeHTTPRequest,\n TResponse extends NodeHTTPResponse,\n> = NodeHTTPHandlerOptions<TRouter, TRequest, TResponse> & {\n /**\n * The base path to handle requests for.\n * This will be sliced from the beginning of the request path\n *
|
|
1
|
+
{"version":3,"file":"standalone.mjs","names":[],"sources":["../../src/adapters/standalone.ts"],"sourcesContent":["/**\n * If you're making an adapter for tRPC and looking at this file for reference, you should import types and functions from `@trpc/server` and `@trpc/server/http`\n *\n * @example\n * ```ts\n * import type { AnyTRPCRouter } from '@trpc/server'\n * import type { HTTPBaseHandlerOptions } from '@trpc/server/http'\n * ```\n */\n\nimport http from 'http';\n// --- http2 ---\nimport type * as http2 from 'http2';\n// @trpc/server\nimport { type AnyRouter } from '../@trpc/server';\n// oxlint-disable-next-line no-restricted-imports\nimport { run } from '../unstable-core-do-not-import';\nimport type {\n NodeHTTPCreateContextFnOptions,\n NodeHTTPHandlerOptions,\n NodeHTTPRequest,\n NodeHTTPResponse,\n} from './node-http';\nimport {\n createURL,\n internal_exceptionHandler,\n nodeHTTPRequestHandler,\n} from './node-http';\n\n// same as in the fetch adapter\nconst trimSlashes = (path: string): string => {\n path = path.startsWith('/') ? path.slice(1) : path;\n path = path.endsWith('/') ? path.slice(0, -1) : path;\n\n return path;\n};\n\ntype StandaloneHandlerOptions<\n TRouter extends AnyRouter,\n TRequest extends NodeHTTPRequest,\n TResponse extends NodeHTTPResponse,\n> = NodeHTTPHandlerOptions<TRouter, TRequest, TResponse> & {\n /**\n * The base path to handle requests for.\n * This will be sliced from the beginning of the request path\n * @default '/'\n * @example '/trpc/'\n * @example '/trpc/api/'\n */\n basePath?: string;\n};\n\n// --- http1 ---\nexport type CreateHTTPHandlerOptions<TRouter extends AnyRouter> =\n StandaloneHandlerOptions<TRouter, http.IncomingMessage, http.ServerResponse>;\n\nexport type CreateHTTPContextOptions = NodeHTTPCreateContextFnOptions<\n http.IncomingMessage,\n http.ServerResponse\n>;\n\nfunction createHandler<\n TRouter extends AnyRouter,\n TRequest extends NodeHTTPRequest,\n TResponse extends NodeHTTPResponse,\n>(\n opts: StandaloneHandlerOptions<TRouter, TRequest, TResponse>,\n): (req: TRequest, res: TResponse) => void {\n const basePath = trimSlashes(opts.basePath ?? '/');\n\n return (req, res) => {\n let path = '';\n\n run(async () => {\n const url = createURL(req);\n\n // get procedure(s) path and remove the slashes around it\n path = trimSlashes(trimSlashes(url.pathname).slice(basePath.length));\n\n await nodeHTTPRequestHandler({\n ...opts,\n req,\n res,\n path,\n });\n }).catch(\n internal_exceptionHandler({\n req,\n res,\n path,\n ...opts,\n }),\n );\n };\n}\n\n/**\n * @internal\n */\nexport function createHTTPHandler<TRouter extends AnyRouter>(\n opts: CreateHTTPHandlerOptions<TRouter>,\n): http.RequestListener {\n return createHandler(opts);\n}\n\nexport function createHTTPServer<TRouter extends AnyRouter>(\n opts: CreateHTTPHandlerOptions<TRouter>,\n) {\n return http.createServer(createHTTPHandler(opts));\n}\n\n// --- http2 ---\nexport type CreateHTTP2HandlerOptions<TRouter extends AnyRouter> =\n StandaloneHandlerOptions<\n TRouter,\n http2.Http2ServerRequest,\n http2.Http2ServerResponse\n >;\n\nexport type CreateHTTP2ContextOptions = NodeHTTPCreateContextFnOptions<\n http2.Http2ServerRequest,\n http2.Http2ServerResponse\n>;\n\nexport function createHTTP2Handler(opts: CreateHTTP2HandlerOptions<AnyRouter>) {\n return createHandler(opts);\n}\n"],"mappings":";;;;;;;;;;;;;;AA8BA,MAAM,eAAe,SAAyB;CAC5C,OAAO,KAAK,WAAW,GAAG,IAAI,KAAK,MAAM,CAAC,IAAI;CAC9C,OAAO,KAAK,SAAS,GAAG,IAAI,KAAK,MAAM,GAAG,EAAE,IAAI;CAEhD,OAAO;AACT;AA0BA,SAAS,cAKP,MACyC;;CACzC,MAAM,WAAW,aAAA,iBAAY,KAAK,cAAA,QAAA,mBAAA,KAAA,IAAA,iBAAY,GAAG;CAEjD,QAAQ,KAAK,QAAQ;EACnB,IAAI,OAAO;EAEX,IAAI,YAAY;GACd,MAAM,MAAM,UAAU,GAAG;GAGzB,OAAO,YAAY,YAAY,IAAI,QAAQ,CAAC,CAAC,MAAM,SAAS,MAAM,CAAC;GAEnE,MAAM,uBAAA,eAAA,eAAA,CAAA,GACD,IAAA,GAAA,CAAA,GAAA;IACH;IACA;IACA;GACF,CAAA,CAAC;EACH,CAAC,CAAC,CAAC,MACD,0BAAA,eAAA;GACE;GACA;GACA;EACG,GAAA,IACL,CAAC,CACH;CACF;AACF;;;;AAKA,SAAgB,kBACd,MACsB;CACtB,OAAO,cAAc,IAAI;AAC3B;AAEA,SAAgB,iBACd,MACA;CACA,OAAO,KAAK,aAAa,kBAAkB,IAAI,CAAC;AAClD;AAeA,SAAgB,mBAAmB,MAA4C;CAC7E,OAAO,cAAc,IAAI;AAC3B"}
|
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.37.6d6969c7c",
|
|
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": "6d6969c7cd8eb140c8dcc42e33750b4e88eaaa0d"
|
|
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.37.6d6969c7c
|
|
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.37.6d6969c7c
|
|
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`
|