Back to DocsRecipe

Cloudflare Workers Primer

Deploy serverless functions at the edge with zero cold starts. Workers run on Cloudflare's global network, intercepting requests before they reach your origin.

Why Workers?

Workers execute JavaScript in V8 isolates — not containers. This means sub-millisecond cold starts and pricing based on CPU time, not wall-clock duration. Perfect for API gateways, A/B routing, auth checks, and HTML rewriting at the edge.

Project Setup

npm create cloudflare@latest my-worker
cd my-worker
npx wrangler dev

Wrangler is Cloudflare's CLI. It handles bundling, preview, and deployment with a single command.

First Handler

export default {
  async fetch(request, env, ctx) {
    return new Response("Hello edge!", {
      headers: { "content-type": "text/plain" },
    });
  },
};

Every Worker exports a default object with a fetch handler. The runtime passes the incoming Request, bindings, and execution context.

Bindings & KV

Bindings inject resources into your Worker at runtime — KV namespaces, R2 buckets, D1 databases, secrets, and environment variables. Define them in wrangler.toml and access them via env.

// wrangler.toml
[[kv_namespaces]]
binding = "CACHE"
id = "abc123"

// Worker
const val = await env.CACHE.get("key");

Deploy

npx wrangler deploy

Your Worker is live on a workers.dev subdomain in under 30 seconds. Attach a custom domain via the Cloudflare dashboard.