Skip to main content
skill CX Codex

cloudflare-workers — Claude Code skill: edge functions with Wrangler

A skill for building and deploying Cloudflare Workers edge functions with Wrangler. Useful for APIs, cron jobs and middleware.

Install into Claude Code · Skills CLI (Vercel) All methods and platforms ↓
npx skills add BagelHole/DevOps-Security-Agent-Skills --skill cloudflare-workers -a claude-code
Open on GitHub

What cloudflare-workers does

The skill gives your agent context on Cloudflare Workers and Wrangler: scaffolding a project, configuring wrangler.toml, deploying, and tailing logs. It ships TypeScript examples for a router, KV-backed rate limiting middleware, D1 queries and secret handling. Commands cover local dev, per-environment deploys, rollback and filtered wrangler tail.

You need Node.js 18+ and the Wrangler CLI: npm install -g wrangler. A Cloudflare account is required too, with auth via wrangler login or a CLOUDFLARE_API_TOKEN variable. Skip the login step and the deploy fails, so set the token before your first push to production.

The skill installs with one npx skills add command and works across several agents. If you edit wrangler.toml by hand, watch compatibility_date and flags like nodejs_compat — they decide which Node APIs your runtime exposes.

What it helps with

  • scaffold a new Worker project and ship it to production
  • add KV-backed rate limiting in front of an origin server
  • run D1 SQL queries from inside a Worker
  • wire up secrets and env vars for a staging environment
  • tail production logs live and roll back a bad deploy

Example prompts for the agent

  • Scaffold a new Cloudflare Worker with a TypeScript router and a health check endpoint
  • Add rate limiting middleware backed by a KV binding that forwards to origin
  • Set up wrangler.toml with a staging environment and deploy there

How to install cloudflare-workers

1Skills CLI (Vercel)

npx skills add BagelHole/DevOps-Security-Agent-Skills --skill cloudflare-workers -a claude-code

2Manually: put the files in place

~/.claude/skills/cloudflare-workers/SKILL.md

Copy the whole skill folder; for one project use .claude/skills/cloudflare-workers/

Step by step, with commands for each platform: How to install skills in Claude Code: five ways

Questions about cloudflare-workers

How do I install cloudflare-workers in Claude?

Run npx skills add BagelHole/DevOps-Security-Agent-Skills --skill cloudflare-workers -a claude-code. The skill lands at ~/.claude/skills/cloudflare-workers/SKILL.md.

What does the cloudflare-workers skill do?

It helps your agent write and deploy Cloudflare Workers edge functions through Wrangler: APIs, cron jobs, middleware. Examples include a router, KV rate limiting and D1 queries.

What do I need before using it?

Node.js 18+ and the Wrangler CLI (npm install -g wrangler). You also need a Cloudflare account and auth via wrangler login or the CLOUDFLARE_API_TOKEN variable.

Source text

SKILL.md · MIT
---
name: cloudflare-workers
description: Build and deploy edge functions with Cloudflare Workers and Wrangler. Use for APIs, cron jobs, and edge middleware.
license: MIT
metadata:
  author: devops-skills
  version: "1.0"
---

# 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

```bash
# 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

```bash
# 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

```toml
# 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

```typescript
// 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

```typescript
// 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

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

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

```typescript
// KV operations in a Worker
interface Env {
  MY_KV: KVNamespace;
}

export default {
  async fetch(request: Request, env: Env): Promise<Response> {
    // Write with TTL
    await env.MY_KV.put("session:abc", JSON.stringify({ user: "alice" }), {
      expirationTtl: 3600,
    });

    // Read
    const session = await env.MY_KV.get("session:abc", "json");

    // List keys by prefix
    const list = await env.MY_KV.list({ prefix: "session:", limit: 100 });

    // Delete
    await env.MY_KV.delete("session:abc");

    return Response.json({ session, keys: list.keys.length });
  },
};
```

```bash
# KV CLI operations
npx wrangler kv namespace create MY_KV
npx wrangler kv namespace list
npx wrangler kv key put --namespace-id=abc123 "config:feature-flags" '{"darkMode":true}'
npx wrangler kv key get --namespace-id=abc123 "config:feature-flags"
npx wrangler kv key list --namespace-id=abc123 --prefix="config:"
```

## D1 Database Binding

```toml
# wrangler.toml
[[d1_databases]]
binding = "DB"
database_name = "my-app"
database_id = "xxxx-yyyy-zzzz"
```

```typescript
// D1 SQL queries in a Worker
interface Env {
  DB: D1Database;
}

export default {
  async fetch(request: Request, env: Env): Promise<Response> {
    // Parameterized query
    const { results } = await env.DB.prepare(
      "SELECT id, name, email FROM users WHERE active = ? LIMIT ?"
    )
      .bind(1, 50)
      .all();

    // Insert
    await env.DB.prepare("INSERT INTO users (name, email) VALUES (?, ?)")
      .bind("Alice", "[email protected]")
      .run();

    // Batch multiple statements
    await env.DB.batch([
      env.DB.prepare("UPDATE users SET active = 0 WHERE last_login < ?").bind("2024-01-01"),
      env.DB.prepare("DELETE FROM sessions WHERE expires_at < ?").bind(Date.now()),
    ]);

    return Response.json(results);
  },
};
```

```bash
# D1 CLI operations
npx wrangler d1 create my-app
npx wrangler d1 list
npx wrangler d1 execute my-app --command="CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, email TEXT, active INTEGER DEFAULT 1)"
npx wrangler d1 execute my-app --file=./migrations/001_init.sql
npx wrangler d1 execute my-app --command="SELECT * FROM users" --json
```

## Cron Triggers

```toml
# wrangler.toml
[triggers]
crons = [
  "0 */6 * * *",   # Every 6 hours
  "0 0 * * MON",   # Every Monday at midnight
  "*/15 * * * *",  # Every 15 minutes
]
```

```typescript
// src/index.ts — scheduled handler
export default {
  async scheduled(event: ScheduledEvent, env: Env, ctx: ExecutionContext): Promise<void> {
    switch (event.cron) {
      case "0 */6 * * *":
        ctx.waitUntil(cleanupExpiredSessions(env));
        break;
      case "0 0 * * MON":
        ctx.waitUntil(generateWeeklyReport(env));
        break;
    }
  },

  async fetch(request: Request, env: Env): Promise<Response> {
    return new Response("OK");
  },
};
```

## Durable Objects

```toml
# wrangler.toml
[durable_objects]
bindings = [
  { name = "COUNTER", class_name = "Counter" }
]

[[migrations]]
tag = "v1"
new_classes = ["Counter"]
```

```typescript
// src/counter.ts — Durable Object class
export class Counter {
  state: DurableObjectState;

  constructor(state: DurableObjectState) {
    this.state = state;
  }

  async fetch(request: Request): Promise<Response> {
    let count = (await this.state.storage.get<number>("count")) || 0;
    count++;
    await this.state.storage.put("count", count);
    return Response.json({ count });
  }
}

// src/index.ts — route to Durable Object
interface Env {
  COUNTER: DurableObjectNamespace;
}

export default {
  async fetch(request: Request, env: Env): Promise<Response> {
    const id = env.COUNTER.idFromName("global-counter");
    const stub = env.COUNTER.get(id);
    return stub.fetch(request);
  },
};
```

## Custom Routing

```toml
# Route to specific zones
routes = [
  { pattern = "api.example.com/v1/*", zone_name = "example.com" },
  { pattern = "api.example.com/v2/*", zone_name = "example.com" },
]

# Or use custom domains (automatic SSL)
# Dashboard: Workers > your-worker > Triggers > Custom Domains
```

## Troubleshooting

| Symptom | Cause | Fix |
|---------|-------|-----|
| `Error 1101: Worker threw exception` | Unhandled error in fetch handler | Wrap handler in try/catch; check `wrangler tail` for stack trace |
| `exceeded CPU time limit` | Worker exceeds 10ms CPU (free) or 30s (paid) | Optimize code; offload work with `ctx.waitUntil()` |
| KV reads return stale data | KV is eventually consistent (~60s) | Use `cacheTtl` option or switch to Durable Objects for strong consistency |
| `wrangler dev` binding errors | Local bindings not configured | Use `--remote` flag or configure `preview_id` in `wrangler.toml` |
| Secret not found in Worker | Secret set for wrong environment | Verify with `wrangler secret list --env <env>` |
| CORS errors from browser | Missing CORS headers in response | Add `Access-Control-Allow-Origin` headers; handle OPTIONS preflight |
| Route not matching | Pattern does not include `/*` suffix | Add `/*` to catch all paths: `api.example.com/*` |

## Related Skills

- [cloudflare-pages](../cloudflare-pages/) - Frontend deployments with Pages Functions
- [cloudflare-r2](../cloudflare-r2/) - Object storage at the edge
- [cloudflare-zero-trust](../cloudflare-zero-trust/) - Protect Worker endpoints with Access

© devops-skills · MIT · BagelHole/DevOps-Security-Agent-Skills

Similar skills

Everything for DevOps and infrastructure →

From the same set127

identity-access-management A skill for setting up SSO, SCIM provisioning and MFA through Google Workspace, Okta or Azure AD. Useful once manual onboarding stops keeping up with the team. CX Codex +1 317installs vercel-deployments A skill for deploying frontend and full-stack apps on Vercel: previews, edge functions, environment variables and production guardrails. CX Codex +1 316installs llmops-platform-engineering A skill for building an internal LLM platform: CI/CD with evaluation gates, model promotion, canary deploys and rollback. CX Codex +1 315installs vllm-server Deploys and configures vLLM inference servers with continuous batching and tensor parallelism. Use it to host open-source LLMs behind an OpenAI-compatible API. CX Codex +1 314installs azure-monitor-audit Configures Azure Monitor, Log Analytics, and Activity Logs for centralized auditing. It helps fulfill logging requirements for SOC 2, HIPAA, PCI DSS, or ISO 27001. CX Codex +1 313installs saas-security-posture A skill that audits and hardens your company SaaS stack: SSO, OAuth grants, shadow IT and admin accounts across Slack, GitHub, Google Workspace and AWS. CX Codex +1 314installs datadog Sets up the Datadog agent, APM tracing, log collection, and metrics for services and databases. Useful when configuring unified infrastructure monitoring. CX Codex +1 312installs firebase-app-platform A skill that walks your agent through Firebase backends: Auth, Firestore, Cloud Functions and Hosting. Useful when you want managed services instead of your own server. CX Codex +1 313installs

Project sponsors

Companies that keep this analytics open
Gold sponsor

Impressions, clicks and code copies — open statistics. We keep the numbers public for the same reason NeBlask itself is public. Become a sponsor