Cloudflare Workers
Overview
Cloudflare Workers runs code at the edge in V8 isolates, with cold starts measured in low milliseconds. Workers pairs with storage and compute services: KV (eventually-consistent key-value cache), D1 (serverless SQLite), R2 (S3-compatible object storage with no egress fees), Durable Objects (strongly consistent, single-instance state), and Queues (message queues for background work). The CLI is Wrangler; configuration lives in wrangler.jsonc (or the older wrangler.toml).
Instructions
- Scaffold a new Worker with
npm create cloudflare@latest -- my-worker (the create-cloudflare CLI, "C3"). wrangler init still exists but C3 is what Cloudflare's own quickstart uses now.
- Write the Worker as an ES Module:
export default { async fetch(request, env, ctx) { ... } }. The older Service Worker syntax (addEventListener('fetch', ...)) still runs but is not recommended for new code.
- Always set
compatibility_date in wrangler.jsonc to pin runtime behavior to a known date; bump it deliberately when you want newer defaults.
- For storage, prefer D1 for relational/SQL data, KV for simple read-heavy key-value caching, R2 for object storage, and Durable Objects when you need a single strongly-consistent instance coordinating state (e.g. a WebSocket room or a rate limiter).
- Run
wrangler dev for local development; it simulates KV/D1/R2 locally by default and only touches real remote resources when you pass --remote.
- Deploy with
wrangler deploy. Routes, bindings and build settings live in wrangler.jsonc.
- Store secrets with
wrangler secret put SECRET_NAME (interactive prompt) — never put them in wrangler.jsonc. Type all bindings with an Env interface (TypeScript) generated by wrangler types.
- Create a KV namespace with
wrangler kv namespace create <BINDING_NAME> and copy the returned id into kv_namespaces in wrangler.jsonc. Create a D1 database with wrangler d1 create <NAME> and apply schema with wrangler d1 migrations apply <NAME>.
- For caching, use the Cache API (
caches.default), and for heavier HTML rewriting use HTMLRewriter. Use ctx.waitUntil() for fire-and-forget async work (analytics, logging) that should not block the response.
- Tail live logs with
wrangler tail.
Examples
Example 1: Edge API with KV caching
User request: "Set up a Cloudflare Worker that serves cached API responses from KV."
npm create cloudflare@latest -- product-cache-api
cd product-cache-api
npx wrangler kv namespace create PRODUCT_CACHE
// wrangler.jsonc
{
"name": "product-cache-api",
"main": "src/index.ts",
"compatibility_date": "2026-09-23",
"kv_namespaces": [
{ "binding": "PRODUCT_CACHE", "id": "a1b2c3d4e5f64a7b8c9d0e1f2a3b4c5d" }
]
}
// src/index.ts
export interface Env {
PRODUCT_CACHE: KVNamespace;
}
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const url = new URL(request.url);
const sku = url.searchParams.get("sku");
if (!sku) return new Response("Missing sku", { status: 400 });
const cached = await env.PRODUCT_CACHE.get(sku);
if (cached) return new Response(cached, { headers: { "Cache-Control": "public, max-age=60" } });
const upstream = await fetch(`https://api.internal.example/products/${sku}`);
const body = await upstream.text();
await env.PRODUCT_CACHE.put(sku, body, { expirationTtl: 300 });
return new Response(body, { headers: { "Cache-Control": "public, max-age=60" } });
},
};
npx wrangler dev # local, simulated KV
npx wrangler deploy
Output: a Worker that checks KV for a cached product, falls back to the origin API, and caches the result for five minutes.
Example 2: Scheduled sync into D1
User request: "Build a Worker that runs on a schedule to sync inventory counts from an external API into D1."
npx wrangler d1 create inventory-db
npx wrangler d1 migrations create inventory-db create_inventory_table
# edit the generated migration SQL, then:
npx wrangler d1 migrations apply inventory-db --remote
{
"d1_databases": [
{ "binding": "DB", "database_name": "inventory-db", "database_id": "7f3e9c21-4b8a-4d6e-9f12-5a6b7c8d9e0f" }
],
"triggers": { "crons": ["0 * * * *"] }
}
export default {
async scheduled(event: ScheduledEvent, env: Env, ctx: ExecutionContext) {
const res = await fetch("https://api.internal.example/inventory/snapshot");
const items: { sku: string; count: number }[] = await res.json();
const stmt = env.DB.prepare("INSERT OR REPLACE INTO inventory (sku, count) VALUES (?, ?)");
await env.DB.batch(items.map((i) => stmt.bind(i.sku, i.count)));
ctx.waitUntil(fetch("https://api.internal.example/sync/ack", { method: "POST" }));
},
};
Output: a cron-triggered Worker (hourly) that refreshes a D1 inventory table from an upstream API.
Guidelines
wrangler.jsonc is now the format Cloudflare recommends for new projects; some newer Wrangler features are JSON-only. wrangler.toml still works but migrate when convenient.
- Use ES Module syntax over Service Worker syntax for new Workers.
- Type every environment binding with an
Env interface; run wrangler types to regenerate it after changing bindings.
- Handle errors with explicit HTTP status codes instead of letting exceptions produce an unhandled-error page.
- Prefer D1 for relational data; use KV only for simple, read-heavy caching where eventual consistency is acceptable.
wrangler dev without --remote simulates storage locally — don't assume local test data exists in production, or vice versa.
- Secrets set with
wrangler secret put are per-environment; re-run it for staging and production separately if you use multiple environments.