From 707e60d754dea6708562da6d718e14509eed8bcc Mon Sep 17 00:00:00 2001 From: Yusuke Wada Date: Wed, 11 Sep 2024 14:14:33 +0900 Subject: [PATCH] docs(cloudflare-pages): Accessing `EventContext` --- docs/getting-started/cloudflare-pages.md | 42 ++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/docs/getting-started/cloudflare-pages.md b/docs/getting-started/cloudflare-pages.md index 1dfa1d34..e19cd1be 100644 --- a/docs/getting-started/cloudflare-pages.md +++ b/docs/getting-started/cloudflare-pages.md @@ -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() + +app.get('/hello', (c) => { + return c.json({ + message: `Hello, ${c.env.eventContext.data.user}!`, // 'Joe' + }) +}) + +export const onRequest = handle(app) +```