本文へスキップ
Skillpedia
APIとサーバー(バックエンド)48k · #4169

cloudflare-workers

できること

Cloudflare Workersを使うと、「関数」と呼ばれる小さなプログラムを、Cloudflareの世界規模のネットワーク上で直接作成し、実行できます。これにより、ユーザーがどこにいても、アプリケーションが非常に素早く応答できるようになります。

使う場面

  • ✓非常に高速な応答が求められるAPI(他のプログラムが通信に使うサービス)を作るとき。
  • ✓メインのサーバーにリクエストが届く前に、セキュリティチェックや調整を加えたいとき。
  • ✓常時稼働しているサーバーを用意せずに、特定の時刻に自動処理を実行したいとき。

スキルのリンク

https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/cloudflare-workers/SKILL.md

コピーしてAI(Claude、ChatGPT、Cursor)に貼り付け、指示に従うよう頼んでください。

使い方

いちばん簡単な方法:メッセージをコピーしてAIに貼り付けるだけ。AIがスキルを読んで指示に従います。

貼り付け用メッセージ

このスキルを使って手伝ってください:https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/cloudflare-workers/SKILL.md このリンクのSKILL.mdファイルを読んで、私の作業でその指示に従ってください。
こういうスキルを、AIが自分で見つけてくれたら?無料のSkillpedia MCPをインストール。1行で、作業の前に15,000+のスキルから探してくれます。1分でインストール →

AIへの頼み方の例

“誰かがアクセスしたら「Hello World」と返す、シンプルなAPIを作成してください。”

毎週5つの新しいスキル。1分で読めます。

仕組み

コードはJavaScriptまたはTypeScriptで書き、Wranglerというツールを使ってそのコードをCloudflareのネットワークに送ります。コードをユーザーの近くで実行する処理は、Cloudflareが引き受けます。

技術的な内容(元のSKILL.md)

作者による元のテキスト(英語)をGitHubからそのまま表示しています。

Cloudflare Workers

Deploy JavaScript and TypeScript functions to Cloudflare's global edge network with sub-millisecond cold starts.

When to Use

  • Building lightweight APIs and microservices at the edge.
  • Adding middleware (auth, rate limiting, header injection) in front of origin servers.
  • Running cron jobs on a schedule without maintaining infrastructure.
  • Processing webhooks, image transformations, or A/B testing logic.
  • Serving dynamic content from KV, D1, or R2 storage bindings.

Prerequisites

  • Node.js 18+ installed locally.
  • Wrangler CLI: npm install -g wrangler.
  • Cloudflare account (free plan supports 100,000 requests/day).
  • Authenticated: wrangler login or set CLOUDFLARE_API_TOKEN.

Quick Start

# Scaffold a new Worker project
npm create cloudflare@latest my-worker
cd my-worker

# Login to Cloudflare
npx wrangler login

# Start local development server (port 8787)
npx wrangler dev

# Deploy to production
npx wrangler deploy

Essential Wrangler Commands

# Local development with remote bindings (KV, D1, R2)
npx wrangler dev --remote

# Deploy to a specific environment
npx wrangler deploy --env staging

# Set a secret (prompts for value)
npx wrangler secret put API_TOKEN
npx wrangler secret put API_TOKEN --env staging

# List secrets
npx wrangler secret list

# Tail production logs in real time
npx wrangler tail

# Tail with filters
npx wrangler tail --status=error --search="timeout"

# View deployment versions
npx wrangler deployments list

# Rollback to a previous deployment
npx wrangler rollback

Wrangler Configuration

# wrangler.toml
name = "my-api"
main = "src/index.ts"
compatibility_date = "2024-09-01"
compatibility_flags = ["nodejs_compat"]

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

# Or use a workers.dev subdomain
# workers_dev = true

# Environment variables (non-secret)
[vars]
ENVIRONMENT = "production"
API_VERSION = "v2"

# Staging environment override
[env.staging]
name = "my-api-staging"
routes = [
  { pattern = "api-staging.example.com/*", zone_name = "example.com" }
]
[env.staging.vars]
ENVIRONMENT = "staging"

Worker Examples

Basic API Router

// src/index.ts
export interface Env {
  ENVIRONMENT: string;
}

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

    switch (url.pathname) {
      case "/":
        return new Response("OK", { status: 200 });

      case "/api/health":
        return Response.json({
          status: "healthy",
          env: env.ENVIRONMENT,
          timestamp: new Date().toISOString(),
        });

      case "/api/data":
        if (request.method !== "POST") {
          return new Response("Method Not Allowed", { status: 405 });
        }
        const body = await request.json();
        // Process in the background after returning response
        ctx.waitUntil(logToAnalytics(body));
        return Response.json({ received: true });

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

async function logToAnalytics(data: unknown): Promise<void> {
  await fetch("https://analytics.example.com/ingest", {
    method: "POST",
    body: JSON.stringify(data),
    headers: { "Content-Type": "application/json" },
  });
}

Middleware: Rate Limiting with KV

// src/rate-limiter.ts
interface Env {
  RATE_LIMIT_KV: KVNamespace;
  ORIGIN_URL: string;
}

export default {
  async fetch(request: Request, env: Env): Promise<Response> {
    const ip = request.headers.get("CF-Connecting-IP") || "unknown";
    const key = `ratelimit:${ip}`;
    const window = 60; // seconds
    const maxRequests = 100;

    const current = parseInt((await env.RATE_LIMIT_KV.get(key)) || "0");

    if (current >= maxRequests) {
      return new Response("Too Many Requests", {
        status: 429,
        headers: { "Retry-After": String(window) },
      });
    }

    await env.RATE_LIMIT_KV.put(key, String(current + 1), {
      expirationTtl: window,
    });

    // Forward to origin
    const originRequest = new Request(env.ORIGIN_URL + new URL(request.url).pathname, request);
    return fetch(originRequest);
  },
};

KV Storage Binding

# wrangler.toml
[[kv_namespaces]]
binding = "MY_KV"
id = "abc123def456"

# Preview namespace for local dev
[[kv_namespaces]]
binding = "MY_KV"
id = "abc123def456"

…
よくある質問

Cloudflare Workersを使うのに料金は必要ですか?

Cloudflareの無料プランには、1日あたりのリクエスト数の上限が比較的多く設定されています。小規模なプロジェクトやテストであれば、多くの場合これで十分です。

「エッジ」とは何を意味しますか?

「エッジ」とは、Cloudflareがサーバーを世界中に配置している物理的な拠点のことを指します。エッジでコードを実行すると、エンドユーザーに近い場所で動作するため、すべてが速くなります。

「コールドスタート」とは何ですか?

しばらく動いていなかったコードが、初めて実行されるときに発生する、わずかな遅延のことです。Cloudflare Workersは、コールドスタートが非常に速く、ほとんど気にならないことで知られています。

詳細

作者による元の説明

Build and deploy edge functions with Cloudflare Workers and Wrangler. Use for APIs, cron jobs, and edge middleware.

repo: sickn33/agentic-awesome-skills

人気

GitHubのスター
48k
ランキング
#4169
ライセンス
MIT
更新日
2026/10/15

このスキルは役に立ちますか?

0

ログイン して投票しましょう。

コメント

  • …

このリポジトリの他のスキル

似ているスキル