Skip to content

Commit 45c1c99

Browse files
committed
feat: accessing request body via middleware
1 parent db8e612 commit 45c1c99

File tree

1 file changed

+36
-6
lines changed

1 file changed

+36
-6
lines changed

docs/pages/guides/middleware.mdx

+36-6
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,9 @@ export const POST = frames(async (ctx) => {
3737

3838
return {
3939
image: (
40-
<div tw="flex">The user's username is {ctx.message.requesterUserData.username}</div>
40+
<div tw="flex">
41+
The user's username is {ctx.message.requesterUserData.username}
42+
</div>
4143
),
4244
};
4345
});
@@ -73,7 +75,7 @@ export const POST = frames(
7375

7476
## Defining your own middleware
7577

76-
You can define your own middleware by creating a function that returns a promise that resolves to the next middleware, or a [Web API `Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response), or a `FrameDefinition`.
78+
You can define your own middleware by creating a function that returns a promise that resolves to the next middleware, or a [Web API `Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response), or a [`FrameDefinition`](/reference/core/createFrames#framedefinition).
7779

7880
Middleware can modify the context or return a response that will terminate the request early.
7981

@@ -84,10 +86,10 @@ Middleware can modify the context or return a response that will terminate the r
8486
```tsx [frames.ts]
8587
import { createFrames, types } from "frames.js/next";
8688

87-
const myMiddleware: types.FramesMiddleware<
88-
any,
89-
{ foo: string }
90-
> = async (ctx, next) => {
89+
const myMiddleware: types.FramesMiddleware<any, { foo: string }> = async (
90+
ctx,
91+
next
92+
) => {
9193
return next({ foo: "bar" });
9294
};
9395

@@ -117,3 +119,31 @@ export const POST = handler;
117119
```
118120

119121
:::
122+
123+
124+
### Accessing the request object
125+
126+
Sometimes you want to access the request object in your middleware - whenever you do this, you should clone the request object to avoid mutating it and breaking other middleware.
127+
128+
Here's an example of creating middleware which will add the request json to your context:
129+
130+
```tsx
131+
import { createFrames, types } from "frames.js/next";
132+
133+
const bodyMiddleware: types.FramesMiddleware<any, { body: any }> = async (
134+
ctx,
135+
next
136+
) => {
137+
const body = await ctx.request.clone().json();
138+
return next({ body });
139+
};
140+
141+
export const frames = createFrames({
142+
basePath: "/",
143+
initialState: {
144+
pageIndex: 0,
145+
},
146+
middleware: [bodyMiddleware],
147+
// The request body will now be available via `ctx.body` in your frame handlers
148+
});
149+
```

0 commit comments

Comments
 (0)