Logotipo de Cloudflare Workers Author

Cloudflare Workers Author

Comunidad
d-padmanabhan
cloudflare-workers-author

Workflow for building production-grade Cloudflare Workers in TypeScript - bootstrap, bindings and storage choice, routing (Hono + RPC via WorkerEntrypoint), testing with @cloudflare/vitest-plugin, gradual deployments, and common pitfalls. Use when adding a new Worker, adding endpoints to an existing Worker, choosing between KV / R2 / D1 / Durable Objects / Hyperdrive, setting up testing, configuring deployment, or reviewing a Worker PR.

Descripción general

Editord-padmanabhan
Repositorioagent-engineering-handbook
Nombre de la habilidadcloudflare-workers-author
Estrellas
20
Forks
3
Archivos incluidos
7
LicenciaMIT
Enlaces
  • Instrucciones en Markdown

    Un archivo SKILL.md que el modelo carga cuando lo necesita, de modo que solo consume tokens cuando la petición encaja con la habilidad.

  • Funciona con cualquier LLM

    Las habilidades de IA están en Markdown, no en código específico de un proveedor, por lo que funcionan con GPT, Claude, Gemini, Grok o un modelo local.

  • Archivos incluidos: 7

    Scripts, plantillas y referencias que el modelo puede leer mientras trabaja. Los archivos son de solo lectura y nunca se ejecutan.

  • Código abierto

    Publicada por d-padmanabhan en GitHub. Revisa el contenido original antes de instalarla.

Instalación

Instala la habilidad de IA Cloudflare Workers Author en TypingMind para usarla con cualquier LLM, o añádela a otro agente que lea SKILL.md.

1

Instalar en TypingMind

TypingMind instala una habilidad directamente desde su carpeta de GitHub: lee SKILL.md, empaqueta los archivos de recursos y guarda el resultado localmente.

  1. Abre la aplicación y ve a Plugins → Habilidades.
  2. Elige «Instalar desde GitHub».
  3. Pega la URL de la carpeta de la habilidad que se muestra a continuación y confirma.
    https://github.com/d-padmanabhan/agent-engineering-handbook/tree/main/skills/cloudflare-workers-author
  4. Activa la habilidad en cada chat en el que quieras tenerla disponible.
Plugins → Habilidades → Añadir habilidad → URL de GitHub; después, pega la URL de la carpeta y pulsa Continuar.
2

Instalar en otro agente

Cualquier agente que lea el formato Agent Skills puede usar esta habilidad: copia la carpeta en el directorio de habilidades de ese agente.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/d-padmanabhan/agent-engineering-handbook.git /tmp/agent-engineering-handbook
mkdir -p .claude/skills
cp -r /tmp/agent-engineering-handbook/skills/cloudflare-workers-author .claude/skills/cloudflare-workers-author
Reinicia Claude Code después de copiarla para que detecte la nueva habilidad.

Úsala en TypingMind

Activa Cloudflare Workers Author en cualquier chat de TypingMind y el modelo se encargará del resto. Su nombre y descripción se incluyen en el prompt del sistema y, en cuanto una petición encaja con la habilidad, el modelo carga las instrucciones completas por sí solo. No tienes que invocarla manualmente y no consume tokens hasta que se utiliza.

El modelo carga Cloudflare Workers Author automáticamente en cuanto una petición es relevante para esa habilidad.

Funciona con cualquier modelo de IA

Las habilidades de IA son instrucciones en Markdown, no código específico de un proveedor, por lo que Cloudflare Workers Author no está vinculada al modelo para el que se creó. Instálala una sola vez en TypingMind y úsala con GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama o un modelo local que ejecutes tú, todo con tus propias claves API.

  • Se carga solo cuando se necesita

    El prompt del sistema solo incluye el nombre y la descripción. Las instrucciones se cargan con la primera petición que encaja con la habilidad, por lo que una habilidad que no se usa no supone ningún coste.

  • Cambia de modelo durante el chat

    Como la habilidad contiene instrucciones y no código, cambiar de modelo no impide que funcione: el nuevo modelo lee el mismo archivo SKILL.md.

Instrucciones de la habilidad

Este es el contenido de SKILL.md que carga el modelo. Léelo antes de instalar la habilidad: contiene instrucciones que tu modelo seguirá.

Cloudflare Workers Author

Companion rule: 401-cloudflare-workers.mdc (file-scoped to wrangler.{jsonc,toml,json} and common Worker entry-point names). The rule is the gate (non-negotiables); this skill is the workflow (how to actually build the Worker).

Voice: opinionated. Cloudflare Workers is a small, fast platform with a specific runtime model. Most production incidents come from treating it like a generic Node.js server (top-level await, mutable module state, unbounded loops, secrets in logs, public-URL Worker-to-Worker calls). The workflow below prevents those.


When to invoke this skill

Invoke when:

  • The user asks to build a new Cloudflare Worker, Durable Object, Workflow, Queue consumer, Cron Trigger, Email Worker, or Pages Function.
  • The user is adding routes / endpoints to an existing Worker.
  • The user asks "should I use KV / D1 / R2 / DO / Hyperdrive for this?" (the bindings-and-storage decision matrix is the answer).
  • The user is setting up testing for a Worker.
  • The user is configuring deployment (gradual rollouts, OIDC for GitHub Actions, secret rotation).
  • A PR review touches wrangler.jsonc, a Worker entry-point file, or a binding configuration.

Do NOT invoke for:

  • Cloudflare Pages static-site work (not Worker authoring). See cloud-platforms/references/cloudflare.md § Pages.
  • WAF rule authoring (use cloudflare-waf-author skill instead).
  • Generic JavaScript / TypeScript code that happens to be imported by a Worker - delegate to the typescript-javascript skill.

Pre-step: classify what you're building

Each Worker type has a different entry-point shape and different bindings emphasis. Ask the user which one if unclear - the wrong entry-point shape is a wrong-handler-signature bug that won't surface until deploy time.

TypeEntry pointMost common bindings
Default-export HTTP Workerexport default { async fetch(req, env, ctx) {...} } satisfies ExportedHandler<Env>KV, D1, R2, AI, Service Bindings
Named-entrypoint (RPC target)export default class extends WorkerEntrypoint { async myMethod() {...} }Same, called via Service Binding from another Worker
Durable Objectexport class Room extends DurableObject {...} + a default fetch handler that routes to DODO storage + KV / R2 for cold data
Workflowexport class MyWorkflow extends WorkflowEntrypoint { async run(event, step) {...} }KV, D1, R2, Service Bindings, AI
Queue consumerexport default { async queue(batch, env, ctx) {...} }D1, R2, Service Bindings, AI
Cron Triggerexport default { async scheduled(event, env, ctx) {...} }KV, D1, R2, Service Bindings
Email Workerexport default { async email(message, env, ctx) {...} }R2 for attachments, D1 for logs
Pages Functionexport const onRequest: PagesFunction<Env> = async (ctx) => {...} (in functions/[[path]].ts)KV, D1, R2 (subset of full Worker bindings)

The six-step workflow

Step 1 - Bootstrap the project

If this is a new Worker (no existing wrangler.jsonc), follow references/project-bootstrap.md to get a minimal Module Workers project with:

  • wrangler.jsonc (the modern config format - JSONC with comments; recommended by Cloudflare since Wrangler v3.91.0)
  • package.json with wrangler, typescript, and a types script that runs wrangler types
  • tsconfig.json with strict mode, ESNext target, "types": [], and the generated worker-configuration.d.ts in include
  • src/worker.ts with the generated Env type (do not hand-author it) and satisfies ExportedHandler<Env>
  • .dev.vars in .gitignore; worker-configuration.d.ts generated by wrangler types

[!IMPORTANT] wrangler types now generates the Workers runtime types and supersedes @cloudflare/workers-types. Current Wrangler (4.9x+) prints this on every wrangler types run and tells you to uninstall @cloudflare/workers-types and remove it from tsconfig.json. The generated worker-configuration.d.ts provides both the global Env (from vars + declared secrets) and the runtime globals (Request, Response, ExecutionContext, ExportedHandler, etc.), pinned to your compatibility_date. So: no @cloudflare/workers-types dependency, "types": [] in tsconfig.json, and worker-configuration.d.ts in include. Declare expected secrets under secrets.required in wrangler.jsonc so they appear in the generated Env. Vars are typed as their literal values by default; run wrangler types --strict-vars=false to type them as string when a var's value varies by environment.

If the user already has a Worker, read their existing wrangler.jsonc before suggesting changes. Don't propose a fresh structure that conflicts with their conventions.

Step 2 - Choose bindings and storage

This is the most consequential design decision in any new Worker. Pick wrong and you'll be migrating data in six months. The full decision matrix is in references/bindings-and-storage.md; the headline:

NeedUseDon't use
Session / config / feature flag (small, eventually consistent, low write)KVD1, R2
Relational queries, transactions, joins (single-region, SQLite scale)D1KV
File / blob storage (any size; metadata + body)R2KV (25 MB value limit)
Strongly-consistent coordination (sessions, rate limits, websocket fan-out)Durable ObjectKV (eventually consistent), D1 (single-region, not strongly consistent across Workers)
Connection pooling to existing Postgres / MySQLHyperdriveDirect TCP (works but no pooling)
Job queues, dead-letter, batchingQueuesManual KV-based queue
LLM inferenceWorkers AI behind AI Gateway (cost cap + caching + observability)Direct provider API calls
Vector searchVectorizeKV with embedding lookups (no ANN index)

Document the choice in the PR description with the rejected alternatives and why.

Step 3 - Route requests

Pick a router based on complexity:

ComplexityChoiceWhy
1-3 routes, no middlewareNative URL + switchZero deps, smallest bundle
Many routes, middleware, typed envHono (de facto)Typed, fast, designed for edge runtimes, OpenAPI integration available
Worker-to-Worker calls onlyRPC via WorkerEntrypointNo HTTP overhead, typed arguments and return values, faster than HTTP service bindings
GraphQLGraphQL Yoga + HonoYoga has a Workers adapter

For Hono patterns (typed env via Hono<{ Bindings: Env, Variables: ... }>, middleware, error boundaries, OpenAPI) and RPC patterns (when to use, named entrypoints, lifecycle), see references/hono-patterns.md.

Step 4 - Test

The canonical testing path is @cloudflare/vitest-plugin v1+ with Vitest 4.1+. It runs tests inside the Workers runtime via Miniflare, with bindings mocked or real (your choice), HMR for fast reruns, and isolated per-test storage.

See references/testing-with-vitest-pool.md for setup details. The pattern:

  • vitest.config.ts registers the cloudflareTest() Vite plugin (exported from @cloudflare/vitest-plugin) inside a standard defineConfig from vitest/config, pointing at your wrangler.jsonc
  • tsconfig.json for tests includes "@cloudflare/vitest-plugin/types" in types (declares the cloudflare:test module)
  • Unit tests: import the handler, call worker.fetch(request, env, ctx) directly with mocked env
  • Integration tests: use SELF.fetch() from cloudflare:test (in-process) or auxiliary Workers (fresh isolate)

[!IMPORTANT] Cloudflare renamed @cloudflare/vitest-pool-workers to @cloudflare/vitest-plugin in v1. Migrate the dependency, package imports, and TypeScript types entry. The configuration API remains cloudflareTest({ wrangler: { configPath: "./wrangler.jsonc" } }) inside plugins in a vitest/config defineConfig; do not restore the removed defineWorkersConfig helper.

Reject in review: new tests using unstable_dev or the renamed @cloudflare/vitest-pool-workers package.

Step 5 - Deploy and roll out gradually

Workers supports two deployment models:

  • Standard deploy (wrangler deploy) - upload and immediately serve 100% from the new version. Fine for low-risk changes.
  • Gradual deployment (wrangler versions upload then wrangler versions deploy) - upload as a new version without serving traffic, split traffic between old and new, then promote to 100%. Required for production HTTP Workers serving customer traffic.

Headline commands:

bash
# Upload new version without deploying
wrangler versions upload

# Interactive split (prompts for percentages)
wrangler versions deploy

# Non-interactive: 90% old, 10% new
wrangler versions deploy <old-version-id>@90 <new-version-id>@10

# Promote to 100%
wrangler versions deploy <new-version-id>@100

Smoke-test a specific version in production via the Cloudflare-Workers-Version-Overrides request header (the version override applies even when its percentage is 0%).

For CI integration (OIDC trust for GitHub Actions instead of long-lived API tokens), secret rotation, and the canary-then-promote pattern, see references/deployment-and-versions.md.

Step 6 - Verify and ship

Before merge:

  • wrangler types regenerated; worker-configuration.d.ts matches wrangler.jsonc
  • tsc --noEmit clean
  • wrangler deploy --dry-run clean (catches binding misconfigurations)
  • @cloudflare/vitest-plugin tests pass
  • PR description names the rejected storage alternatives and why
  • PR description names the soak plan for the gradual rollout (e.g., "10% for 1h, then 50% for 1h, then 100%")
  • Reviewer checklist from 401-cloudflare-workers.mdc ticked

Self-check before submitting

The high-leverage subset of the 401-cloudflare-workers.mdc reviewer checklist:

  • Module Workers syntax (export default {...} or class extends WorkerEntrypoint); no addEventListener("fetch", ...)
  • Env interface imported from generated worker-configuration.d.ts; satisfies ExportedHandler<Env> on the default export
  • No secrets in console.log, error messages, response bodies, or thrown errors
  • All fire-and-forget async work wrapped in ctx.waitUntil()
  • Cloudflare resources declared as bindings (not env vars); Worker-to-Worker calls use Service Bindings + RPC (not public URLs)
  • Subrequest budget considered; loops use batching where the API supports it (D1 batch(), etc.)
  • No top-level await, no module-scope mutable state, no module-scope fetch()
  • compatibility_date set; compatibility_flags minimal and justified
  • wrangler.jsonc is source of truth; deployment from CI (not Dashboard "Edit code")
  • Tests use @cloudflare/vitest-plugin (not deprecated unstable_dev)

See references/common-pitfalls.md for the full list of failure modes observed across many Workers teams, organized by symptom (cold-start regressions, intermittent state pollution, secret leaks, subrequest budget exhaustion, deployment drift).


Related

  • 401-cloudflare-workers.mdc - the rule (file-scoped non-negotiables)
  • 400-cloudflare.mdc - broader Cloudflare platform playbook
  • 405-cloudflare-waf-rules.mdc - file-scoped WAF rule playbook
  • cloud-platforms skill - cross-cloud platform patterns
  • cloudflare-waf-author skill - WAF rule authoring workflow companion
  • skills/typescript-javascript - general TypeScript / JavaScript patterns

Archivos incluidos

El modelo los lee según los necesita mientras la habilidad está cargada. Son archivos de solo lectura y nunca se ejecutan.

Preguntas frecuentes

¿Qué hace la habilidad de IA Cloudflare Workers Author?

Workflow for building production-grade Cloudflare Workers in TypeScript - bootstrap, bindings and storage choice, routing (Hono + RPC via WorkerEntrypoint), testing with @cloudflare/vitest-plugin, gradual deployments, and common pitfalls. Use when adding a new Worker, adding endpoints to an existing Worker, choosing between KV / R2 / D1 / Durable Objects / Hyperdrive, setting up testing, configuring deployment, or reviewing a Worker PR.

¿Por qué usar Cloudflare Workers Author en TypingMind?

Porque la instalas una vez y la usas con cualquier modelo. Cloudflare Workers Author está escrita en Markdown, no en código específico de un proveedor, por lo que la misma habilidad funciona con GPT-5, Claude, Gemini, Grok o un modelo local, y puedes cambiar de modelo en mitad del chat sin que deje de funcionar. TypingMind utiliza tus propias claves API, de modo que pagas directamente a los proveedores en lugar de pagar una suscripción por puesto, y tus habilidades y chats permanecen en tu propio almacenamiento.

¿Cómo instalo Cloudflare Workers Author en TypingMind?

Abre Plugins → Habilidades → Instalar desde GitHub en TypingMind y pega https://github.com/d-padmanabhan/agent-engineering-handbook/tree/main/skills/cloudflare-workers-author. TypingMind lee el archivo SKILL.md de esa carpeta, empaqueta los archivos de la carpeta e instala el conjunto como una habilidad que puedes activar en cada chat.

¿Qué modelos de IA pueden usar Cloudflare Workers Author?

Cualquier modelo que conectes en TypingMind. Las habilidades de IA son instrucciones en Markdown, no código específico de un proveedor, por lo que GPT, Claude, Gemini, Grok y los modelos locales pueden cargar esta habilidad cuando una solicitud se corresponda con ella.

¿Con cuántos modelos de IA puedo usar Cloudflare Workers Author?

Con tantos como quieras. Siempre que un modelo admita habilidades, puedes usar Cloudflare Workers Author con él: GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama y muchos más, todos en TypingMind con tus propias claves API.

¿Es gratuita la habilidad de IA Cloudflare Workers Author?

Sí. d-padmanabhan la ha publicado en GitHub bajo la licencia MIT. Solo pagas a tu proveedor de IA por los tokens que utilizas.

¿Qué son las habilidades de IA?

Una habilidad de IA es un conjunto de instrucciones reutilizables que enseña a un modelo de IA a realizar una tarea concreta. Sigue el formato abierto Agent Skills: un archivo SKILL.md con un nombre y una descripción, además de los scripts, plantillas o archivos de referencia que pueda necesitar el modelo. El modelo solo lee las instrucciones cuando tu solicitud se corresponde con la habilidad, por lo que una habilidad instalada no supone ningún coste hasta que se utiliza.

¿En qué se diferencian las habilidades de IA de los plugins o los servidores MCP?

Un plugin o un servidor MCP proporciona al modelo nuevas herramientas que puede invocar: código que se ejecuta en algún lugar y devuelve un resultado. En cambio, una habilidad de IA aporta conocimientos y procedimientos al modelo: cómo abordar una tarea, qué pasos seguir y qué se considera un buen resultado. Las habilidades son instrucciones en Markdown, por lo que no necesitan servidor, clave API ni entorno de ejecución, y funcionan con cualquier modelo.

Ver el directorio

Crea ya tu propio espacio de trabajo con IA

Suscríbete a nuestro boletín para recibir avisos sobre nuevas funciones y próximos sorteos 👇