Skip to content

Cloudflare Workers

Cloudflare Workers 是 Cloudflare CDN 上的一个 JavaScript 边缘运行时。

你可以在本地开发应用,并使用几个命令通过 Wrangler 发布它。Wrangler 包含转译器,因此我们可以使用 TypeScript 编写代码。

🌐 You can develop the application locally and publish it with a few commands using Wrangler. Wrangler includes transcompiler, so we can write the code with TypeScript.

让我们用 Hono 为 Cloudflare Workers 制作你的第一个应用。

🌐 Let’s make your first application for Cloudflare Workers with Hono.

1. 设置

🌐 1. Setup

Cloudflare Workers 的入门模板已可用。使用 "create-hono" 命令开始你的项目。此示例请选择 cloudflare-workers 模板。

🌐 A starter for Cloudflare Workers is available. Start your project with "create-hono" command. Select cloudflare-workers template for this example.

sh
npm create hono@latest my-app
sh
yarn create hono my-app
sh
pnpm create hono my-app
sh
bun create hono@latest my-app
sh
deno init --npm hono my-app

移动到 my-app 并安装依赖。

🌐 Move to my-app and install the dependencies.

sh
cd my-app
npm i
sh
cd my-app
yarn
sh
cd my-app
pnpm i
sh
cd my-app
bun i

2. 你好,世界

🌐 2. Hello World

像下面这样编辑 src/index.ts

🌐 Edit src/index.ts like below.

ts
import { Hono } from 'hono'
const app = new Hono()

app.get('/', (c) => c.text('Hello Cloudflare Workers!'))

export default app

3. 跑

🌐 3. Run

在本地运行开发服务器。然后,在你的网页浏览器中访问 http://localhost:8787

🌐 Run the development server locally. Then, access http://localhost:8787 in your web browser.

sh
npm run dev
sh
yarn dev
sh
pnpm dev
sh
bun run dev

更改端口编号

🌐 Change port number

如果你需要更改端口号,可以按照此处的说明更新 wrangler.toml / wrangler.json / wrangler.jsonc 文件: Wrangler 配置

🌐 If you need to change the port number you can follow the instructions here to update wrangler.toml / wrangler.json / wrangler.jsonc files: Wrangler Configuration

或者,你可以按照这里的说明设置 CLI 选项: Wrangler CLI

🌐 Or, you can follow the instructions here to set CLI options: Wrangler CLI

4. 部署

🌐 4. Deploy

如果你有一个 Cloudflare 账户,你可以部署到 Cloudflare。在 package.json 中,$npm_execpath 需要更改为你选择的包管理器。

🌐 If you have a Cloudflare account, you can deploy to Cloudflare. In package.json, $npm_execpath needs to be changed to your package manager of choice.

sh
npm run deploy
sh
yarn deploy
sh
pnpm run deploy
sh
bun run deploy

就这些!

🌐 That's all!

将 Hono 与其他事件处理程序一起使用

🌐 Using Hono with other event handlers

你可以在_模块工作者模式_下将 Hono 与其他事件处理程序(例如 scheduled)集成。

🌐 You can integrate Hono with other event handlers (such as scheduled) in Module Worker mode.

为此,将 app.fetch 导出为模块的 fetch 处理器,然后根据需要实现其他处理器:

🌐 To do this, export app.fetch as the module's fetch handler, and then implement other handlers as needed:

ts
const app = new Hono()

export default {
  fetch: app.fetch,
  scheduled: async (batch, env) => {},
}

提供静态文件

🌐 Serve static files

如果你想提供静态文件,你可以使用 Cloudflare Workers 的 静态资源功能。在 wrangler.jsonc 中指定文件的目录:

🌐 If you want to serve static files, you can use the Static Assets feature of Cloudflare Workers. Specify the directory for the files in wrangler.jsonc:

jsonc
"assets": { "directory": "public" }

然后创建 public 目录并将文件放在那里。例如,./public/static/hello.txt 将作为 /static/hello.txt 提供。

🌐 Then create the public directory and place the files there. For instance, ./public/static/hello.txt will be served as /static/hello.txt.

.
├── package.json
├── public
│   ├── favicon.ico
│   └── static
│       └── hello.txt
├── src
│   └── index.ts
└── wrangler.jsonc

类型

🌐 Types

如果你想拥有工人类型,你必须安装 @cloudflare/workers-types

🌐 You have to install @cloudflare/workers-types if you want to have workers types.

sh
npm i --save-dev @cloudflare/workers-types
sh
yarn add -D @cloudflare/workers-types
sh
pnpm add -D @cloudflare/workers-types
sh
bun add --dev @cloudflare/workers-types

测试

🌐 Testing

用于测试,我们建议使用 @cloudflare/vitest-pool-workers。 请参考 示例 进行设置。

🌐 For testing, we recommend using @cloudflare/vitest-pool-workers. Refer to examples for setting it up.

如果有以下应用。

🌐 If there is the application below.

ts
import { Hono } from 'hono'

const app = new Hono()
app.get('/', (c) => c.text('Please test me!'))

我们可以用这段代码测试它是否返回“200 OK”响应。

🌐 We can test if it returns "200 OK" Response with this code.

ts
describe('Test the application', () => {
  it('Should return 200 response', async () => {
    const res = await app.request('http://localhost/')
    expect(res.status).toBe(200)
  })
})

绑定

🌐 Bindings

在 Cloudflare Workers 中,我们可以绑定环境变量、KV 命名空间、R2 存储桶或 Durable Object。你可以在 c.env 中访问它们。如果你将绑定的“类型定义”作为泛型传递给 Hono,它将具有类型。

🌐 In the Cloudflare Workers, we can bind the environment values, KV namespace, R2 bucket, or Durable Object. You can access them in c.env. It will have the types if you pass the "type definition" for the bindings to the Hono as generics.

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

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

// Access to environment values
app.put('/upload/:key', async (c, next) => {
  const key = c.req.param('key')
  await c.env.MY_BUCKET.put(key, c.req.body)
  return c.text(`Put ${key} successfully!`)
})

自动生成绑定类型

🌐 Generating Bindings Types Automatically

与其手动定义绑定类型,你可以使用 wrangler types 命令从你的 wrangler.toml 自动生成它们。使用 --env-interface 标志可以避免与 Hono 内置的 Env 类型发生命名冲突:

🌐 Instead of defining bindings types by hand, you can auto-generate them from your wrangler.toml using the wrangler types command. Use the --env-interface flag to avoid a naming collision with Hono's built-in Env type:

sh
wrangler types --env-interface CloudflareBindings

这会生成一个带有你指定接口名称的 worker-configuration.d.ts 文件。然后将其传递给 Hono:

🌐 This generates a worker-configuration.d.ts file with the interface name you specify. Then pass it to Hono:

ts
const app = new Hono<{ Bindings: CloudflareBindings }>()

app.put('/upload/:key', async (c, next) => {
  const key = c.req.param('key')
  await c.env.MY_BUCKET.put(key, c.req.body)
  return c.text(`Put ${key} successfully!`)
})

在中间件中使用变量

🌐 Using Variables in Middleware

这是模块工作者模式的唯一情况。如果你想在中间件中使用变量或秘密变量,例如在基本身份验证中间件中的“username”或“password”,你需要像下面这样写。

🌐 This is the only case for Module Worker mode. If you want to use Variables or Secret Variables in Middleware, for example, "username" or "password" in Basic Authentication Middleware, you need to write like the following.

ts
import { basicAuth } from 'hono/basic-auth'

type Bindings = {
  USERNAME: string
  PASSWORD: string
}

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

//...

app.use('/auth/*', async (c, next) => {
  const auth = basicAuth({
    username: c.env.USERNAME,
    password: c.env.PASSWORD,
  })
  return auth(c, next)
})

同样适用于 Bearer 身份验证中间件、JWT 身份验证或其他。

🌐 The same is applied to Bearer Authentication Middleware, JWT Authentication, or others.

从 GitHub Actions 部署

🌐 Deploy from GitHub Actions

在通过 CI 部署代码到 Cloudflare 之前,你需要一个 Cloudflare 令牌。你可以从 用户 API 令牌 管理它。

🌐 Before deploying code to Cloudflare via CI, you need a Cloudflare token. You can manage it from User API Tokens.

如果这是新创建的令牌,请选择 编辑 Cloudflare Workers 模板。如果你已经有另一个令牌,请确保该令牌具有相应的权限。

🌐 If it's a newly created token, select the Edit Cloudflare Workers template. If you already have another token, make sure the token has the corresponding permissions.

然后转到你的 GitHub 仓库设置面板:Settings->Secrets and variables->Actions->Repository secrets,并添加一个名称为 CLOUDFLARE_API_TOKEN 的新密钥。

🌐 then go to your GitHub repository settings dashboard: Settings->Secrets and variables->Actions->Repository secrets, and add a new secret with the name CLOUDFLARE_API_TOKEN.

然后在你的 Hono 项目根文件夹中创建 .github/workflows/deploy.yml,粘贴以下代码:

🌐 then create .github/workflows/deploy.yml in your Hono project root folder, paste the following code:

yml
name: Deploy

on:
  push:
    branches:
      - main

jobs:
  deploy:
    runs-on: ubuntu-latest
    name: Deploy
    steps:
      - uses: actions/checkout@v4
      - name: Deploy
        uses: cloudflare/wrangler-action@v3
        with:
          apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}

然后编辑 wrangler.jsonc,并在 compatibility_date 行之后添加此代码。

🌐 then edit wrangler.jsonc, and add this code after the compatibility_date line.

jsonc
"main": "src/index.ts",
"minify": true

一切准备就绪!现在推送代码并享受它吧。

🌐 Everything is ready! Now push the code and enjoy it.

本地开发时加载环境

🌐 Load env when local development

要为本地开发配置环境变量,请在项目的根目录下创建一个 .dev.vars 文件或 .env 文件。 这些文件应使用 dotenv 语法进行格式化。例如:

🌐 To configure the environment variables for local development, create a .dev.vars file or a .env file in the root directory of the project. These files should be formatted using the dotenv syntax. For example:

SECRET_KEY=value
API_TOKEN=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9

有关本节的更多信息,你可以在 Cloudflare 文档中找到: https://developers.cloudflare.com/workers/wrangler/configuration/#secrets

然后我们使用 c.env.* 在代码中获取环境变量。

🌐 Then we use the c.env.* to get the environment variables in our code.

INFO

默认情况下,process.env 在 Cloudflare Workers 中不可用,因此建议从 c.env 获取环境变量。如果你想使用它,需要启用 nodejs_compat_populate_process_env 标志。你也可以从 cloudflare:workers 导入 env。详情请参阅 如何在 Cloudflare 文档中访问 env

ts
type Bindings = {
  SECRET_KEY: string
}

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

app.get('/env', (c) => {
  const SECRET_KEY = c.env.SECRET_KEY
  return c.text(SECRET_KEY)
})

在将项目部署到 Cloudflare 之前,请记住在 Cloudflare Workers 项目的配置中设置环境变量/密钥。

🌐 Before you deploy your project to Cloudflare, remember to set the environment variable/secrets in the Cloudflare Workers project's configuration.

有关本节的更多内容,你可以在 Cloudflare 文档中找到: https://developers.cloudflare.com/workers/configuration/environment-variables/#add-environment-variables-via-the-dashboard

Hono 中文网 - 粤ICP备13048890号