agentleFS
PanPanFRPanPanFR/oh-my-kilo/skills/cloudflare/SKILL.md

cloudflare

Skill12 starsChanged 3 months agoMITView on GitHub

Unified Cloudflare platform skill: Workers, Durable Objects, Wrangler CLI, KV, D1, R2, AI, Vectorize, Queues, Workflows, Containers, Pipelines, Secrets Store, Agents SDK, Pages, security (WAF, DDoS, Turnstile), networking (Tunnel, Spectrum), IaC (Terraform, Pulumi). Use for any CF task. Retrieval-first.

  • Reads credentials
  • Installs packages

37 other projects use a version of this, 18 of them edited.

Adopted by

Most recently taken up by

Used with

Projects with it also use cloudflare-one-migrations, cloudflare-email-service and 9 more.

Other files people use alongside this one.

Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
  • CloudflareSkill

    cloudflare-one-migrations

    Assess and plan migrations from existing VPN, SWG, or SASE platforms to Cloudflare One, including policy mapping, parity gaps, and rollout.

    Also in 6 projects that use this

  • CloudflareSkill

    cloudflare-email-service

    Implement or troubleshoot Cloudflare Email Sending and Email Routing integrations and their delivery configuration.

    Also in 8 projects that use this

  • OpenAISkill

    workers-best-practices

    Reviews and authors Cloudflare Workers code against production best practices. Load when writing new Workers, reviewing Worker code, configuring wrangler.jsonc, or checking for common Workers anti-patterns (streaming, floating promises, global state, secrets, bindings, observability). Biases towards retrieval from Cloudflare docs over pre-trained knowledge.

    Also in 11 projects that use this

  • OpenAISkill

    durable-objects

    Create and review Cloudflare Durable Objects. Use when building stateful coordination (chat rooms, multiplayer games, booking systems), implementing RPC methods, SQLite storage, alarms, WebSockets, or reviewing DO code for best practices. Covers Workers integration, wrangler config, and testing with Vitest. Biases towards retrieval from Cloudflare docs over pre-trained knowledge.

    Also in 9 projects that use this

  • akornmeierSkill

    mongodb

    Guide for implementing MongoDB - a document database platform with CRUD operations, aggregation pipelines, indexing, replication, sharding, search capabilities, and comprehensive security. Use when working with MongoDB databases, designing schemas, writing queries, optimizing performance, configuring deployments (Atlas/self-managed/Kubernetes), implementing security, or integrating with applications through 15+ official drivers. (project)

    Also in 3 projects that use this

  • imehrSkill

    railway

    Railway.com deployment and management - deployment, logs, migrations, troubleshooting, monorepo strategies, security, and CLI reference. Use when deploying to Railway, configuring services, managing environment variables, or debugging deployment issues.

    Also in 3 projects that use this

  • +2 more from cloudflare
  • +3 more from openai

The file

We split this skill into the rules it gives an agent

1 rule. 0 are common, 1 is distinctive, and 0 are very specific to this project.

  • 0

    Common

    Most of the 31 edited versions we read keep these.

  • 1

    Distinctive

    This author's own choices. Worth a look.

  • 0

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    When reference and docs disagree, trust the docs.

    line 23

“Common” is measured: kept by at least 6 in 10 of the 31 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Cloudflare Platform Skill (Unified)

Consolidated: cloudflare + workers-best-practices + wrangler + durable-objects.

Retrieval-first — fetch latest docs before citing numbers, APIs, config.

Retrieval Sources

SourceURLUse for
CF Docshttps://developers.cloudflare.com/Limits, pricing, API reference
Workers typesnpm pack @cloudflare/workers-typesType signatures, binding shapes
Wrangler schemanode_modules/wrangler/config-schema.jsonConfig fields, binding shapes
Changeloghttps://developers.cloudflare.com/changelog/Recent changes
Best Practiceshttps://developers.cloudflare.com/workers/best-practices/workers-best-practices/Canonical rules, anti-patterns
DO APIhttps://developers.cloudflare.com/durable-objects/api/DO methods, storage, alarms

When reference and docs disagree, trust the docs.


DECISION TREES

"I need to run code"

├─ Serverless edge functions → Workers
├─ Full-stack with Git deploys → Pages
├─ Stateful coordination/real-time → Durable Objects
├─ Long-running multi-step → Workflows
├─ Run containers → Containers
├─ Multi-tenant (customers deploy) → Workers for Platforms
├─ Scheduled tasks (cron) → Cron Triggers
├─ Lightweight edge logic (modify HTTP) → Snippets
├─ Process execution events (logs) → Tail Workers
└─ Optimize latency to backend → Smart Placement

"I need to store data"

├─ Key-value (config, sessions, cache) → KV
├─ Relational SQL → D1 (SQLite) or Hyperdrive (existing PG/MySQL)
├─ Object/file (S3-compatible) → R2
├─ Versioned file trees → Artifacts
├─ Message queue → Queues
├─ Vector embeddings → Vectorize
├─ Per-entity state → DO storage (SQLite)
├─ Secrets → Secrets Store
├─ Streaming ETL to R2 → Pipelines
├─ Managed Iceberg catalog → R2 Data Catalog
├─ Serverless SQL analytics → R2 SQL
└─ Persistent cache → Cache Reserve

"I need AI/ML"

├─ Run inference (LLMs, embeddings, images) → Workers AI
├─ Vector database for RAG/search → Vectorize
├─ Build stateful AI agents → Agents SDK
├─ Gateway for any AI provider → AI Gateway
└─ AI-powered search widget → AI Search

"I need security"

├─ WAF → WAF
├─ DDoS protection → DDoS
├─ Bot detection → Bot Management
├─ API protection → API Shield
├─ CAPTCHA alternative → Turnstile
└─ Credential leak detection → WAF (managed ruleset)

WORKERS BEST PRACTICES

Configuration

RuleSummary
compatibility_dateSet to today on new; update periodically
nodejs_compatEnable flag — many libs need Node.js built-ins
wrangler typesRun after config changes — never hand-write Env
SecretsUse wrangler secret put, never hardcode
wrangler.jsoncJSON config preferred; newer features JSON-only

Request & Response

RuleSummary
StreamingStream large/unknown payloads — never await response.text() on unbounded
waitUntilUse ctx.waitUntil() for post-response work; don't destructure ctx

Architecture

RuleSummary
Bindings over RESTUse in-process bindings (KV, R2, D1, Queues) not REST API
Queues & WorkflowsMove async work off critical path
Service bindingsWorker-to-Worker via service bindings, not public HTTP
HyperdriveAlways for external PG/MySQL connections

Security

RuleSummary
Web Cryptocrypto.randomUUID() / crypto.getRandomValues() — never Math.random()
No passThroughOnExceptionExplicit try/catch with structured errors

Anti-Patterns (NEVER)

Anti-patternWhy
await response.text() unboundedMemory exhaustion (128MB limit)
Hardcoded secretsCredential leak
Math.random() for tokensNot cryptographically secure
Bare fetch() no await/waitUntilFloating promise
Module-level mutable request stateCross-request data leaks
REST API from WorkerUnnecessary network hop, latency
ctx.passThroughOnException()Hides bugs
Hand-written EnvDrifts from wrangler config
Destructuring ctxLoses this binding
any on Env/paramsDefeats type safety
as unknown as T double-castHides type incompatibilities
implements on platform classesUse extends DurableObject/WorkerEntrypoint/Workflow
env.X inside platform classUse this.env.X

DURABLE OBJECTS

When to Use

NeedExample
CoordinationChat rooms, multiplayer, collaborative docs
Strong consistencyInventory, booking, turn-based games
Per-entity storageMulti-tenant SaaS, per-user data
Persistent connectionsWebSockets, real-time notifications
Scheduled per entitySubscription renewals, game timeouts

When NOT to Use

  • Stateless request handling (plain Workers)
  • Maximum global distribution
  • High fan-out independent requests

Core Pattern

import { DurableObject } from "cloudflare:workers";

export class MyDO extends DurableObject<Env> {
  constructor(ctx: DurableObjectState, env: Env) {
    super(ctx, env);
    ctx.blockConcurrencyWhile(async () => {
      this.ctx.storage.sql.exec(`
        CREATE TABLE IF NOT EXISTS items (
          id INTEGER PRIMARY KEY AUTOINCREMENT,
          data TEXT NOT NULL
        )
      `);
    });
  }

  async addItem(data: string): Promise<number> {
    const result = this.ctx.storage.sql.exec<{ id: number }>(
      "INSERT INTO items (data) VALUES (?) RETURNING id", data
    );
    return result.one().id;
  }
}

Critical Rules

  1. Model around coordination atoms — one DO per entity, not global
  2. getByName() for deterministic routing — same input = same DO
  3. SQLite storage — configure new_sqlite_classes in migrations
  4. Initialize in constructor — blockConcurrencyWhile() for schema only
  5. RPC methods — not fetch() handler (compat date >= 2024-04-03)
  6. Persist first, cache second — write storage before memory
  7. One alarm per DO — setAlarm() replaces existing

Anti-Patterns

  • Single global DO (bottleneck)
  • blockConcurrencyWhile() every request (kills throughput)
  • Critical state only in memory (lost on eviction)
  • await between related writes (breaks atomicity)
  • Holding blockConcurrencyWhile across fetch/external I/O

Stub Creation

const stub = env.MY_DO.getByName("room-123");  // Deterministic
const id = env.MY_DO.idFromString(storedId);     // From ID string
const stub = env.MY_DO.newUniqueId();             // New unique

Storage

// SQL (synchronous, recommended)
this.ctx.storage.sql.exec("INSERT INTO t (c) VALUES (?)", value);
const rows = this.ctx.storage.sql.exec<Row>("SELECT * FROM t").toArray();

// KV (async)
await this.ctx.storage.put("key", value);
const val = await this.ctx.storage.get<Type>("key");

Alarms

await this.ctx.storage.setAlarm(Date.now() + 60_000);
async alarm() { /* process, optionally reschedule */ }
await this.ctx.storage.deleteAlarm();

WRANGLER CLI

Quick Reference

TaskCommand
Local devwrangler dev
Deploywrangler deploy
Deploy dry runwrangler deploy --dry-run
Generate typeswrangler types
Profile startupwrangler check startup
Live logswrangler tail
Deletewrangler delete
Auth statuswrangler whoami

Config (wrangler.jsonc)

{
  "$schema": "./node_modules/wrangler/config-schema.json",
  "name": "my-worker",
  "main": "src/index.ts",
  "compatibility_date": "2026-01-01",
  "compatibility_flags": ["nodejs_compat"],
  "vars": { "ENVIRONMENT": "production" },
  "kv_namespaces": [{ "binding": "KV", "id": "<ID>" }],
  "r2_buckets": [{ "binding": "BUCKET", "bucket_name": "my-bucket" }],
  "d1_databases": [{ "binding": "DB", "database_name": "my-db", "database_id": "<ID>" }],
  "ai": { "binding": "AI" },
  "vectorize": [{ "binding": "INDEX", "index_name": "my-index" }],
  "hyperdrive": [{ "binding": "HD", "id": "<ID>" }],
  "durable_objects": { "bindings": [{ "name": "COUNTER", "class_name": "Counter" }] },
  "migrations": [{ "tag": "v1", "new_sqlite_classes": ["Counter"] }],
  "workflows": [{ "binding": "WF", "name": "my-workflow", "class_name": "MyWorkflow" }],
  "queues": {
    "producers": [{ "binding": "Q", "queue": "my-queue" }],
    "consumers": [{ "queue": "my-queue", "max_batch_size": 10 }]
  },
  "triggers": { "crons": ["0 * * * *"] },
  "observability": { "enabled": true, "head_sampling_rate": 1 },
  "env": {
    "staging": { "name": "my-worker-staging", "vars": { "ENVIRONMENT": "staging" } }
  }
}

Local Dev

wrangler dev                          # Local mode (default)
wrangler dev --env staging            # Specific environment
wrangler dev --port 8787              # Custom port
wrangler dev --live-reload            # HTML live reload
wrangler dev --test-scheduled         # Test cron handlers (visit /__scheduled)

Remote bindings for local dev:

{ "r2_buckets": [{ "binding": "BUCKET", "bucket_name": "my-bucket", "remote": true }] }

Deployment

wrangler deploy                       # Production
wrangler deploy --env staging         # Staging
wrangler deploy --dry-run             # Validate without deploy
wrangler deploy --keep-vars           # Keep dashboard variables
wrangler deploy --minify              # Minify code

Secrets

wrangler secret put API_KEY           # Interactive (preferred)
wrangler secret put KEY < key.pem     # From file
wrangler secret list                  # List
wrangler secret delete API_KEY        # Delete
wrangler secret bulk secrets.json     # Bulk from JSON

KV

wrangler kv namespace create MY_KV
wrangler kv key put --namespace-id <ID> "key" "value"
wrangler kv key get --namespace-id <ID> "key"
wrangler kv bulk put --namespace-id <ID> data.json

R2

wrangler r2 bucket create my-bucket
wrangler r2 object put my-bucket/path --file ./local-file.txt
wrangler r2 object get my-bucket/path

D1

wrangler d1 create my-database
wrangler d1 execute my-database --remote --command "SELECT * FROM users"
wrangler d1 execute my-database --remote --file ./schema.sql
wrangler d1 migrations create my-database create_users_table
wrangler d1 migrations apply my-database --remote
wrangler d1 export my-database --remote --output backup.sql

Vectorize

wrangler vectorize create my-index --dimensions 768 --metric cosine
wrangler vectorize create my-index --preset @cf/baai/bge-base-en-v1.5
wrangler vectorize query my-index --vector "[0.1, ...]" --top-k 10

Hyperdrive

wrangler hyperdrive create my-hd --origin-host db.example.com --origin-port 5432 --database mydb --origin-user user --origin-password "$PASS"

Workers AI

wrangler ai models

Config: { "ai": { "binding": "AI" } } (always remote, charges apply)

Queues

wrangler queues create my-queue
wrangler queues consumer add my-queue my-worker

Workflows

wrangler workflows list
wrangler workflows trigger my-workflow --params '{"key":"value"}'
wrangler workflows instances list my-workflow

Containers

wrangler containers build -t my-app:latest . --push
wrangler containers list
wrangler containers registries list

Pipelines

wrangler pipelines create my-pipeline --r2 my-bucket
wrangler pipelines show my-pipeline

Secrets Store

wrangler secrets-store store create my-store
wrangler secrets-store secret put <STORE_ID> my-secret
wrangler secrets-store secret get <STORE_ID> my-secret

Pages

wrangler pages project create my-site
wrangler pages deploy ./dist --branch main

Observability

wrangler tail                          # Stream logs
wrangler tail --status error           # Filter by status
wrangler tail --search "error"         # Filter by term

Testing (Vitest)

npm install -D @cloudflare/vitest-pool-workers vitest
import { defineWorkersConfig } from "@cloudflare/vitest-pool-workers/config";
export default defineWorkersConfig({
  test: { poolOptions: { workers: { wrangler: { configPath: "./wrangler.jsonc" } } } }
});

Troubleshooting

IssueSolution
command not found: wranglernpm install -D wrangler
Auth errorswrangler login
Startup time exceededwrangler check startup
Type errors after configwrangler types
Binding undefinedCheck name matches config exactly

PRODUCT INDEX

Compute & Runtime

Workers, Pages, Durable Objects, Workflows, Containers, Workers for Platforms, Cron Triggers, Tail Workers, Snippets, Smart Placement

Storage & Data

KV, D1, R2, Artifacts, Queues, Hyperdrive, DO Storage, Secrets Store, Pipelines, R2 Data Catalog, R2 SQL

AI & ML

Workers AI, Vectorize, Agents SDK, AI Gateway, AI Search

Networking

Tunnel, Spectrum, TURN, Network Interconnect, Argo Smart Routing, Workers VPC

Security

WAF, DDoS, Bot Management, API Shield, Turnstile

Media

Images, Stream, Browser Rendering, Zaraz

IaC

Pulumi, Terraform, API

Other

Email Routing, Email Workers, Static Assets, Bindings, Cache Reserve, Flagship (feature flags)

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.