Skip to content

Commit 3a6af6d

Browse files
authored
docs/ts: passing data from middlewares (#1860)
1 parent c7994e2 commit 3a6af6d

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

docs/ts/develop/middleware.md

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,30 @@ The `next` function returns a `HandlerResponse` object which contains the respon
7474
Extra response headers can be added using `resp.header.set(key, value)` or `resp.header.add(key, value)`,
7575
if the endpoint is a [typed API endpoint](/docs/ts/primitives/defining-apis).
7676

77+
To pass data from middleware to an API handler, you can assign values to `req.data` within the middleware. These values can then be accessed in the handler using `currentRequest()`.
78+
79+
Here’s an example:
80+
81+
```ts
82+
const mw = middleware(async (req, next) => {
83+
// Assign a value to the request
84+
req.data.myMiddlewareData = { some: "data" };
85+
86+
return await next(req);
87+
});
88+
89+
export const ep = api(
90+
{ expose: true, method: "GET", path: "/endpoint" },
91+
async () => {
92+
const callMeta = currentRequest() as APICallMeta;
93+
94+
// Access the value in the API handler
95+
const myData = callMeta.middlewareData?.myMiddlewareData;
96+
// Use the data as needed
97+
},
98+
);
99+
```
100+
77101
## Middleware ordering
78102

79103
Middleware runs in the order they are defined in the [Service definitions](/docs/ts/primitives/services)

0 commit comments

Comments
 (0)