cloudflare-workers

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Cloudflare Workers

Cloudflare Workers

Overview

概述

Cloudflare Workers is a serverless execution environment that runs JavaScript, TypeScript, Python, and Rust code on Cloudflare's global network. Workers execute in milliseconds, scale automatically, and integrate with Cloudflare's storage and compute products through bindings.
Key Benefits:
  • Zero cold starts - Workers run in V8 isolates, not containers
  • Global deployment - Code runs in 300+ cities worldwide
  • Rich ecosystem - Bindings to D1, KV, R2, Durable Objects, Queues, and more
  • Full-stack capable - Build APIs and serve static assets in one project
  • Standards-based - Uses Web APIs (fetch, crypto, streams, WebSockets)
Cloudflare Workers是一个无服务器执行环境,可在Cloudflare全球网络上运行JavaScript、TypeScript、Python和Rust代码。Workers可在毫秒级内执行,自动扩展,并通过bindings与Cloudflare的存储和计算产品集成。
核心优势:
  • 零冷启动 - Workers运行在V8隔离环境中,而非容器
  • 全球部署 - 代码在全球300+城市运行
  • 丰富的生态系统 - 可绑定D1、KV、R2、Durable Objects、Queues等产品
  • 全栈支持 - 在一个项目中构建API并提供静态资源
  • 基于标准 - 使用Web API(fetch、crypto、streams、WebSockets)

When to Use This Skill

适用场景

Use Cloudflare Workers for:
  • APIs and backends - RESTful APIs, GraphQL, tRPC, WebSocket servers
  • Full-stack applications - React, Next.js, Remix, Astro, Vue, Svelte with static assets
  • Edge middleware - Authentication, rate limiting, A/B testing, routing
  • Background processing - Scheduled jobs (cron), queue consumers, webhooks
  • Data transformation - ETL pipelines, real-time data processing
  • AI applications - RAG systems, chatbots, image generation with Workers AI
  • Proxy and gateway - API gateways, content transformation, protocol translation
Cloudflare Workers适用于:
  • API与后端 - RESTful API、GraphQL、tRPC、WebSocket服务器
  • 全栈应用 - 搭配React、Next.js、Remix、Astro、Vue、Svelte的静态资源服务
  • 边缘中间件 - 身份验证、速率限制、A/B测试、路由
  • 后台处理 - 定时任务(cron)、队列消费者、Webhook
  • 数据转换 - ETL管道、实时数据处理
  • AI应用 - RAG系统、聊天机器人、基于Workers AI的图像生成
  • 代理与网关 - API网关、内容转换、协议转换

Quick Start Workflow

快速开始流程

1. Install Wrangler CLI

1. 安装Wrangler CLI

bash
npm install -g wrangler
bash
npm install -g wrangler

Login to Cloudflare

登录Cloudflare

wrangler login
undefined
wrangler login
undefined

2. Create a New Worker

2. 创建新Worker

bash
undefined
bash
undefined

Using C3 (create-cloudflare) - recommended

推荐使用C3(create-cloudflare)

npm create cloudflare@latest my-worker
npm create cloudflare@latest my-worker

Or create manually

或手动创建

wrangler init my-worker cd my-worker
undefined
wrangler init my-worker cd my-worker
undefined

3. Write Your Worker

3. 编写Worker代码

Basic HTTP API (TypeScript):
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 from Workers!" });
    }

    return new Response("Not found", { status: 404 });
  },
};
With environment variables and KV:
typescript
interface Env {
  MY_VAR: string;
  MY_KV: KVNamespace;
}

export default {
  async fetch(request: Request, env: Env): Promise<Response> {
    // Access environment variable
    const greeting = env.MY_VAR;

    // Read from KV
    const value = await env.MY_KV.get("my-key");

    return Response.json({ greeting, value });
  },
};
基础HTTP API(TypeScript):
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 from Workers!" });
    }

    return new Response("Not found", { status: 404 });
  },
};
包含环境变量与KV的示例:
typescript
interface Env {
  MY_VAR: string;
  MY_KV: KVNamespace;
}

export default {
  async fetch(request: Request, env: Env): Promise<Response> {
    // 访问环境变量
    const greeting = env.MY_VAR;

    // 从KV读取数据
    const value = await env.MY_KV.get("my-key");

    return Response.json({ greeting, value });
  },
};

4. Develop Locally

4. 本地开发

bash
undefined
bash
undefined

Start local development server with hot reload

启动带热重载的本地开发服务器

wrangler dev
wrangler dev
undefined
undefined

5. Deploy to Production

5. 部署到生产环境

bash
undefined
bash
undefined

Deploy to workers.dev subdomain

部署到workers.dev子域名

wrangler deploy
wrangler deploy

Deploy to custom domain (configure in wrangler.toml)

部署到自定义域名(需在wrangler.toml中配置)

wrangler deploy
undefined
wrangler deploy
undefined

Core Concepts

核心概念

Workers Runtime

Workers运行时

Workers use the V8 JavaScript engine with Web Standard APIs:
  • Execution model: Isolates (not containers) - instant cold starts
  • CPU time limit: 10ms (Free), 30s (Paid) per request
  • Memory limit: 128 MB per isolate
  • Languages: JavaScript, TypeScript, Python, Rust
  • APIs: fetch, crypto, streams, WebSockets, WebAssembly
Supported APIs:
  • Fetch API (HTTP requests)
  • URL API (URL parsing)
  • Web Crypto (encryption, hashing)
  • Streams API (data streaming)
  • WebSockets (real-time communication)
  • Cache API (edge caching)
  • HTML Rewriter (HTML transformation)
Workers使用V8 JavaScript引擎,支持Web标准API:
  • 执行模型:隔离环境(而非容器)——实现即时冷启动
  • CPU时间限制:免费版10ms/请求,付费版30s/请求
  • 内存限制:每个隔离环境128MB
  • 支持语言:JavaScript、TypeScript、Python、Rust
  • 支持API:fetch、crypto、streams、WebSockets、WebAssembly
支持的API详情:
  • Fetch API(HTTP请求)
  • URL API(URL解析)
  • Web Crypto(加密、哈希)
  • Streams API(数据流)
  • WebSockets(实时通信)
  • Cache API(边缘缓存)
  • HTML Rewriter(HTML转换)

Handlers

处理器

Workers respond to events through handlers:
Fetch Handler (HTTP requests):
typescript
export default {
  async fetch(request: Request, env: Env, ctx: ExecutionContext) {
    return new Response("Hello!");
  },
};
Scheduled Handler (cron jobs):
typescript
export default {
  async scheduled(event: ScheduledEvent, env: Env, ctx: ExecutionContext) {
    // Runs on schedule defined in wrangler.toml
    await env.MY_KV.put("last-run", new Date().toISOString());
  },
};
Queue Handler (message processing):
typescript
export default {
  async queue(batch: MessageBatch<any>, env: Env, ctx: ExecutionContext) {
    for (const message of batch.messages) {
      await processMessage(message.body);
      message.ack();
    }
  },
};
Workers通过处理器响应事件:
Fetch处理器(处理HTTP请求):
typescript
export default {
  async fetch(request: Request, env: Env, ctx: ExecutionContext) {
    return new Response("Hello!");
  },
};
定时处理器(处理cron任务):
typescript
export default {
  async scheduled(event: ScheduledEvent, env: Env, ctx: ExecutionContext) {
    // 按照wrangler.toml中定义的计划运行
    await env.MY_KV.put("last-run", new Date().toISOString());
  },
};
队列处理器(处理消息):
typescript
export default {
  async queue(batch: MessageBatch<any>, env: Env, ctx: ExecutionContext) {
    for (const message of batch.messages) {
      await processMessage(message.body);
      message.ack();
    }
  },
};

Bindings

Bindings

Bindings connect your Worker to Cloudflare resources. Configure in
wrangler.toml
:
KV (Key-Value Storage):
toml
[[kv_namespaces]]
binding = "MY_KV"
id = "your-kv-namespace-id"
typescript
// Usage
await env.MY_KV.put("key", "value");
const value = await env.MY_KV.get("key");
D1 (SQL Database):
toml
[[d1_databases]]
binding = "DB"
database_name = "my-database"
database_id = "your-database-id"
typescript
// Usage
const result = await env.DB.prepare(
  "SELECT * FROM users WHERE id = ?"
).bind(userId).all();
R2 (Object Storage):
toml
[[r2_buckets]]
binding = "MY_BUCKET"
bucket_name = "my-bucket"
typescript
// Usage
await env.MY_BUCKET.put("file.txt", "contents");
const object = await env.MY_BUCKET.get("file.txt");
const text = await object?.text();
Environment Variables:
toml
[vars]
API_KEY = "development-key"  # pragma: allowlist secret
Secrets (sensitive data):
bash
undefined
Bindings用于将Worker与Cloudflare资源连接,需在
wrangler.toml
中配置:
KV(键值存储):
toml
[[kv_namespaces]]
binding = "MY_KV"
id = "your-kv-namespace-id"
typescript
// 使用示例
await env.MY_KV.put("key", "value");
const value = await env.MY_KV.get("key");
D1(SQL数据库):
toml
[[d1_databases]]
binding = "DB"
database_name = "my-database"
database_id = "your-database-id"
typescript
// 使用示例
const result = await env.DB.prepare(
  "SELECT * FROM users WHERE id = ?"
).bind(userId).all();
R2(对象存储):
toml
[[r2_buckets]]
binding = "MY_BUCKET"
bucket_name = "my-bucket"
typescript
// 使用示例
await env.MY_BUCKET.put("file.txt", "contents");
const object = await env.MY_BUCKET.get("file.txt");
const text = await object?.text();
环境变量:
toml
[vars]
API_KEY = "development-key"  # pragma: allowlist secret
密钥(敏感数据):
bash
undefined

Set via CLI (not in wrangler.toml)

通过CLI设置(不要写在wrangler.toml中)

wrangler secret put API_KEY
undefined
wrangler secret put API_KEY
undefined

Context (ctx)

上下文(ctx)

The
ctx
parameter provides control over request lifecycle:
typescript
export default {
  async fetch(request: Request, env: Env, ctx: ExecutionContext) {
    // Run tasks after response is sent
    ctx.waitUntil(
      env.MY_KV.put("request-count", String(Date.now()))
    );

    // Pass through to origin on exception
    ctx.passThroughOnException();

    return new Response("OK");
  },
};
ctx
参数用于控制请求生命周期:
typescript
export default {
  async fetch(request: Request, env: Env, ctx: ExecutionContext) {
    // 在响应发送后执行任务
    ctx.waitUntil(
      env.MY_KV.put("request-count", String(Date.now()))
    );

    // 发生异常时转发到源站
    ctx.passThroughOnException();

    return new Response("OK");
  },
};

Rapid Development Patterns

快速开发模式

Wrangler Configuration

Wrangler配置

Essential
wrangler.toml
:
toml
name = "my-worker"
main = "src/index.ts"
compatibility_date = "2025-01-01"
基础
wrangler.toml
配置:
toml
name = "my-worker"
main = "src/index.ts"
compatibility_date = "2025-01-01"

Custom domain

自定义域名

routes = [ { pattern = "api.example.com/*", zone_name = "example.com" } ]
routes = [ { pattern = "api.example.com/*", zone_name = "example.com" } ]

Or workers.dev subdomain

或使用workers.dev子域名

workers_dev = true
workers_dev = true

Environment variables

环境变量

[vars] ENVIRONMENT = "production"
[vars] ENVIRONMENT = "production"

Bindings

Bindings配置

[[kv_namespaces]] binding = "CACHE" id = "your-kv-id"
[[d1_databases]] binding = "DB" database_name = "production-db" database_id = "your-db-id"
[[r2_buckets]] binding = "ASSETS" bucket_name = "my-assets"
[[kv_namespaces]] binding = "CACHE" id = "your-kv-id"
[[d1_databases]] binding = "DB" database_name = "production-db" database_id = "your-db-id"
[[r2_buckets]] binding = "ASSETS" bucket_name = "my-assets"

Cron triggers

Cron触发器

[triggers] crons = ["0 0 * * *"] # Daily at midnight
undefined
[triggers] crons = ["0 0 * * *"] # 每日午夜执行
undefined

Environment Management

环境管理

Use environments for staging/production:
toml
[env.staging]
vars = { ENVIRONMENT = "staging" }

[env.staging.d1_databases]
binding = "DB"
database_name = "staging-db"
database_id = "staging-db-id"

[env.production]
vars = { ENVIRONMENT = "production" }

[env.production.d1_databases]
binding = "DB"
database_name = "production-db"
database_id = "production-db-id"
bash
undefined
使用环境区分预发布/生产环境:
toml
[env.staging]
vars = { ENVIRONMENT = "staging" }

[env.staging.d1_databases]
binding = "DB"
database_name = "staging-db"
database_id = "staging-db-id"

[env.production]
vars = { ENVIRONMENT = "production" }

[env.production.d1_databases]
binding = "DB"
database_name = "production-db"
database_id = "production-db-id"
bash
undefined

Deploy to staging

部署到预发布环境

wrangler deploy --env staging
wrangler deploy --env staging

Deploy to production

部署到生产环境

wrangler deploy --env production
undefined
wrangler deploy --env production
undefined

Common Patterns

常见模式

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

      if (url.pathname === "/api/users" && request.method === "GET") {
        const users = await env.DB.prepare("SELECT * FROM users").all();
        return Response.json(users.results);
      }

      if (url.pathname === "/api/users" && request.method === "POST") {
        const body = await request.json();
        await env.DB.prepare(
          "INSERT INTO users (name, email) VALUES (?, ?)"
        ).bind(body.name, body.email).run();
        return Response.json({ success: true }, { status: 201 });
      }

      return Response.json({ error: "Not found" }, { status: 404 });
    } catch (error) {
      return Response.json(
        { error: error.message },
        { status: 500 }
      );
    }
  },
};
Authentication Middleware:
typescript
async function authenticate(request: Request, env: Env): Promise<string | null> {
  const authHeader = request.headers.get("Authorization");
  if (!authHeader?.startsWith("Bearer ")) {
    return null;
  }

  const token = authHeader.substring(7);
  const userId = await env.SESSIONS.get(token);
  return userId;
}

export default {
  async fetch(request: Request, env: Env): Promise<Response> {
    const userId = await authenticate(request, env);

    if (!userId) {
      return Response.json({ error: "Unauthorized" }, { status: 401 });
    }

    // Proceed with authenticated request
    return Response.json({ userId });
  },
};
CORS Headers:
typescript
const corsHeaders = {
  "Access-Control-Allow-Origin": "*",
  "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS",
  "Access-Control-Allow-Headers": "Content-Type, Authorization",
};

export default {
  async fetch(request: Request): Promise<Response> {
    if (request.method === "OPTIONS") {
      return new Response(null, { headers: corsHeaders });
    }

    const response = await handleRequest(request);

    // Add CORS headers to response
    Object.entries(corsHeaders).forEach(([key, value]) => {
      response.headers.set(key, value);
    });

    return response;
  },
};
带错误处理的JSON API:
typescript
export default {
  async fetch(request: Request, env: Env): Promise<Response> {
    try {
      const url = new URL(request.url);

      if (url.pathname === "/api/users" && request.method === "GET") {
        const users = await env.DB.prepare("SELECT * FROM users").all();
        return Response.json(users.results);
      }

      if (url.pathname === "/api/users" && request.method === "POST") {
        const body = await request.json();
        await env.DB.prepare(
          "INSERT INTO users (name, email) VALUES (?, ?)"
        ).bind(body.name, body.email).run();
        return Response.json({ success: true }, { status: 201 });
      }

      return Response.json({ error: "Not found" }, { status: 404 });
    } catch (error) {
      return Response.json(
        { error: error.message },
        { status: 500 }
      );
    }
  },
};
身份验证中间件:
typescript
async function authenticate(request: Request, env: Env): Promise<string | null> {
  const authHeader = request.headers.get("Authorization");
  if (!authHeader?.startsWith("Bearer ")) {
    return null;
  }

  const token = authHeader.substring(7);
  const userId = await env.SESSIONS.get(token);
  return userId;
}

export default {
  async fetch(request: Request, env: Env): Promise<Response> {
    const userId = await authenticate(request, env);

    if (!userId) {
      return Response.json({ error: "Unauthorized" }, { status: 401 });
    }

    // 处理已认证的请求
    return Response.json({ userId });
  },
};
CORS头配置:
typescript
const corsHeaders = {
  "Access-Control-Allow-Origin": "*",
  "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS",
  "Access-Control-Allow-Headers": "Content-Type, Authorization",
};

export default {
  async fetch(request: Request): Promise<Response> {
    if (request.method === "OPTIONS") {
      return new Response(null, { headers: corsHeaders });
    }

    const response = await handleRequest(request);

    // 为响应添加CORS头
    Object.entries(corsHeaders).forEach(([key, value]) => {
      response.headers.set(key, value);
    });

    return response;
  },
};

Static Assets (Full-Stack Apps)

静态资源(全栈应用)

Serve static files alongside your Worker code:
toml
[assets]
directory = "./public"
binding = "ASSETS"
typescript
import { getAssetFromKV } from "@cloudflare/kv-asset-handler";

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

    // API routes
    if (url.pathname.startsWith("/api/")) {
      return handleAPI(request, env);
    }

    // Serve static assets
    try {
      return await getAssetFromKV(
        { request, waitUntil: () => {} },
        { ASSET_NAMESPACE: env.ASSETS }
      );
    } catch {
      return new Response("Not found", { status: 404 });
    }
  },
};
在Worker代码中同时提供静态文件服务:
toml
[assets]
directory = "./public"
binding = "ASSETS"
typescript
import { getAssetFromKV } from "@cloudflare/kv-asset-handler";

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

    // API路由处理
    if (url.pathname.startsWith("/api/")) {
      return handleAPI(request, env);
    }

    // 提供静态资源
    try {
      return await getAssetFromKV(
        { request, waitUntil: () => {} },
        { ASSET_NAMESPACE: env.ASSETS }
      );
    } catch {
      return new Response("Not found", { status: 404 });
    }
  },
};

Testing

测试

Using Vitest:
typescript
import { env, createExecutionContext } from "cloudflare:test";
import { describe, it, expect } from "vitest";
import worker from "./index";

describe("Worker", () => {
  it("responds with JSON", async () => {
    const request = new Request("http://example.com/api/hello");
    const ctx = createExecutionContext();
    const response = await worker.fetch(request, env, ctx);

    expect(response.status).toBe(200);
    expect(await response.json()).toEqual({ message: "Hello!" });
  });
});
使用Vitest进行测试:
typescript
import { env, createExecutionContext } from "cloudflare:test";
import { describe, it, expect } from "vitest";
import worker from "./index";

describe("Worker", () => {
  it("responds with JSON", async () => {
    const request = new Request("http://example.com/api/hello");
    const ctx = createExecutionContext();
    const response = await worker.fetch(request, env, ctx);

    expect(response.status).toBe(200);
    expect(await response.json()).toEqual({ message: "Hello!" });
  });
});

Framework Integration

框架集成

Workers supports major frameworks with adapters:
  • Next.js - Full App Router and Pages Router support
  • Remix / React Router - Native Cloudflare adapter
  • Astro - Server-side rendering on Workers
  • SvelteKit - Cloudflare adapter available
  • Hono - Lightweight web framework built for Workers
  • tRPC - Type-safe APIs with full Workers support
Example with Hono:
typescript
import { Hono } from "hono";

const app = new Hono();

app.get("/", (c) => c.text("Hello!"));
app.get("/api/users/:id", async (c) => {
  const id = c.req.param("id");
  const user = await c.env.DB.prepare(
    "SELECT * FROM users WHERE id = ?"
  ).bind(id).first();
  return c.json(user);
});

export default app;
Workers通过适配器支持主流框架:
  • Next.js - 全面支持App Router与Pages Router
  • Remix / React Router - 原生Cloudflare适配器
  • Astro - 在Workers上实现服务端渲染
  • SvelteKit - 提供Cloudflare适配器
  • Hono - 为Workers打造的轻量级Web框架
  • tRPC - 完全支持Workers的类型安全API
Hono框架示例:
typescript
import { Hono } from "hono";

const app = new Hono();

app.get("/", (c) => c.text("Hello!"));
app.get("/api/users/:id", async (c) => {
  const id = c.req.param("id");
  const user = await c.env.DB.prepare(
    "SELECT * FROM users WHERE id = ?"
  ).bind(id).first();
  return c.json(user);
});

export default app;

Advanced Topics

进阶主题

For detailed information on advanced features, see the reference files:
  • Complete Bindings Guide:
    references/bindings-complete-guide.md
    - Deep dive into all binding types (Durable Objects, Queues, Vectorize, AI, Hyperdrive, etc.)
  • Deployment & CI/CD:
    references/wrangler-and-deployment.md
    - Wrangler commands, GitHub Actions, GitLab CI/CD, gradual rollouts, versions
  • Development Best Practices:
    references/development-patterns.md
    - Testing strategies, debugging, error handling, performance optimization
  • Advanced Features:
    references/advanced-features.md
    - Workers for Platforms, Smart Placement, WebSockets, streaming, custom domains
  • Observability:
    references/observability.md
    - Logging (tail, Logpush, Workers Logs), metrics, traces, debugging
如需了解高级功能的详细信息,请参考以下文档:
  • 完整Bindings指南
    references/bindings-complete-guide.md
    - 深入讲解所有Bindings类型(Durable Objects、Queues、Vectorize、AI、Hyperdrive等)
  • 部署与CI/CD
    references/wrangler-and-deployment.md
    - Wrangler命令、GitHub Actions、GitLab CI/CD、灰度发布、版本管理
  • 开发最佳实践
    references/development-patterns.md
    - 测试策略、调试、错误处理、性能优化
  • 高级功能
    references/advanced-features.md
    - Workers for Platforms、智能部署、WebSockets、流处理、自定义域名
  • 可观测性
    references/observability.md
    - 日志(tail、Logpush、Workers Logs)、指标、追踪、调试

Resources

资源