cloudflare-workers

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Cloudflare Workers

Cloudflare Workers

Serverless platform for building applications across Cloudflare's global network.
一款可在Cloudflare全球网络上构建应用的无服务器平台。

Quick Navigation

快速导航

  • Runtime & handlers →
    references/runtime.md
  • Bindings overview →
    references/bindings.md
  • Wrangler configuration →
    references/wrangler.md
  • Local development →
    references/local-dev.md
  • Static assets →
    references/assets.md
  • Testing →
    references/testing.md
  • 运行时与处理器 →
    references/runtime.md
  • 绑定概览 →
    references/bindings.md
  • Wrangler配置 →
    references/wrangler.md
  • 本地开发 →
    references/local-dev.md
  • 静态资源 →
    references/assets.md
  • 测试 →
    references/testing.md

When to Use

适用场景

  • Building serverless APIs or full-stack applications
  • Running edge functions with global distribution
  • Connecting to Cloudflare storage (KV, R2, D1, Durable Objects)
  • Running AI inference with Workers AI
  • Configuring Wrangler CLI and wrangler.toml
  • Setting up local development with Miniflare
  • Testing Workers with Vitest
  • 构建无服务器API或全栈应用
  • 运行具备全球分发能力的边缘函数
  • 连接Cloudflare存储服务(KV、R2、D1、Durable Objects)
  • 通过Workers AI运行AI推理
  • 配置Wrangler CLI与wrangler.toml
  • 基于Miniflare搭建本地开发环境
  • 使用Vitest测试Workers

Module Worker (Recommended Syntax)

模块Worker(推荐语法)

typescript
export default {
  async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
    return new Response("Hello, World!");
  },
} satisfies ExportedHandler<Env>;
typescript
export default {
  async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
    return new Response("Hello, World!");
  },
} satisfies ExportedHandler<Env>;

Handler Types

处理器类型

HandlerTriggerUse Case
fetch
HTTP requestAPIs, websites
scheduled
Cron triggerBackground jobs
queue
Queue messageAsync processing
email
Email receivedEmail routing
处理器触发方式适用场景
fetch
HTTP请求API、网站
scheduled
Cron触发器后台任务
queue
队列消息异步处理
email
收到邮件邮件路由

Bindings Overview

绑定概览

Access Cloudflare resources via
env
object.
BindingTypeLocal Dev
KV
KVNamespace
✅ Simulated
R2
R2Bucket
✅ Simulated
D1
D1Database
✅ Simulated
Durable Objects
DurableObjectNamespace
✅ Simulated
Queues
Queue
✅ Simulated
Workers AI
Ai
❌ Remote only
Vectorize
VectorizeIndex
❌ Remote only
Browser Rendering
Fetcher
❌ Remote only
Hyperdrive
Hyperdrive
❌ Remote only
Static Assets
Fetcher
✅ Simulated
Service Binding
Fetcher
✅ Simulated
通过
env
对象访问Cloudflare资源。
绑定类型类型本地开发支持
KV
KVNamespace
✅ 可模拟
R2
R2Bucket
✅ 可模拟
D1
D1Database
✅ 可模拟
Durable Objects
DurableObjectNamespace
✅ 可模拟
Queues
Queue
✅ 可模拟
Workers AI
Ai
❌ 仅支持远程
Vectorize
VectorizeIndex
❌ 仅支持远程
Browser Rendering
Fetcher
❌ 仅支持远程
Hyperdrive
Hyperdrive
❌ 仅支持远程
静态资源
Fetcher
✅ 可模拟
服务绑定
Fetcher
✅ 可模拟

Minimal Configuration

最简配置

jsonc
// wrangler.jsonc
{
  "$schema": "./node_modules/wrangler/config-schema.json",
  "name": "my-worker",
  "main": "src/index.ts",
  "compatibility_date": "2025-03-07",
  "compatibility_flags": ["nodejs_compat"],
  "observability": {
    "enabled": true,
    "head_sampling_rate": 1
  }
}
jsonc
// wrangler.jsonc
{
  "$schema": "./node_modules/wrangler/config-schema.json",
  "name": "my-worker",
  "main": "src/index.ts",
  "compatibility_date": "2025-03-07",
  "compatibility_flags": ["nodejs_compat"],
  "observability": {
    "enabled": true,
    "head_sampling_rate": 1
  }
}

Essential Commands

常用命令

bash
undefined
bash
undefined

Development

开发

npx wrangler dev # Local dev (Miniflare) npx wrangler dev --remote # Remote dev (code on Cloudflare)
npx wrangler dev # 本地开发(基于Miniflare) npx wrangler dev --remote # 远程开发(代码部署在Cloudflare)

Deployment

部署

npx wrangler deploy # Deploy to production npx wrangler versions upload # Upload without deploying npx wrangler versions deploy # Promote version
npx wrangler deploy # 部署到生产环境 npx wrangler versions upload # 上传版本但不部署 npx wrangler versions deploy # 推广版本至生产

Secrets

密钥管理

npx wrangler secret put KEY # Add secret npx wrangler secret list # List secrets
npx wrangler secret put KEY # 添加密钥 npx wrangler secret list # 列出所有密钥

Types

类型生成

npx wrangler types # Generate TypeScript types
undefined
npx wrangler types # 生成TypeScript类型定义
undefined

Compatibility Settings

兼容性设置

toml
undefined
toml
undefined

wrangler.toml

wrangler.toml

compatibility_date = "2025-03-07" compatibility_flags = ["nodejs_compat"]

Key flags:

- `nodejs_compat` — Enable Node.js APIs
- `nodejs_compat_v2` — Improved process implementation
compatibility_date = "2025-03-07" compatibility_flags = ["nodejs_compat"]

关键标志:

- `nodejs_compat` — 启用Node.js API
- `nodejs_compat_v2` — 改进的进程实现

Quick Recipes

快速示例

Fetch Handler with Routing

带路由的Fetch处理器

typescript
export default {
  async fetch(request: Request, env: Env): Promise<Response> {
    const url = new URL(request.url);

    if (url.pathname === "/api/hello") {
      return Response.json({ message: "Hello!" });
    }

    if (url.pathname.startsWith("/static/")) {
      return env.ASSETS.fetch(request);
    }

    return new Response("Not Found", { status: 404 });
  },
};
typescript
export default {
  async fetch(request: Request, env: Env): Promise<Response> {
    const url = new URL(request.url);

    if (url.pathname === "/api/hello") {
      return Response.json({ message: "Hello!" });
    }

    if (url.pathname.startsWith("/static/")) {
      return env.ASSETS.fetch(request);
    }

    return new Response("Not Found", { status: 404 });
  },
};

Scheduled Handler (Cron)

Scheduled处理器(Cron)

typescript
export default {
  async scheduled(controller: ScheduledController, env: Env, ctx: ExecutionContext) {
    ctx.waitUntil(doBackgroundWork(env));
  },
};
toml
undefined
typescript
export default {
  async scheduled(controller: ScheduledController, env: Env, ctx: ExecutionContext) {
    ctx.waitUntil(doBackgroundWork(env));
  },
};
toml
undefined

wrangler.toml

wrangler.toml

[triggers] crons = ["0 * * * *"] # Every hour
undefined
[triggers] crons = ["0 * * * *"] # 每小时执行一次
undefined

Queue Consumer

队列消费者

typescript
export default {
  async queue(batch: MessageBatch, env: Env, ctx: ExecutionContext) {
    for (const message of batch.messages) {
      console.log(message.body);
      message.ack();
    }
  },
};
typescript
export default {
  async queue(batch: MessageBatch, env: Env, ctx: ExecutionContext) {
    for (const message of batch.messages) {
      console.log(message.body);
      message.ack();
    }
  },
};

Critical Prohibitions

重要禁忌

  • Do NOT store secrets in
    wrangler.toml
    — use
    wrangler secret put
  • Do NOT use
    remote: true
    for Durable Objects or Workflows — unsupported
  • Do NOT expect Workers AI to work locally — always requires remote connection
  • Do NOT omit
    compatibility_date
    — defaults to oldest date (2021-11-02)
  • Do NOT use Service Worker syntax for new projects — use ES Modules
  • Do NOT mix Service Worker and Module syntax in same project
  • 请勿在
    wrangler.toml
    中存储密钥 — 使用
    wrangler secret put
    命令
  • 请勿对Durable Objects或Workflows设置
    remote: true
    — 该配置不被支持
  • 请勿期望Workers AI在本地运行 — 始终需要远程连接
  • 请勿省略
    compatibility_date
    — 默认值为最早版本日期(2021-11-02)
  • 新项目请勿使用Service Worker语法 — 请使用ES Modules
  • 请勿在同一项目中混合使用Service Worker与Module语法

Common Gotchas

常见问题与解决方法

IssueSolution
Local bindings emptyAdd
--local
flag to Wrangler KV/R2/D1 commands
AI not working locallyUse
remote: true
in ai binding config
Node APIs unavailableAdd
nodejs_compat
to compatibility_flags
First deploy failsUse
wrangler deploy
, not
versions upload
for first deploy
问题解决方案
本地绑定为空在Wrangler的KV/R2/D1命令中添加
--local
标志
AI在本地无法工作在AI绑定配置中设置
remote: true
Node API无法使用在compatibility_flags中添加
nodejs_compat
首次部署失败首次部署请使用
wrangler deploy
,而非
versions upload

Related Skills

相关技能

  • cloudflare-pages
    — Full-stack hosting with Git deployment
  • cloudflare-d1
    — D1 database operations
  • cloudflare-r2
    — R2 object storage
  • cloudflare-kv
    — KV namespace operations
  • cloudflare-durable-objects
    — Stateful coordination
  • cloudflare-pages
    — 支持Git部署的全栈托管服务
  • cloudflare-d1
    — D1数据库操作
  • cloudflare-r2
    — R2对象存储
  • cloudflare-kv
    — KV命名空间操作
  • cloudflare-durable-objects
    — 有状态协调服务