Skip to content

Commit

Permalink
docs(cloudflare-pages): Accessing EventContext (#479)
Browse files Browse the repository at this point in the history
  • Loading branch information
yusukebe authored Sep 11, 2024
1 parent 92a6f0f commit 32fd22c
Showing 1 changed file with 42 additions and 0 deletions.
42 changes: 42 additions & 0 deletions docs/getting-started/cloudflare-pages.md
Original file line number Diff line number Diff line change
Expand Up @@ -361,3 +361,45 @@ export const onRequest = [
handleMiddleware(middleware3),
]
```

### Accessing `EventContext`

You can access [`EventContext`](https://developers.cloudflare.com/pages/functions/api-reference/#eventcontext) object via `c.env` in `handleMiddleware`.

```ts
// functions/_middleware.ts
import { handleMiddleware } from 'hono/cloudflare-pages'

export const onRequest = [
handleMiddleware(async (c, next) => {
c.env.eventContext.data.user = 'Joe'
await next()
}),
]
```

Then, you can access the data value in via `c.env.eventContext` in the handler:

```ts
// functions/api/[[route]].ts
import type { EventContext } from 'hono/cloudflare-pages'
import { handle } from 'hono/cloudflare-pages'

// ...

type Env = {
Bindings: {
eventContext: EventContext
}
}

const app = new Hono<Env>()

app.get('/hello', (c) => {
return c.json({
message: `Hello, ${c.env.eventContext.data.user}!`, // 'Joe'
})
})

export const onRequest = handle(app)
```

0 comments on commit 32fd22c

Please sign in to comment.