mcpField
C
cloudflare-workers

cloudflare-workers

github.com/tenequm云与 DevOps4082 次安装1 周前更新
代码仓库

关于 cloudflare-workers

面向开发者的 Cloudflare Workers 技能,介绍如何在 Cloudflare 网络上构建和部署服务端应用。涵盖存储绑定、框架集成、测试及 MCP 服务托管。

主要功能

  1. 01构建 API 与全栈应用
  2. 02使用存储和计算绑定
  3. 03处理定时任务与队列
  4. 04集成 Web 框架
  5. 05本地开发与测试
  6. 06部署远程 MCP 服务

适用场景

  1. 01构建 REST 或 GraphQL 后端
  2. 02在边缘运行身份验证与路由
  3. 03处理后台任务和 Webhook
  4. 04托管 MCP 服务

MCP 相关

该技能说明如何在 Cloudflare Workers 上托管远程 MCP 服务。它不描述面向 MCP 客户端的工具或资源接口。

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/tenequm/skills --skill cloudflare-workers

安装后在 Claude Code 中输入/cloudflare-workers确认已加载。

详细介绍

Cloudflare Workers

概述

Cloudflare Workers 是一种无服务器执行环境,可在 Cloudflare 的全球网络上运行 JavaScript、TypeScript、Python 和 Rust 代码。Workers 可在毫秒内执行、自动扩展,并通过绑定与 Cloudflare 的存储和计算产品集成。

主要优势:

  • 零冷启动 - Workers 在 V8 隔离区中运行,而非容器
  • 全球部署 - 代码在全球 300 多个城市运行
  • 丰富的生态系统 - 通过绑定连接 D1、KV、R2、Durable Objects、Queues、Containers、Workflows 等
  • 支持全栈开发 - 在一个项目中构建 API 并提供静态资源
  • 基于标准 - 使用 Web API(fetch、crypto、streams、WebSockets)

何时使用此技能

在以下场景中使用 Cloudflare Workers:

  • API 和后端 - RESTful API、GraphQL、tRPC、WebSocket 服务
  • 全栈应用 - 使用静态资源构建 React、Next.js、Remix、Astro、Vue、Svelte 应用
  • 边缘中间件 - 身份验证、速率限制、A/B 测试、路由
  • 后台处理 - 定时任务(cron)、队列消费者、webhook
  • 数据转换 - ETL 流水线、实时数据处理
  • AI 应用 - 使用 Workers AI 构建 RAG 系统、聊天机器人、图像生成应用
  • 持久化工作流 - 使用 Workflows 执行具有自动重试功能的多步骤长时间运行任务
  • 容器工作负载 - 使用 Containers 在 Workers 旁运行 Docker 容器
  • MCP 服务 - 托管远程 Model Context Protocol 服务
  • 代理和网关 - API 网关、内容转换、协议转换

快速入门工作流

1. 安装 Wrangler CLI
npm install -g wrangler

# Login to Cloudflare
wrangler login
2. 创建新的 Worker
# Using C3 (create-cloudflare) - recommended
npm create cloudflare@latest my-worker

# Or create manually
wrangler init my-worker
cd my-worker
3. 编写 Worker

基本 HTTP API(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:

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 });
  },
};
4. 本地开发
# Start local development server with hot reload
wrangler dev

# Access at http://localhost:8787
5. 部署到生产环境
# Deploy to workers.dev subdomain
wrangler deploy

# Deploy to custom domain (configure in wrangler.toml)
wrangler deploy

核心概念

Workers 运行时

Workers 使用 V8 JavaScript 引擎和 Web 标准 API:

  • 执行模型:隔离区(而非容器)——即时冷启动
  • CPU 时间限制:每个请求 10ms(免费版)、30s(付费版)
  • 内存限制:每个隔离区 128 MB
  • 语言: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 转换)
处理程序

Workers 通过处理程序响应事件:

Fetch 处理程序(HTTP 请求):

export default {
  async fetch(request: Request, env: Env, ctx: ExecutionContext) {
    return new Response("Hello!");
  },
};

Scheduled 处理程序(cron 任务):

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 处理程序(消息处理):

export default {
  async queue(batch: MessageBatch<any>, env: Env, ctx: ExecutionContext) {
    for (const message of batch.messages) {
      await processMessage(message.body);
      message.ack();
    }
  },
};
绑定

绑定将 Worker 连接到 Cloudflare 资源。在 wrangler.toml 中配置:

KV(键值存储):

[[kv_namespaces]]
binding = "MY_KV"
id = "your-kv-namespace-id"
// Usage
await env.MY_KV.put("key", "value");
const value = await env.MY_KV.get("key");

D1(SQL 数据库):

[[d1_databases]]
binding = "DB"
database_name = "my-database"
database_id = "your-database-id"
// Usage
const result = await env.DB.prepare(
  "SELECT * FROM users WHERE id = ?"
).bind(userId).all();

R2(对象存储):

[[r2_buckets]]
binding = "MY_BUCKET"
bucket_name = "my-bucket"
// Usage
await env.MY_BUCKET.put("file.txt", "contents");
const object = await env.MY_BUCKET.get("file.txt");
const text = await object?.text();

环境变量(仅限非机密数据):

[vars]
GREETING = "hello"
ENVIRONMENT = "development"

机密(敏感数据——切勿放入 wrangler.toml):

# Set via CLI; the value is encrypted server-side and never written to disk locally
wrangler secret put MY_API_KEY
上下文(ctx)

ctx 参数用于控制请求生命周期:

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");
  },
};
顶层环境访问

自 2025 年 3 月起,你可以在模块级别导入 env,而不必通过处理程序传递:

import { env } from "cloudflare:workers";

// Access bindings outside of handlers
const apiClient = new ApiClient({ apiKey: env.API_KEY });

export default {
  async fetch(request: Request): Promise<Response> {
    // env is also available here without the parameter
    const data = await env.MY_KV.get("config");
    return Response.json({ data });
  },
};

这样可以避免在函数签名中层层传递 env,并支持在模块级别进行初始化。

快速开发模式

Wrangler 配置

必备的 wrangler.toml:

name = "my-worker"
main = "src/index.ts"
compatibility_date = "2025-09-01"

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

# Or workers.dev subdomain
workers_dev = true

# Environment variables
[vars]
ENVIRONMENT = "production"

# 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"

# Cron triggers
[triggers]
crons = ["0 0 * * *"]  # Daily at midnight
环境管理

使用环境区分预发布和生产环境:

[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"
# Deploy to staging
wrangler deploy --env staging

# Deploy to production
wrangler deploy --env production
常见模式

带错误处理的 JSON API:

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 }
      );
    }
  },
};

身份验证中间件:

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 标头:

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;
  },
};
静态资源(全栈应用)

在提供 Worker 代码的同时提供静态文件:

[assets]
directory = "./public"
binding = "ASSETS"
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 via the ASSETS binding
    return env.ASSETS.fetch(request);
  },
};
测试

使用 Vitest:

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!" });
  });
});

框架集成

Workers 支持主流框架,并提供适配器:

  • Next.js - 完整支持 App Router 和 Pages Router
  • Remix / React Router - 原生 Cloudflare 适配器
  • Astro - 在 Workers 上进行服务器端渲染
  • SvelteKit - 提供 Cloudflare 适配器
  • Hono - 为 Workers 构建的轻量级 Web 框架
  • tRPC - 完全支持 Workers 的类型安全 API

Hono 示例:

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;

高级主题

如需详细了解高级功能,请参阅参考文件:

  • 完整绑定指南:references/bindings-complete-guide.md - 所有绑定类型(D1、KV、R2、Durable Objects、Queues、Workers AI、Vectorize、Workflows、Containers、Secrets Store、Pipelines、AutoRAG)
  • 部署与 CI/CD:references/wrangler-and-deployment.md - Wrangler v4 迁移、命令、GitHub Actions、GitLab CI/CD、渐进式发布、远程绑定
  • 开发最佳实践:references/development-patterns.md - 测试、调试、错误处理、性能、顶层 env 访问模式
  • 高级功能:references/advanced-features.md - Containers、Workflows、MCP 服务、Workers for Platforms、WebSockets、Node.js 兼容性、流式处理
  • 可观测性:references/observability.md - 日志(tail、Logpush、Workers Logs)、指标、跟踪、调试

资源

官方文档:

模板与快速入门:

社区:

评论

支持 Markdown