DevOps & Tools
Build full-stack apps on Cloudflare Workers, from runtime basics to storage, AI and security.
A path through the Cloudflare developer platform: the Workers runtime and tooling, then the storage products (KV, R2, D1, Durable Objects, Queues), AI services, media, email, and the security and integration patterns that tie them together. It suits JavaScript developers who want to ship serverless apps at the edge. Each subject links the official Cloudflare documentation.
The subjects follow the roadmap.sh Cloudflare roadmap.
Cloudflare Workers are JavaScript running on web-standard APIs, deployed from a terminal and usually from a Git repository. Get comfortable with the language, the shell and HTTP first; everything on the platform is built on top of them.
Modules, async/await, promises, destructuring and classes. Workers are ES modules exporting a default object with handlers, so modern syntax and promise handling come up in every file.
Moving around directories, running npm and npx, setting environment variables and reading command output. Wrangler, the main tool for Workers, is entirely a CLI.
Methods, status codes, headers, caching directives, cookies, CORS and TLS. A Worker sits directly in the request path, so you handle these by hand rather than through a framework.
Commit, branch, merge and push. Workers Builds and Pages deploy straight from a connected GitHub or GitLab repository, creating preview URLs per branch.
The working toolkit for Workers projects: the npm ecosystem for dependencies and tooling, TypeScript for typed bindings, and a mental model of serverless code running in hundreds of locations close to the user.
Node runs Wrangler and your build locally, and npm installs packages. Workers are not Node, but the nodejs_compat flag provides many Node built-ins such as Buffer and node:crypto.
Types, interfaces and generics. Run wrangler types to generate an Env interface from your config so bindings like KV namespaces and D1 databases are typed in your handlers.
Code runs per request or event with no servers to manage, billed by usage. Design for statelessness, short CPU budgets and external storage, and push long work into queues or workflows.
Running code in the data centre nearest each visitor cuts latency, but your database may still sit in one region. Smart Placement can move a Worker closer to its backend when that wins.
The Workers runtime (open-sourced as workerd) runs your code inside V8 isolates and exposes web-standard APIs instead of Node's. A Worker exports handlers such as fetch, scheduled and queue, receives bindings on env, and has CPU-time and memory limits you need to design around.
The fetch(request, env, ctx) handler receives a standard Request and returns a Response. Bodies are streams that can be read once, so use request.clone() if two consumers need them.
Outbound fetch() for subrequests plus Web Crypto, Streams, URL, TextEncoder, WebSockets and HTMLRewriter. Subrequests per invocation are capped, so batch or fan out with care.
An isolate is created on demand, reused for many requests and evicted at any time, so global state is a cache, never a store. ctx.waitUntil() keeps work like logging alive after the response is sent.
Choose between CDN caching via Cache-Control and cf fetch options, the per-data-centre Cache API, and globally replicated KV. Pick by how fresh data must be and whether it must be shared across locations.
Wrap handlers for auth, CORS, logging and error handling, either by composing functions or with a router's middleware chain such as Hono's app.use(). Keep the order explicit: auth before business logic, error capture outermost.
A single fetch handler quickly grows a pile of if statements on url.pathname. A small router built for Workers adds path params, method matching and middleware with almost no bundle cost.
A fast, typed web framework built on web standards that runs on Workers, Deno, Bun and Node. Offers routing, middleware, validators and typed bindings through new Hono<{ Bindings: Env }>().
A tiny router of under a kilobyte with a chainable API and helpers like json() and error(). A good fit when you want routing and nothing else.
Workers can serve static assets and server-render full-stack apps. Framework adapters build your app into a Worker plus an assets directory, so the same deployment handles pages, APIs and bindings.
React Router, Next.js (through the OpenNext adapter), Astro, SvelteKit, Nuxt and others deploy to Workers. Start with npm create cloudflare@latest and pick the framework template.
Projects are configured in wrangler.jsonc (or wrangler.toml), developed locally with wrangler dev, and shipped with wrangler deploy or through Git-connected builds. Use environments and versions to keep staging separate and roll out gradually.
The CLI for everything: wrangler dev, wrangler deploy, wrangler tail for live logs, wrangler secret put, and subcommands for KV, R2, D1 and Queues. Its config file declares bindings, routes and compatibility date.
During wrangler dev, press d to open Chrome DevTools attached to your Worker for breakpoints, console output, CPU profiles and memory snapshots.
Either connect the repo to Workers Builds for automatic deploys and preview URLs, or run wrangler deploy from GitHub Actions with an API token scoped to Workers. Apply D1 migrations as a separate step before deploying.
KV is a globally replicated key-value store optimised for many reads and relatively few writes. Writes can take up to about a minute to reach every location, so use it for config, sessions, flags and cached content — not for counters or anything needing strong consistency.
env.KV.get(key, "json"), put(key, value, { expirationTtl }), delete(key) and list({ prefix, cursor }). Values can be strings, JSON, ArrayBuffer or streams up to 25 MiB.
Bindings attach resources to a Worker through config, appearing as properties on env. They need no credentials in code, and the same pattern covers KV, R2, D1, Queues, AI and other Workers.
Attach up to 1 KB of JSON metadata to a key on put, read it with getWithMetadata, and get it for free from list(). Handy for storing timestamps or content types without fetching the value.
Write or delete up to 10,000 keys in one request with wrangler kv bulk put or the REST API, and read several keys at once by passing an array to get. Use these for seeding and migrations.
Cache-aside in front of a slow origin: read KV, fall back to the origin, then write back with a TTL via ctx.waitUntil. The cacheTtl option on get also keeps hot keys in the local data centre longer.
R2 is S3-compatible object storage with no egress fees. Access it from Workers through a binding or from anywhere through the S3 API, which makes it a natural home for uploads, media, backups and build artefacts.
Flat buckets of objects addressed by key, each with a body plus HTTP and custom metadata. Not a file system: "folders" are just key prefixes and listing is by prefix.
env.BUCKET.put, get (with ranges and conditional headers), head, delete and list. Create buckets with wrangler r2 bucket create and set CORS rules before browsers upload directly.
Stream bodies instead of buffering them to stay within Worker memory, use multipart uploads for big files, or hand clients presigned S3 URLs so uploads bypass your Worker entirely.
Serve user uploads and media publicly through a custom domain on the bucket so the CDN caches them, or privately through a Worker that checks auth first. Use content-addressed keys for long cache lifetimes.
Lifecycle rules delete objects or move them to Infrequent Access after a number of days, and abort stale multipart uploads. Set them for temp uploads and logs so storage does not grow forever.
D1 is Cloudflare's serverless SQL database built on SQLite. Each database lives in one primary location with optional read replicas, is queried through a binding with prepared statements, and fits the many-small-databases pattern well, such as one per tenant.
Plain SQLite DDL: tables, indexes, foreign keys (enforced by default) and STRICT tables. Keep the schema in version control and change it only through migrations.
Numbered SQL files created with wrangler d1 migrations create and applied with wrangler d1 migrations apply, using --local or --remote. Applied migrations are tracked in a table inside the database.
Index the columns you filter and join on, check plans with EXPLAIN QUERY PLAN, and use db.batch() to send several statements in one round trip. Billing counts rows read, so full scans cost money as well as time.
A lightweight TypeScript ORM with a D1 driver. Define tables in TS, generate SQL migrations with drizzle-kit, and get typed queries without a heavy runtime.
Prisma ORM can talk to D1 through its driver adapter, giving you the Prisma schema and typed client on Workers. Migrations are generated as SQL and applied with Wrangler.
Queues decouple work from the request: a producer Worker sends messages through a binding and a consumer Worker receives them in batches with automatic retries. Delivery is at least once, so consumers must be idempotent.
The queue(batch, env, ctx) handler receives up to a configured batch size; call msg.ack() or msg.retry({ delaySeconds }) per message, or let a thrown error retry the whole batch.
Send emails, resize images or call slow APIs from a consumer instead of the request path. Use ctx.waitUntil only for short fire-and-forget work; anything that must not be lost belongs in a queue.
After max_retries, failed messages move to a configured dead letter queue instead of disappearing. Alert on it and give it its own consumer to inspect or replay messages.
A Durable Object is a single-threaded instance with its own strongly consistent storage, addressed by name or ID, that lives in one location. It is the tool for coordination on Workers: chat rooms, rate limiters, collaborative documents and anything needing one source of truth.
Keep hot state in instance fields and persist anything important to storage, since the object can be evicted when idle. Name objects by the thing they own, such as idFromName(roomId).
All requests for one object are processed by a single thread, so locking disappears. Use objects to serialise access, fan out WebSocket messages (with hibernation to save cost) and schedule work with alarms.
Each object has private storage: a key-value API and, for SQLite-backed objects, ctx.storage.sql for real SQL queries. Data survives restarts and is co-located with the code for very fast access.
Writes made without awaiting in between are coalesced atomically, and ctx.storage.transaction() or transactionSync() group reads and writes explicitly. Input and output gates prevent races while storage calls are in flight.
Workflows are durable multi-step programs on Workers: each step.do() result is persisted and retried on failure, and step.sleep() can pause for hours or days without holding compute. Use them for onboarding sequences, data pipelines and anything that must survive failures midway.
Workers AI runs open models on Cloudflare's GPUs through an AI binding: env.AI.run(model, input). You pay per use with no infrastructure, and the catalogue covers text, embeddings, images, speech and classification.
Chat and completion with open LLMs such as Llama and Mistral variants, using messages input and optional stream: true for server-sent tokens. Some models support function calling and JSON mode.
Text-to-image generation, image classification, object detection and image-to-text models. Inputs and outputs are bytes, so pass Uint8Array data and return images with the right content type.
Whisper-family models transcribe audio to text, with timestamps on some variants. Upload audio as bytes; long recordings should be split into chunks to fit request limits.
Call models from your Worker through the binding, the REST API, or the OpenAI-compatible endpoints, and route calls through AI Gateway for caching and logs. LoRA adapters let you serve fine-tuned variants of some models.
Vectorize is a globally distributed vector database for Workers. Store embeddings with metadata, query by similarity, and combine it with Workers AI embeddings to build semantic search and retrieval-augmented generation without leaving the platform.
Numeric vectors that place similar content close together. Create an index with the embedding model's dimensions and metric (cosine, euclidean or dot-product), and use the same model for documents and queries.
env.VECTORIZE.query(vector, { topK, filter, returnMetadata }) returns the nearest matches. Create metadata indexes for fields you filter on, and store an ID that points back to the source record.
Embed the query with Workers AI, search Vectorize, then pass the top passages to an LLM as context. AutoRAG packages this pipeline as a managed service if you would rather not build it.
Stream is a managed video platform: upload or record, and Cloudflare handles encoding, storage and adaptive delivery. You get HLS/DASH manifests and an embeddable player instead of running your own transcoding pipeline.
Play through the Stream player iframe or your own player using the HLS or DASH URL. Signed URLs or tokens restrict who can watch, and pricing is per minute stored and delivered.
Push RTMPS or SRT from OBS or an encoder to a live input, and viewers watch with low latency. Recordings can be saved automatically and replayed like regular videos.
Uploads are transcoded into multiple renditions automatically. You can also generate thumbnails, clip videos, add captions and use direct creator uploads so users upload straight to Stream.
Cloudflare Images stores, resizes and optimises images, serving AVIF or WebP depending on the browser. Define variants for common sizes, or transform any image on the fly through /cdn-cgi/image/ URLs or the cf.image option in a Worker fetch.
Calls, now part of Cloudflare Realtime, is a WebRTC selective forwarding unit running on Cloudflare's network, with a TURN service for clients behind strict NATs. You build the signalling and app logic; it routes audio, video and data tracks between participants.
Cloudflare Tunnel runs the cloudflared daemon next to a private service and opens outbound-only connections to Cloudflare, so you can publish it on a hostname without opening inbound ports. Combine it with Access to put a login in front.
Email Routing receives mail for your domain, and an Email Worker can process each message with an email(message, env, ctx) handler: forward it, reply, reject it, or parse it and act on its contents.
Map addresses to destinations in Email Routing rules, with a catch-all for everything else. Send a rule to a Worker to decide per message and call message.forward(address) to a verified destination.
Read message.from, message.to, headers and the raw MIME stream, parse it with a library such as postal-mime, and store attachments in R2 or push events to a queue.
Drop or bounce unwanted mail with message.setReject(reason) based on sender allowlists, header checks or content rules before it is forwarded anywhere.
AI Gateway is a proxy in front of AI providers (OpenAI, Anthropic, Workers AI and others). Changing the base URL gives you logging, caching, rate limiting, retries and fallbacks between models, plus cost analytics across providers.
Browser Rendering runs headless Chrome on Cloudflare so a Worker can take screenshots, render PDFs or scrape JavaScript-heavy pages through a Puppeteer or Playwright binding or simple REST endpoints. Reuse sessions where possible, since browsers are the expensive part.
Workers sit in front of your origin, which makes them a natural place for security controls and speed-ups: setting headers, rate limiting, caching, rewriting HTML and filtering bots. Know the isolation model so you understand what the platform protects and what remains your job.
Each Worker is isolated from others in memory, timers are coarsened against side-channel attacks, and secrets are injected as bindings. Your code is still responsible for validating input and authenticating callers.
Instead of a container per function, many V8 isolates share one process, so cold starts are a few milliseconds and memory overhead is small. The trade-off is no native binaries and a 128 MB memory limit per isolate.
Add Content-Security-Policy, Strict-Transport-Security, X-Content-Type-Options and Referrer-Policy to responses in a Worker, or with Transform Rules if no code is needed.
Use the Rate Limiting binding for per-key limits inside a Worker, WAF rate limiting rules to block abusive IPs before your code runs, or a Durable Object when you need exact, strongly consistent counts.
caches.default.match() and put() store responses in the current data centre only; nothing is replicated globally. Use it for computed responses and remember it is not available on workers.dev hostnames.
HTMLRewriter streams HTML through CSS-selector handlers so you can inject scripts, rewrite links or personalise pages without buffering the whole document.
Cloudflare terminates TLS at the edge with automatically issued certificates. Set the encryption mode to Full (strict) so traffic to the origin is encrypted and validated too.
Bot Fight Mode, Turnstile challenges and, on Enterprise plans, a bot score per request exposed to Workers as request.cf.botManagement. Use Turnstile on forms instead of CAPTCHAs.
Real systems are several Workers plus third-party services. Cloudflare provides zero-latency calls between Workers, triggers from cron, queues and email, and the fetch API for everything outside, so you can split responsibilities without adding network hops.
File-based routing for Cloudflare Pages: files under /functions become Worker handlers next to your static site. New projects are generally better served by Workers with static assets.
Bind one Worker to another and call it through env.AUTH.fetch() or typed RPC methods on a WorkerEntrypoint class. Calls skip the public internet and add no extra request billing.
Choose RPC through service bindings for synchronous calls, Queues for asynchronous hand-offs, and Durable Objects for shared state. Avoid calling your own Worker over its public URL.
Call third-party APIs with fetch, store keys with wrangler secret put, set timeouts with AbortSignal.timeout(), and cache responses where the API allows to save quota.
Verify signatures with Web Crypto (crypto.subtle.verify on the raw body), respond quickly with 2xx, and push the real work to a queue so provider retries do not cause duplicate processing.
Workers react to more than HTTP: cron triggers, queue messages, R2 event notifications, email and Workflows. Model the system as producers and consumers so parts can fail and retry independently.
Local development, testing and observability for Workers. Everything runs on the open-source workerd runtime locally, so tests and wrangler dev behave like production, and the dashboard plus wrangler tail show what happens after deploy.
The local simulator behind wrangler dev and the Vitest integration, with local KV, R2, D1, Queues and Durable Objects. Use its API directly only for custom test setups.
Chrome DevTools work locally and against deployed Workers for profiling CPU time, inspecting heap snapshots and stepping through code. Profile before optimising; CPU time is what you are billed for.
@cloudflare/vitest-pool-workers runs Vitest tests inside the Workers runtime with real bindings and isolated storage per test. Use SELF.fetch() for integration tests and call handlers directly for unit tests.
Enable Workers Logs in config to keep console.log output searchable in the dashboard, stream live logs with wrangler tail, and log structured JSON so you can filter by fields.
Dashboard metrics for requests, errors and CPU time, Logpush to send logs to your own storage or SIEM, and OpenTelemetry export to external tools. Set notifications for error spikes.
Reproduce locally with wrangler dev --remote when you need real resources, read exceptions in wrangler tail, and check the compatibility date and flags when behaviour differs between local and deployed.