Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs: add more details to cloudflare workers bindings section #548

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions docs/getting-started/cloudflare-workers.md
Original file line number Diff line number Diff line change
Expand Up @@ -247,6 +247,50 @@ app.put('/upload/:key', async (c, next) => {
})
```

If the request handler were put into a separate file, you can pass the "_type struct_" through `Context`.

```ts
import { Context } from 'hono'

type Bindings = {
MY_BUCKET: R2Bucket
USERNAME: string
PASSWORD: string
}

export const handler = async (c: Context<{
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We don't recommend using Context for c for the following reasons:

https://hono.dev/docs/guides/best-practices#don-t-make-controllers-when-possible

Bindings: Bindings
}>) => {
return c.text(c.env.USERNAME)
}
```

Cloudflare Wrangler also had the ability to generate types for bindings, So you can use the generated types directly in any `.ts` file.

```sh
wrangler types
```

After running the command you will get a `worker-configuration.d.ts` file which will have a typescript interface called `Env`.

```ts
// Generated by Wrangler by running `wrangler types`

interface Env {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The naming Env will be confusing because we often use the following code:

type Env = {
  Bindings: {
    KV: KVNamespace
  },
  Variables: {
    foo: string
  }
}

Actually, the code which is generated from C3 does not use Env but uses CloudflareBindings:

// Generated by Wrangler by running `wrangler types --env-interface CloudflareBindings`

interface CloudflareBindings {
	MY_VARIABLE: "production_value";
}

// ... your bindings
}
```

```ts
import { Hono } from 'hono'

const app = new Hono<{
Bindings: Env
}>()
```

Refer to [Commands - Wrangler](https://developers.cloudflare.com/workers/wrangler/commands/#types) for more details.

## Using Variables in Middleware

This is the only case for Module Worker mode.
Expand Down