Production-Ready on Cloudflare: the complete guide

By

Tagged: Cloudflare

The complete free handbook to shipping and operating production apps on Cloudflare: Workers, Static Assets, Wrangler 4, Local Explorer, D1, KV, R2, Queues, Durable Objects, Turnstile, Email Service, observability, gradual deploys, and rollbacks.

AI coding agents can generate a working web application in an afternoon. That part is solved. The hard part now is operating that app once real people, bots, bad migrations, and traffic spikes hit it.

This handbook replaces my older free Cloudflare courses. Everything you need to build, test, deploy, observe, and recover real products on the Cloudflare stack lives on this page, with no signups and no paywall.

I run several production properties on Cloudflare every day, including this blog (flaviocopes.com), my Mac app support portal (support.flaviocopes.com), and my app update server (updates.flaviocopes.com). Every command, query plan, bundle size, trace, and screenshot in this guide comes from running a real Worker application (pulsewatch, an uptime and incident monitor) locally on Wrangler 4.167 and from the production setups I maintain.

Find your way around this guide

This is a long reference handbook. Jump straight to the part you need:

If you want toJump to
Understand the 2027 Cloudflare mental model and what to skipThe 2027 Cloudflare mental model, The default stack map
Master DNS, TLS, caching, and edge securityDNS, TLS, caching, and edge security
Set up a real project with wrangler.jsonc and environmentsProject setup, wrangler.jsonc, and environments
Run locally and debug with Local ExplorerLocal development and Local Explorer
Understand the Workers runtime, Hono, and static asset routingWorkers runtime, Hono, and static assets
Pick between D1, KV, R2, Durable Objects, and HyperdriveChoosing the right storage
Run D1 safely with migrations, indexes, and Time TravelD1 in production
Use KV and R2 without hitting consistency or memory trapsKV and R2 in production
Move work off the request path with waitUntil, Cron, Queues, and WorkflowsBackground work and scheduling
Coordinate real-time state with Durable ObjectsDurable Objects and when to skip them
Lock down auth, Turnstile, rate limits, webhooks, and TunnelsAuth, bots, abuse, and edge security
Send and receive transactional email nativelyTransactional email on Cloudflare
Add AI features with strict cost capsAI on Cloudflare without runaway bills
Write real workerd tests and read production tracesTesting and observability
Ship with CI/CD, gradual rollouts, rollbacks, and cost guardrailsCI/CD, gradual deployments, and rollbacks
Debug live traffic, manage secrets, and prevent billing spikesProduction debugging, cost control, and Wrangler workflows
Practice the full stack with 10 progressive exercisesHands-on Cloudflare exercises
See real production lessons and a pre-launch checklistWhat I run in production, Pre-launch checklist and cheat sheet

The 2027 Cloudflare mental model

Cloudflare started as a CDN and reverse proxy. Every piece of the developer platform still sits on that foundation.

When a browser requests your domain, it connects to a nearby Cloudflare data center announced worldwide via anycast. Cloudflare terminates TLS at the edge, runs security checks, serves cached or static files directly, and only wakes your JavaScript when a route needs dynamic logic.

You can see that edge layer on any proxied site with curl -I:

curl -sI https://flaviocopes.com | grep -iE '^(http/|server|cf-|cache-control)'

Here is the real response from this site:

HTTP/2 200
content-type: text/html; charset=utf-8
cache-control: public, max-age=0, must-revalidate
server: cloudflare
cf-cache-status: DYNAMIC
cf-ray: a5f69b81197cedda-MXP

The cf-ray suffix (MXP) shows which Cloudflare data center answered the request (Milan). Everything you build on Cloudflare lives inside that network boundary.

Isolates, not long-running servers

Cloudflare Workers run on workerd, an open-source V8 isolate runtime. Your code does not boot a virtual machine or a persistent Node.js server process.

That difference causes most of the bugs AI coding agents introduce when they scaffold a Cloudflare app:

  • No reliable in-memory state between requests. Module-level caches or Maps can vanish on the next request, or worse, leak request-scoped data across users sharing an isolate.
  • No dangling background work. On a Node server, firing a fetch() without await keeps running after the response finishes. On a Worker, the runtime can cancel unfinished promises the moment you return a Response, unless you register them with ctx.waitUntil().
  • Strict memory ceilings. Each isolate gets 128 MB of RAM. Buffering a 200 MB file with await response.arrayBuffer() crashes the Worker. Streaming passes it through in constant memory.
  • CPU time vs. wall time. You pay for CPU execution time, not the milliseconds spent waiting on a D1 query or an upstream fetch(). Long network waits do not drain your CPU budget, but tight loops and heavy synchronous parsing do.

Where Cloudflare is a poor fit

Knowing when to walk away saves weeks of workarounds. Skip Workers as your primary compute layer when you need:

  • Long-running native binaries like ffmpeg, headless video rendering, or heavy Python ML pipelines (use Cloudflare Containers or a dedicated VPS for those workloads, and keep Workers in front as the API gateway).
  • Unbounded raw TCP servers or legacy protocols that assume a single long-lived process.
  • Multi-terabyte analytical SQL warehouses (D1 tops out at 10 GB per database, so use Postgres via Hyperdrive or a dedicated analytical store when a single database grows beyond that).

The default stack map

Open the Cloudflare dashboard and the sidebar has more than twenty developer products. Do not adopt them because they are there.

Start from the smallest stack that runs a real product reliably, and add the heavier primitives only when a concrete problem forces your hand.

The 2027 Cloudflare production stackBrowser traffic hits Cloudflare DNS, TLS, WAF, and Turnstile, then splits between free Static Assets and the Worker API, which connects to D1, KV, R2, Queues, Email Service, and Workers Logs.Static filesAPI / SSR routesBrowser /ClientDNS + TLS + WAF+ Rate LimitWorkers StaticAssetsWorker Isolate/ HonoD1 SQLiteKV CacheR2 ObjectStorageQueues + DLQEmail Service /WebhooksWorkers Logs +Traces

Here is the opinionated 2027 default stack and the exact boundary for every product:

JobDefault choiceSkip until…Operational gotcha to watch
Web app + APIWorkers + Static AssetsYou only have a legacy Pages project already workingNever route static assets through a catch-all Worker middleware
Relational dataD1 (SQLite)A single database approaches 10 GB or needs Postgres extensionsMissing composite indexes trigger full SCAN table reads
Read-heavy cacheKVNever use for strong consistency or billing countersEventual consistency (~60s propagation) and 1 write/sec per key
Files, exports, mediaR2Small site assets that belong in static buildsStream large objects instead of buffering in RAM
Async jobs & retriesQueues + DLQInline work takes under ~100ms and rarely failsAt-least-once delivery means consumers must be idempotent
Scheduled jobsCron TriggersYou need per-entity dynamic schedules (use DO alarms)Cron runs in UTC; handle DST explicitly if local wall time matters
Multi-step durable jobsWorkflowsA job does not need durable sleep, waits, or per-step retriesKeep step payloads serializable and small
Live WebSockets / locksDurable ObjectsYou do not need single-writer coordinationNever funnel all global traffic into one single DO ID
Existing Postgres / MySQLHyperdriveYou do not have an external database to keepDisable query caching on read-after-write paths
Bot protectionTurnstileEndpoint is private or already authenticatedAlways verify the token server-side with siteverify
Outbound transactional mailEmail Service or ResendYou need marketing broadcasts (use a newsletter tool)Restrict allowed_destination_addresses on alert Workers
Private origin exposureCloudflare TunnelEverything already runs on WorkersRun two cloudflared replicas for high availability

Why Workers with Static Assets replaces Pages for new projects

For years, static sites lived on Cloudflare Pages and APIs lived on Cloudflare Workers. Going into 2027, Cloudflare’s recommendation for new projects is Workers with Static Assets, and I agree with it.

I compared both models in Cloudflare Pages vs Workers.

With Workers Static Assets, your frontend HTML/CSS/JS and your API live in one repository, one wrangler.jsonc, and one deployment pipeline. You get Cron Triggers, Queues consumers, Durable Objects, Gradual Deployments, and Workers Observability out of the box without splitting your app across two projects.

Existing Pages sites like this blog keep working fine, so there is no rush to migrate a working static site, but start new full-stack apps on Workers.

If you are choosing a full-stack framework on top of Workers, I compared Astro, Hono, React Router, Void, and vinext in Void, vinext, or React Router for a Cloudflare app? and Deploying Hono on Cloudflare Workers. For APIs and small server-rendered apps, Hono plus static assets keeps the bundle tiny and the request path obvious.

DNS, TLS, caching, and edge security

Before writing Worker code, get the network layer right. Most production outages on day one happen in DNS and TLS settings, not application code.

Zones and the orange cloud

When you add a domain to Cloudflare, Cloudflare becomes its authoritative DNS provider (a zone). Each DNS record has a proxy toggle:

  • Proxied (orange cloud): DNS resolves to Cloudflare’s anycast IP addresses. Traffic passes through Cloudflare’s edge, giving you HTTPS, DDoS mitigation, WAF rules, caching, and Worker routing.
  • DNS only (grey cloud): DNS returns your origin IP directly. Cloudflare only answers the DNS lookup and never sees the HTTP traffic.

Keep your domain registrar/DNS mental model separate from your hosting. Domains stay stable for years while hosting changes.

When you point a domain at a new Worker or server, change one layer at a time: get DNS resolving first, enable the proxy second, then verify HTTPS and redirects with curl -I.

Fixing the redirect loop trap

The single most common misconfiguration when enabling the Cloudflare proxy is SSL/TLS mode set to Flexible.

In Flexible mode, Cloudflare connects to your visitor over HTTPS, then connects to your origin server over plain HTTP. If your origin server sees plain HTTP and redirects to HTTPS, Cloudflare sends the browser right back to the same URL forever.

Always use Full (strict) with a valid TLS certificate on the origin (Cloudflare Origin CA certificates are free and valid for up to 15 years). When you hit a loop, inspect the raw Location headers with curl -I instead of guessing in a browser.

I walked through the full diagnosis in Fix ‘Too many redirects’ after enabling Cloudflare proxy.

Reading cache headers and controlling freshness

Check the cf-cache-status header on any response to see what the edge did:

cf-cache-statusWhat happened
HITServed directly from the local Cloudflare data center
MISSNot in edge cache; fetched from origin or Worker and stored
EXPIREDCached entry passed its TTL; refreshed from origin
BYPASSCache skipped (often due to Cache-Control: private or cookies)
DYNAMICNot cached by default (standard for HTML and API JSON)

Never cache responses containing Set-Cookie, private user data, or personalized HTML at the shared edge cache. Use Cache-Control: private, no-store on every authenticated endpoint so a misconfigured Cache Rule can never leak one user’s response to another.

For public API responses that can tolerate short staleness, use explicit s-maxage headers or Workers Cache, covered in Workers Caching.

Origin protection and WAF basics

If you proxy a traditional server behind Cloudflare, attackers can still scan IPv4 space and hit your origin IP directly, bypassing every WAF rule and rate limit you configured. Lock the origin firewall so it only accepts connections from Cloudflare IP ranges, or remove public inbound ports altogether with Cloudflare Tunnel.

Everyday DNS records, orange cloud, and SSL for beginners

If DNS and SSL settings in the Cloudflare dashboard feel cryptic at first, five tiny rules cover almost everything you ever click:

Record typeWhat it points toEveryday example
A / AAAAAn IPv4 or IPv6 server addressPointing flaviocopes.com to a VPS IP
CNAMEAnother domain namePointing www to flaviocopes.com
TXTVerification strings and email rulesDomain ownership, SPF, DKIM, DMARC
MXYour email provider’s mail serversReceiving email at you@yourdomain.com

Next to every A and CNAME record sits Cloudflare’s orange cloud vs gray cloud toggle:

  • Orange cloud (Proxied): Traffic flows through Cloudflare’s CDN, free HTTPS, caching, and DDoS shield. Use this for normal websites and APIs.
  • Gray cloud (DNS only): Cloudflare only answers the IP address and gets out of the way. Use this for SSH (ssh.yourdomain.com), mail records, or hosts that manage their own TLS certificates.

For SSL/TLS encryption mode, set your zone to Full (Strict) whenever your origin server has a valid certificate. Avoid Flexible SSL whenever your origin redirects HTTP to HTTPS, because Cloudflare talks HTTP to your server while your server redirects back to HTTPS forever (the classic ERR_TOO_MANY_REDIRECTS loop).

And when your Worker needs an API key or webhook secret, never put it in wrangler.jsonc. Put local values in .dev.vars (gitignored) and push production secrets with:

npx wrangler secret put RESEND_API_KEY

Project setup, wrangler.jsonc, and environments

To keep every example in this guide grounded in real output, we will walk through PulseWatch, a real uptime and incident monitor built with Hono, Static Assets, D1, KV, R2, Queues, and Cron Triggers.

Start from an empty directory with Wrangler 4 installed locally in the project:

mkdir pulsewatch && cd pulsewatch
npm init -y
npm install hono
npm install -D wrangler typescript vitest @cloudflare/vitest-pool-workers

Run npx wrangler --version to verify you are on Wrangler 4 (wrangler 4.167.0 in this run). Keep Wrangler as a project devDependency rather than relying on a random global version so CI and your laptop match.

Make wrangler.jsonc your single source of truth

Always use wrangler.jsonc instead of the older wrangler.toml. Newer Cloudflare features ship JSON-only first, and referencing the local $schema gives your editor instant autocomplete and validation.

Here is the complete wrangler.jsonc for PulseWatch:

{
  "$schema": "./node_modules/wrangler/config-schema.json",
  "name": "pulsewatch",
  "main": "src/index.ts",
  "compatibility_date": "2026-11-24",
  "compatibility_flags": ["nodejs_compat"],
  "observability": {
    "enabled": true,
    "head_sampling_rate": 1
  },
  "assets": {
    "directory": "./public",
    "binding": "ASSETS",
    "run_worker_first": ["/api/*", "/admin/*"]
  },
  "vars": {
    "ENVIRONMENT": "production",
    "CACHE_TTL_SECONDS": "60"
  },
  "d1_databases": [
    {
      "binding": "DB",
      "database_name": "pulsewatch",
      "database_id": "00000000-0000-0000-0000-000000000001",
      "migrations_dir": "./migrations"
    }
  ],
  "kv_namespaces": [
    {
      "binding": "STATUS_CACHE",
      "id": "00000000000000000000000000000001"
    }
  ],
  "r2_buckets": [
    {
      "binding": "EXPORTS",
      "bucket_name": "pulsewatch-exports"
    }
  ],
  "queues": {
    "producers": [
      { "binding": "ALERTS_QUEUE", "queue": "pulsewatch-alerts" }
    ],
    "consumers": [
      {
        "queue": "pulsewatch-alerts",
        "max_batch_size": 10,
        "max_batch_timeout": 5,
        "max_retries": 3,
        "dead_letter_queue": "pulsewatch-alerts-dlq"
      }
    ]
  },
  "triggers": {
    "crons": ["*/5 * * * *"]
  },
  "env": {
    "staging": {
      "name": "pulsewatch-staging",
      "vars": {
        "ENVIRONMENT": "staging",
        "CACHE_TTL_SECONDS": "15"
      },
      "d1_databases": [
        {
          "binding": "DB",
          "database_name": "pulsewatch-staging",
          "database_id": "00000000-0000-0000-0000-000000000002",
          "migrations_dir": "./migrations"
        }
      ],
      "kv_namespaces": [
        {
          "binding": "STATUS_CACHE",
          "id": "00000000000000000000000000000002"
        }
      ],
      "r2_buckets": [
        {
          "binding": "EXPORTS",
          "bucket_name": "pulsewatch-exports-staging"
        }
      ],
      "queues": {
        "producers": [
          { "binding": "ALERTS_QUEUE", "queue": "pulsewatch-alerts-staging" }
        ],
        "consumers": [
          {
            "queue": "pulsewatch-alerts-staging",
            "max_batch_size": 10,
            "max_batch_timeout": 5,
            "max_retries": 3,
            "dead_letter_queue": "pulsewatch-alerts-staging-dlq"
          }
        ]
      }
    }
  }
}

Notice two production rules baked into that file:

  1. Bindings are not inherited across env.* blocks. When I first wrote this config, I omitted queues inside env.staging. Running npx wrangler types immediately marked ALERTS_QUEUE?: Queue as optional across the entire Env interface, which failed tsc --noEmit. Repeating every binding explicitly inside env.staging keeps staging isolated from production and guarantees identical types across environments.
  2. Pin compatibility_date and enable nodejs_compat. The compatibility date locks runtime behavior so a Cloudflare platform upgrade never silently breaks your app. Adding nodejs_compat lets you import standard built-ins like node:crypto.

Generate Env types instead of hand-writing them

Never hand-write an interface Env by memory. It drifts the moment someone adds a binding or secret. Generate it straight from wrangler.jsonc and .dev.vars:

npx wrangler types

Wrangler writes worker-configuration.d.ts automatically:

interface __BaseEnv_Env {
  STATUS_CACHE: KVNamespace
  EXPORTS: R2Bucket
  DB: D1Database
  ALERTS_QUEUE: Queue
  ASSETS: Fetcher
  ENVIRONMENT: 'staging' | 'production'
  CACHE_TTL_SECONDS: '15' | '60'
  ADMIN_TOKEN: string
  WEBHOOK_SECRET: string
  TURNSTILE_SECRET_KEY: string
}

Add npx wrangler types --check to CI so a pull request that edits wrangler.jsonc without regenerating types fails immediately.

Separate public vars from secrets

Non-secret configuration (ENVIRONMENT, CACHE_TTL_SECONDS, PUBLIC_TURNSTILE_SITE_KEY) belongs in wrangler.jsonc under vars so it is reviewed in Git.

Keep secrets (ADMIN_TOKEN, WEBHOOK_SECRET, TURNSTILE_SECRET_KEY, API keys) out of wrangler.jsonc and Git by placing them in a gitignored .dev.vars file for local development:

ADMIN_TOKEN=local-admin-token-change-in-prod
WEBHOOK_SECRET=whsec_local_test_signing_key_2026
TURNSTILE_SECRET_KEY=1x0000000000000000000000000000000AA

In production and staging, push secrets via Wrangler’s interactive prompt or from a file (never pass secret values as plain shell arguments where they land in shell history):

npx wrangler secret put ADMIN_TOKEN
npx wrangler secret put ADMIN_TOKEN --env staging

I covered environment separation and secret rotation in more detail in Cloudflare Workers: secrets and environments.

Local development and Local Explorer

Good local development is what separates calm shipping from pushing broken code to production to “see if it works”.

Start the local Worker runtime with:

npx wrangler dev

By default, Wrangler simulates D1, KV, R2, Queues, and Static Assets completely locally inside .wrangler/state/v3/. Restarting wrangler dev preserves that local data.

You can run destructive schema experiments, seed fake incidents, and break queries with zero risk to live users.

Be careful with "remote": true on any binding in wrangler.jsonc. That flag connects your local wrangler dev session to a live deployed resource (required for Workers AI and Vectorize, optional for D1/R2/KV). Always check the startup table Wrangler prints so you know which bindings are local and which are remote.

Once wrangler dev is running, PulseWatch serves its static status page at http://localhost:8787/. After seeding three monitors (flaviocopes.com, support.flaviocopes.com, and updates.flaviocopes.com) and recording a simulated HTTP 503 failure on the third one, the status page renders straight from Static Assets plus /api/status:

PulseWatch local status page showing degraded state across three monitored endpoints

Inspecting local bindings and traces with Local Explorer

Wrangler 4 ships with Local Explorer, a built-in DevTools UI hosted at /cdn-cgi/local/explorer on your dev server (http://localhost:8787/cdn-cgi/local/explorer). There is nothing extra to install.

Cloudflare Local Explorer showing PulseWatch Observability, D1, KV, R2, and Email bindings

Local Explorer shows every binding wired into wrangler.jsonc in one sidebar:

  • D1 Databases (DB): Browse tables, edit rows, inspect schema, and run ad-hoc SQL queries directly against .wrangler/state.
  • KV Namespaces (STATUS_CACHE): Read, edit, or delete cached keys without writing throwaway Wrangler commands.
  • R2 Buckets (EXPORTS): Inspect uploaded objects, folders, and metadata.
  • Observability (Traces & Events): See every local HTTP request, duration, span count, and error status in real time.
  • Cron Triggers: Fire your scheduled() handler on demand without waiting five minutes.
  • Copy prompt for agent: Gives your coding agent direct API access to inspect local D1/KV/R2 state while debugging.

Here is our local monitors table inside Local Explorer after running our seed requests (Query Time: 0.0ms, Rows Read: 3):

Local Explorer D1 table view displaying the three seeded PulseWatch monitors

And here is the R2 EXPORTS bucket immediately after triggering POST /admin/export, showing the snapshots/ prefix containing snapshots/2026-11-24.json:

Local Explorer R2 bucket view showing the snapshots directory inside pulsewatch-exports

Workers runtime, Hono, and static assets

Understanding the boundary between Static Assets and your Worker is the single biggest lever for keeping latency low and your Cloudflare bill tiny.

Fig 1 · 1/4How a request crosses Cloudflare
Static asset · served at edge · 0 Worker invocations

Look at step 4 in the figure above. I learned that lesson the hard way on this blog: a root middleware intercepted every incoming path, turning every JPEG, CSS file, and font into a metered function invocation.

Removing the root middleware fixed the bill immediately.

With Workers Static Assets, keep run_worker_first scoped strictly to dynamic paths:

"assets": {
  "directory": "./public",
  "binding": "ASSETS",
  "run_worker_first": ["/api/*", "/admin/*"]
}

Requests for /, /index.html, /app.css, or /logo.webp are served directly by Cloudflare’s edge asset layer with zero Worker invocations. Only /api/* and /admin/* wake your JavaScript.

Structuring a clean Hono Worker with multiple handlers

One Worker can export fetch, scheduled, and queue handlers in the same file. That keeps your HTTP API, cron checks, and async queue consumer sharing the same types, helpers, and deployment artifact.

I wrote a dedicated walkthrough of this pattern in Use fetch, queue, and scheduled handlers in one Cloudflare Worker.

Here is the core structure of src/index.ts in PulseWatch, starting with structured JSON request logging middleware and an explicit error boundary:

import { Hono } from 'hono'
import { signWebhookPayload, timingSafeEqualString } from './crypto'

const app = new Hono<{ Bindings: Env }>()

function logEvent(level: 'info' | 'warn' | 'error', event: string, fields: Record<string, unknown>) {
  console.log(JSON.stringify({ ts: new Date().toISOString(), level, event, ...fields }))
}

app.use('*', async (c, next) => {
  const requestId = c.req.header('cf-ray') ?? crypto.randomUUID()
  const started = Date.now()
  c.header('x-request-id', requestId)
  try {
    await next()
    logEvent('info', 'http_request', {
      requestId,
      method: c.req.method,
      path: new URL(c.req.url).pathname,
      status: c.res.status,
      durationMs: Date.now() - started,
    })
  } catch (err) {
    logEvent('error', 'http_error', {
      requestId,
      path: new URL(c.req.url).pathname,
      error: err instanceof Error ? err.message : String(err),
    })
    return c.json({ error: 'Internal server error', requestId }, 500)
  }
})

Avoid ctx.passThroughOnException() as a safety net. Explicit try/catch with a structured JSON log and a request ID gives you something actionable to search when a user reports a 500.

Profiling Worker startup time

Workers have a strict startup CPU limit (400 ms on paid plans). Heavy top-level imports or parsing large JSON tables at module load time can push a cold isolate over that ceiling before it handles a single request.

Wrangler 4 includes a built-in startup profiler:

npx wrangler check startup

Here is the real profile output for PulseWatch:

Bundle: 71.46 KiB / gzip: 18.52 KiB

Local startup profile:
  Profile window: 20.7 ms
  Sampled time: 20.7 ms
  Active: 9.8 ms (including 0.0 ms garbage collection)
  Idle: 10.9 ms

At 18.52 KiB gzipped and 9.8 ms active startup time, the Worker starts almost instantaneously. Run wrangler check startup whenever you add a large npm package, especially ORMs, validation libraries, or PDF/image parsers.

Typed Env and layered middleware in Hono

Once a Worker grows past three or four endpoints, copying auth checks and response headers into every handler turns messy fast. Hono lets you type both your Cloudflare bindings and per-request context values in one AppEnv definition, so TypeScript checks every middleware and route together.

I like to stack middleware in four predictable layers: security headers and request IDs on every path, explicit CORS on /api/*, Bearer token auth on /admin/*, and then the route handlers themselves.

Here is how those layers look in practice:

import { Hono } from 'hono'
import { cors } from 'hono/cors'
import { timingSafeEqualString } from './crypto'

type AppEnv = {
  Bindings: Env
  Variables: {
    requestId: string
    actor: string
  }
}

const app = new Hono<AppEnv>()

app.use('*', async (c, next) => {
  const requestId =
    c.req.header('cf-ray') ?? crypto.randomUUID()
  c.set('requestId', requestId)
  await next()
  c.header('x-request-id', requestId)
  c.header('x-content-type-options', 'nosniff')
  c.header('referrer-policy', 'strict-origin')
  c.header(
    'strict-transport-security',
    'max-age=31536000; includeSubDomains'
  )
})

app.use(
  '/api/*',
  cors({
    origin: ['https://status.example.com'],
    allowMethods: ['GET', 'POST', 'OPTIONS'],
    allowHeaders: ['Content-Type', 'Authorization'],
    maxAge: 600,
  })
)

app.use('/admin/*', async (c, next) => {
  const header = c.req.header('authorization') ?? ''
  const token = header.replace(/^Bearer\s+/i, '')
  if (!timingSafeEqualString(token, c.env.ADMIN_TOKEN)) {
    return c.json({ error: 'Unauthorized' }, 401)
  }
  c.set('actor', 'admin-api-key')
  await next()
})

Notice two subtle details here. Setting response headers after await next() guarantees they attach even when a downstream handler builds a custom new Response(...), and passing an explicit origin array to cors() avoids accidentally exposing authenticated endpoints to *.

Inside any /admin/* route, c.get('actor') and c.get('requestId') are fully typed strings with zero casting.

Streaming responses under the 128 MB memory cap

If an admin asks to export 100,000 check runs, loading every row into one giant JSON array will blow past the 128 MB isolate memory ceiling and abort the request.

Instead, stream newline-delimited JSON (NDJSON) directly from D1 in small pages using ReadableStream and TextEncoder. Memory stays flat no matter how many rows sit in the table:

app.get('/admin/checks.ndjson', (c) => {
  const encoder = new TextEncoder()
  const db = c.env.DB

  const stream = new ReadableStream({
    async start(controller) {
      let cursor = ''
      while (true) {
        const sql = cursor
          ? `SELECT id, monitor_id, status_code, checked_at
             FROM check_runs WHERE id > ?
             ORDER BY id ASC LIMIT 200`
          : `SELECT id, monitor_id, status_code, checked_at
             FROM check_runs ORDER BY id ASC LIMIT 200`

        const stmt = cursor
          ? db.prepare(sql).bind(cursor)
          : db.prepare(sql)
        const { results } = await stmt.all<{ id: string }>()
        if (results.length === 0) break

        for (const row of results) {
          const line = JSON.stringify(row) + '\n'
          controller.enqueue(encoder.encode(line))
        }
        cursor = results[results.length - 1].id
      }
      controller.close()
    },
  })

  return new Response(stream, {
    headers: {
      'content-type': 'application/x-ndjson; charset=utf-8',
      'cache-control': 'private, no-store',
    },
  })
})

The browser or curl starts receiving lines after the very first 200-row page returns from D1. If the client disconnects halfway through, the runtime stops pulling from the stream instead of wasting work building the rest of the file.

Edge caching with caches.default and ctx.waitUntil()

KV is great for sharing cached JSON globally, yet every read still counts against your KV quota. For hot public endpoints, Cloudflare also gives you the standard Cache API (caches.default), which stores HTTP responses right inside the local data center at zero KV cost.

Always normalize your cache key so random query parameters like ?utm_source=twitter do not fragment the cache. Then write the response asynchronously inside ctx.waitUntil() so the visitor never waits for the cache write:

app.get('/api/public-summary', async (c) => {
  const url = new URL(c.req.url)
  const cacheKey = new Request(
    `${url.origin}${url.pathname}`,
    { method: 'GET' }
  )
  const cache = caches.default

  const hit = await cache.match(cacheKey)
  if (hit) {
    const res = new Response(hit.body, hit)
    res.headers.set('x-edge-cache', 'HIT')
    return res
  }

  const { results } = await c.env.DB.prepare(
    `SELECT id, name, url FROM monitors WHERE enabled = 1`
  ).all()

  const body = JSON.stringify({ monitors: results })
  const res = new Response(body, {
    headers: {
      'content-type': 'application/json; charset=utf-8',
      'cache-control': 'public, s-maxage=60',
      'x-edge-cache': 'MISS',
    },
  })

  c.executionCtx.waitUntil(cache.put(cacheKey, res.clone()))
  return res
})

Remember two quirks of caches.default. First, you must pass res.clone() to cache.put() because a Response body stream can only be read once. Second, caches.default only persists on custom domains in production, while *.workers.dev and wrangler dev bypass or treat it as a no-op, so always verify x-edge-cache: HIT on a staged custom domain.

When an admin updates a monitor and you want the local edge to refresh immediately, call await caches.default.delete(cacheKey). Keep in mind that caches.default is per data center, so combine it with a short s-maxage rather than relying on global instant invalidation.

Static assets and SPA fallback routing in wrangler.jsonc

If your frontend is a React, Vue, or Svelte single-page app that uses client-side routing (like /monitors/mon-1 or /settings/team), a fresh page reload hits Cloudflare for a file that does not exist on disk.

Workers Static Assets handles that cleanly without waking your Worker on every frontend navigation. Set not_found_handling to "single-page-application" and use negative patterns in run_worker_first when a static file lives inside an API prefix:

"assets": {
  "directory": "./dist",
  "binding": "ASSETS",
  "html_handling": "auto-trailing-slash",
  "not_found_handling": "single-page-application",
  "run_worker_first": [
    "/api/*",
    "/admin/*",
    "!/api/openapi.json"
  ]
}

With that config, Cloudflare serves /assets/app.js, /api/openapi.json, and SPA fallback HTML for /monitors/mon-1 straight from the edge for free. Your Worker only runs on real /api/* and /admin/* requests.

What if you want to serve a built HTML page only to logged-in users? Include its path in run_worker_first, check the session cookie in Hono, and hand the request off to the ASSETS binding once authenticated:

app.get('/admin/app/*', async (c) => {
  const session = c.req.header('cookie') ?? ''
  if (!session.includes('pw_session=')) {
    return c.redirect('/login', 302)
  }
  return c.env.ASSETS.fetch(c.req.raw)
})

That gives you authenticated static files without bundling HTML strings inside your JavaScript Worker.

Choosing the right storage

AI agents frequently pick the wrong Cloudflare storage product because the APIs all look equally simple in env. Picking wrong creates subtle production bugs that never appear during single-user local tests.

Fig 2 · 1/4Choosing the right Cloudflare storage
D1 · relational app data · SQLite with strong consistency

Use this reference table when deciding where a piece of data lives:

PropertyD1KVR2Durable ObjectsHyperdrive
Data modelRelational SQLiteKey-value pairsBlobs / objectsPer-ID SQLite + memoryExternal Postgres / MySQL
ConsistencyStrong (primary)Eventual (~60s)Strong per keyStrict single-writerDepends on origin DB
Max size10 GB per DB25 MiB per value5 TB per object10 GB SQLite per DOOrigin DB limit
Write rateModerate (single primary)1 write/sec per keyHighHigh per DO, single-threadedPooled to origin
Billing trapsUnindexed full table scansHeavy writes/deletesClass A/B ops on tiny filesLong-lived idle non-hibernating WSOrigin DB connection saturation
Best fitUsers, orders, incidents, authPublic caches, flags, redirectsUploads, PDFs, exports, backupsChat rooms, locks, strict rate limitsLegacy Postgres you cannot move

The rule of thumb I use is short:

  • Rows with relationships, constraints, or queries belong in D1.
  • Read-heavy snapshots or configuration that can tolerate 60 seconds of staleness belong in KV.
  • Files, backups, and exports belong in R2.
  • Strict single-writer coordination or live WebSockets belong in Durable Objects.

D1 in production

D1 is managed SQLite wired directly into your Worker via env.DB. There is no connection string, no TLS handshake to a database server, and no connection pool to exhaust. You still have to treat it like a real production database.

Schema design and versioned migrations

Put every schema change in ./migrations/ from day one instead of editing production tables by hand in the dashboard. Here is PulseWatch’s initial migration (migrations/0001_init.sql):

CREATE TABLE monitors (
  id TEXT PRIMARY KEY,
  name TEXT NOT NULL,
  url TEXT NOT NULL UNIQUE,
  expected_status INTEGER NOT NULL DEFAULT 200,
  enabled INTEGER NOT NULL DEFAULT 1,
  created_at TEXT NOT NULL DEFAULT (datetime('now'))
);

CREATE TABLE check_runs (
  id TEXT PRIMARY KEY,
  monitor_id TEXT NOT NULL REFERENCES monitors(id) ON DELETE CASCADE,
  status_code INTEGER NOT NULL,
  latency_ms INTEGER NOT NULL,
  ok INTEGER NOT NULL,
  checked_at TEXT NOT NULL DEFAULT (datetime('now'))
);

CREATE TABLE incidents (
  id TEXT PRIMARY KEY,
  monitor_id TEXT NOT NULL REFERENCES monitors(id) ON DELETE CASCADE,
  state TEXT NOT NULL CHECK (state IN ('open', 'resolved')),
  summary TEXT NOT NULL,
  opened_at TEXT NOT NULL DEFAULT (datetime('now')),
  resolved_at TEXT
);

CREATE TABLE alert_deliveries (
  idempotency_key TEXT PRIMARY KEY,
  incident_id TEXT NOT NULL REFERENCES incidents(id) ON DELETE CASCADE,
  channel TEXT NOT NULL,
  delivered_at TEXT NOT NULL DEFAULT (datetime('now'))
);

CREATE INDEX idx_check_runs_monitor_time ON check_runs(monitor_id, checked_at DESC);
CREATE INDEX idx_incidents_monitor_state ON incidents(monitor_id, state);

And a second, additive migration (migrations/0002_add_timeout_ms.sql) that adds a timeout column safely:

ALTER TABLE monitors ADD COLUMN timeout_ms INTEGER NOT NULL DEFAULT 5000;

Apply migrations locally first, then to staging, then to production:

npx wrangler d1 migrations apply pulsewatch --local
npx wrangler d1 migrations apply pulsewatch-staging --remote --env staging
npx wrangler d1 migrations apply pulsewatch --remote

Running --local in PulseWatch prints the exact execution table:

┌─────────────────────────┬────────┐
│ name                    │ status │
├─────────────────────────┼────────┤
│ 0001_init.sql           │ ✅     │
│ 0002_add_timeout_ms.sql │ ✅     │
└─────────────────────────┴────────┘

Prepared statements, indexes, and EXPLAIN QUERY PLAN

Always bind every request value with .bind(). Never interpolate strings into SQL.

D1 bills by rows read and rows written. A missing index doesn’t just slow down a query, it multiplies your billed rows read on every single request. Check every hot query with EXPLAIN QUERY PLAN before deploying.

First, run EXPLAIN QUERY PLAN on an indexed query in PulseWatch:

npx wrangler d1 execute pulsewatch --local --command \
  "EXPLAIN QUERY PLAN SELECT status_code, latency_ms, checked_at FROM check_runs WHERE monitor_id = 'mon-1' ORDER BY checked_at DESC LIMIT 20"

Output:

SEARCH check_runs USING INDEX idx_check_runs_monitor_time (monitor_id=?)

Now run it on an unindexed column (status_code):

npx wrangler d1 execute pulsewatch --local --command \
  "EXPLAIN QUERY PLAN SELECT * FROM check_runs WHERE status_code = 503"

Output:

SCAN check_runs

SEARCH ... USING INDEX reads only the matching rows (20 rows for LIMIT 20). SCAN check_runs reads every row in the table every time. When check_runs hits 500,000 rows, a single unindexed query burns half a million row reads per request.

Atomic writes with db.batch()

In D1, each separate await env.DB.prepare(...).run() is a separate round trip and a separate transaction. If you insert a failed check run and then crash before opening the incident, your database is left half-updated.

Wrap related writes in env.DB.batch([...]). D1 executes the entire batch sequentially inside one atomic transaction and rolls all statements back if any statement fails:

await c.env.DB.batch([
  c.env.DB.prepare(
    `INSERT INTO check_runs (id, monitor_id, status_code, latency_ms, ok) VALUES (?, ?, ?, ?, 0)`
  ).bind(checkId, monitor.id, body.statusCode, body.latencyMs),
  c.env.DB.prepare(
    `INSERT INTO incidents (id, monitor_id, state, summary) VALUES (?, ?, 'open', ?)`
  ).bind(incidentId, monitor.id, summary),
])

Zero-downtime migrations (expand and contract)

When deploying a schema change to a live app, remember that the old Worker version is still serving requests during and right after the migration, and you might need to roll back to it ten minutes later.

Never rename or drop a column in a single release. Split destructive changes across two deployments:

  1. Expand: Add the new column with a DEFAULT (like timeout_ms INTEGER NOT NULL DEFAULT 5000), deploy the migration, then deploy the new Worker that reads and writes both columns.
  2. Contract: Wait until the old Worker version is no longer rollback-eligible, then drop the unused column in a later migration.

Backups and Time Travel recovery

D1 includes Time Travel, which lets you restore a database to any minute-granularity bookmark from the last 30 days on the Workers Paid plan (7 days on Free). Check your current bookmark before any risky migration:

npx wrangler d1 time-travel info pulsewatch

Restore to a specific timestamp or bookmark if a bad script corrupts data:

npx wrangler d1 time-travel restore pulsewatch --timestamp="2026-11-24T07:00:00Z"

For off-Cloudflare disaster recovery, also export periodic SQL dumps to an encrypted backup bucket or local archive:

npx wrangler d1 export pulsewatch --remote --output backup-2026-11-24.sql

Parameterized filters and cursor pagination

Two habits separate a D1 database that costs pennies from one that burns millions of row reads per hour: building dynamic queries strictly with bound parameters, and replacing OFFSET pagination with cursor pagination.

When you run SELECT ... LIMIT 20 OFFSET 20000, SQLite still reads and discards the first 20,000 rows before returning row 20,001. In D1, you get billed for every one of those skipped rows.

Cursor (keyset) pagination uses the last item’s sort column as a WHERE filter instead. Paired with our composite index idx_check_runs_monitor_time(monitor_id, checked_at DESC), page 1,000 reads the same 20 rows as page 1:

app.get('/api/monitors/:id/checks', async (c) => {
  const monitorId = c.req.param('id')
  const before = c.req.query('before')
  const onlyFailed = c.req.query('failed') === '1'
  const rawLimit = Number(c.req.query('limit') ?? '20')
  const limit = Math.min(Math.max(rawLimit, 1), 100)

  const clauses = ['monitor_id = ?']
  const params: unknown[] = [monitorId]

  if (before) {
    clauses.push('checked_at < ?')
    params.push(before)
  }
  if (onlyFailed) {
    clauses.push('ok = 0')
  }

  params.push(limit)
  const sql = `
    SELECT id, status_code, latency_ms, ok, checked_at
    FROM check_runs
    WHERE ${clauses.join(' AND ')}
    ORDER BY checked_at DESC
    LIMIT ?
  `

  const { results } = await c.env.DB.prepare(sql)
    .bind(...params)
    .all<{ checked_at: string }>()

  const nextCursor =
    results.length === limit
      ? results[results.length - 1].checked_at
      : null

  return c.json({ items: results, nextCursor })
})

Notice how clauses only ever contains hardcoded SQL fragments, while user values stay inside params and enter through .bind(...params). Even if a client sends a crafted query string, SQL injection is impossible.

Multi-statement db.batch() and migration discipline

We saw db.batch() earlier for inserting a failed check and an incident atomically. You can also mix writes and a final read in the same batch so your Worker gets back the updated state in a single network round trip:

async function resolveIncident(
  db: D1Database,
  incidentId: string,
  actor: string
) {
  const results = await db.batch([
    db
      .prepare(
        `UPDATE incidents
         SET state = 'resolved',
             resolved_at = datetime('now')
         WHERE id = ? AND state = 'open'`
      )
      .bind(incidentId),
    db
      .prepare(
        `INSERT INTO alert_deliveries
           (idempotency_key, incident_id, channel)
         VALUES (?, ?, ?)`
      )
      .bind(`resolve:${incidentId}`, incidentId, actor),
    db
      .prepare(
        `SELECT COUNT(*) AS open_count
         FROM incidents WHERE state = 'open'`
      ),
  ])

  const updated = results[0].meta.changes
  const countRow = results[2].results[0] as {
    open_count: number
  }
  return { updated, openCount: countRow.open_count }
}

If the second statement violates a PRIMARY KEY constraint because someone already resolved that incident, D1 rolls back the UPDATE in statement 1 automatically.

For schema changes, follow one strict migration loop every time you add a table or index:

# 1. Generate a numbered migration file in ./migrations
npx wrangler d1 migrations create pulsewatch add_tags

# 2. Check pending migrations locally, then apply
npx wrangler d1 migrations list pulsewatch --local
npx wrangler d1 migrations apply pulsewatch --local

# 3. Run your workerd test suite against the new schema
npm test

# 4. Apply to staging first, then production
npx wrangler d1 migrations apply pulsewatch-staging \
  --remote --env staging
npx wrangler d1 migrations apply pulsewatch --remote

Never edit a migration file after it has run on staging or production. Wrangler tracks applied filenames inside the d1_migrations table, so modifying an old file leaves production silently out of sync with your local database. Always create a new numbered migration instead.

For deeper D1 and Drizzle patterns, see Cloudflare D1: a SQL database for your Workers and Astro SSR with D1 and Drizzle ORM.

KV and R2 in production

Once D1 holds your authoritative relational data, KV and R2 handle the two jobs a SQLite database should not do: global read caching and large file storage.

KV: caching with explicit staleness

In PulseWatch, GET /api/status is a public page that could receive thousands of requests per minute during an outage. Hitting D1 on every visitor wastes row reads.

Instead, the Worker checks env.STATUS_CACHE first. On a miss, it queries D1, sends the JSON response immediately, and populates KV inside ctx.waitUntil() with a 60-second TTL (the minimum expiration TTL KV allows):

app.get('/api/status', async (c) => {
  const cached = await c.env.STATUS_CACHE.get('public-status', 'json')
  if (cached) {
    c.header('x-status-cache', 'HIT')
    return c.json(cached)
  }

  // ... query D1 for monitors and openIncidents ...

  const ttl = Math.max(60, Number(c.env.CACHE_TTL_SECONDS) || 60)
  c.executionCtx.waitUntil(
    c.env.STATUS_CACHE.put('public-status', JSON.stringify(payload), { expirationTtl: ttl })
  )

  c.header('x-status-cache', 'MISS')
  return c.json(payload)
})

Running this locally in PulseWatch showed the exact payoff in Local Explorer’s Traces view:

  • Cold GET /api/status (x-status-cache: MISS): 16 ms across 5 spans (KV lookup, two D1 queries, background KV write).
  • Warm GET /api/status (x-status-cache: HIT): 2 ms across 2 spans (KV lookup only, zero D1 reads).

Keep two KV constraints in mind:

  1. Eventual consistency. Deleting or updating public-status invalidates the local data center quickly, while remote data centers can serve the previous value for up to 60 seconds. That is fine for a status page, and completely wrong for checking whether a user already redeemed a one-time license key.
  2. One write per second per key. Never increment a hot global counter under a single KV key. Writes collide and drop updates silently.

R2: streaming objects with zero egress fees

R2 is S3-compatible object storage with $0 egress bandwidth fees. On this site, I use R2 behind downloads.flaviocopes.com for large books and archives so they stay out of Git and out of the Astro build output.

In PulseWatch, POST /admin/export writes a daily snapshot to snapshots/2026-11-24.json with explicit httpMetadata and customMetadata:

await c.env.EXPORTS.put(key, payload, {
  httpMetadata: { contentType: 'application/json' },
  customMetadata: { count: String(results.length) },
})

When serving large files back from R2 through a Worker, stream object.body directly into new Response() instead of calling await object.arrayBuffer() or await object.text():

app.get('/admin/exports/:day', async (c) => {
  const object = await c.env.EXPORTS.get(`snapshots/${c.req.param('day')}.json`)
  if (!object) return c.json({ error: 'Snapshot not found' }, 404)

  const headers = new Headers()
  object.writeHttpMetadata(headers)
  headers.set('etag', object.httpEtag)
  return new Response(object.body, { headers })
})

Streaming keeps Worker memory flat whether the file is 50 KB or 500 MB. For browser-to-R2 uploads larger than a few megabytes, generate short-lived presigned URLs so the browser uploads straight to R2 instead of piping through your Worker.

KV cache-aside with negative caching and key versioning

The simple KV cache-aside pattern works well when keys exist, yet it has a sneaky failure mode: cache penetration. If a bot requests /api/monitors/fake-1, /api/monitors/fake-2, and 10,000 other nonexistent IDs, every lookup misses KV and hits D1.

You can block that flood with negative caching. When D1 returns no row, store a tiny { found: false } sentinel in KV with a 60-second TTL, and prefix keys with a schema version (v2:) so future payload changes never collide with old cached JSON:

type CachedMonitor =
  | { found: true; data: { id: string; name: string } }
  | { found: false }

app.get('/api/monitors/:id', async (c) => {
  const id = c.req.param('id')
  const key = `v2:monitor:${id}`

  const cached = await c.env.STATUS_CACHE.get<CachedMonitor>(
    key,
    'json'
  )
  if (cached) {
    c.header('x-kv-cache', cached.found ? 'HIT' : 'NEG-HIT')
    if (!cached.found) return c.json({ error: 'Not found' }, 404)
    return c.json(cached.data)
  }

  const row = await c.env.DB.prepare(
    `SELECT id, name FROM monitors WHERE id = ?`
  )
    .bind(id)
    .first<{ id: string; name: string }>()

  const entry: CachedMonitor = row
    ? { found: true, data: row }
    : { found: false }

  c.executionCtx.waitUntil(
    c.env.STATUS_CACHE.put(key, JSON.stringify(entry), {
      expirationTtl: row ? 300 : 60,
    })
  )

  c.header('x-kv-cache', 'MISS')
  if (!row) return c.json({ error: 'Not found' }, 404)
  return c.json(row)
})

Notice the two different TTLs: valid monitors stay cached for 5 minutes (300), while missing IDs stay cached for just 60 seconds (60). If you create a new monitor right away, clear its key with await c.env.STATUS_CACHE.delete(key) so the local edge stops serving the negative entry.

Signed R2 upload and download routes with validation

When users upload attachments (screenshots, invoices, or diagnostic logs under ~50 MB), routing uploads through a Worker with short-lived HMAC tokens gives you strict server-side control over file types, byte limits, and cache headers without exposing R2 API credentials to the browser.

First, verify the signed query parameters (exp and sig), validate the Content-Type against an allowlist, and count bytes as they arrive so a client cannot lie with a fake Content-Length header:

const ALLOWED_MIME = new Set([
  'image/png',
  'image/jpeg',
  'image/webp',
  'application/pdf',
])
const MAX_UPLOAD_BYTES = 5 * 1024 * 1024

async function readBoundedBytes(
  body: ReadableStream<Uint8Array>,
  maxBytes: number
): Promise<Uint8Array | null> {
  const reader = body.getReader()
  const chunks: Uint8Array[] = []
  let total = 0

  while (true) {
    const { done, value } = await reader.read()
    if (done) break
    total += value.byteLength
    if (total > maxBytes) {
      await reader.cancel()
      return null
    }
    chunks.push(value)
  }

  const out = new Uint8Array(total)
  let offset = 0
  for (const chunk of chunks) {
    out.set(chunk, offset)
    offset += chunk.byteLength
  }
  return out
}

app.put('/api/uploads/:key', async (c) => {
  const key = c.req.param('key')
  const exp = c.req.query('exp') ?? ''
  const sig = c.req.query('sig') ?? ''

  if (Number(exp) < Math.floor(Date.now() / 1000)) {
    return c.json({ error: 'Upload link expired' }, 403)
  }
  const expected = await signWebhookPayload(
    c.env.WEBHOOK_SECRET,
    exp,
    `PUT:${key}`
  )
  if (!timingSafeEqualString(sig, expected)) {
    return c.json({ error: 'Invalid upload signature' }, 403)
  }

  const mime = (c.req.header('content-type') ?? '').split(';')[0]
  if (!ALLOWED_MIME.has(mime)) {
    return c.json({ error: 'Unsupported file type' }, 415)
  }

  const declared = Number(c.req.header('content-length') ?? '0')
  if (declared > MAX_UPLOAD_BYTES) {
    return c.json({ error: 'File too large' }, 413)
  }
  if (!c.req.raw.body) {
    return c.json({ error: 'Empty body' }, 400)
  }

  const bytes = await readBoundedBytes(
    c.req.raw.body,
    MAX_UPLOAD_BYTES
  )
  if (!bytes) {
    return c.json({ error: 'File exceeds 5 MB limit' }, 413)
  }

  await c.env.EXPORTS.put(`uploads/${key}`, bytes, {
    httpMetadata: {
      contentType: mime,
      cacheControl: 'public, max-age=31536000, immutable',
    },
  })

  return c.json({ key: `uploads/${key}`, bytes: bytes.byteLength })
})

On the download side, honor conditional requests (If-None-Match) so repeat loads return 304 Not Modified without transferring the file body again:

app.get('/api/uploads/:key', async (c) => {
  const key = `uploads/${c.req.param('key')}`
  const object = await c.env.EXPORTS.get(key)
  if (!object) return c.json({ error: 'File not found' }, 404)

  if (c.req.header('if-none-match') === object.httpEtag) {
    return new Response(null, {
      status: 304,
      headers: { etag: object.httpEtag },
    })
  }

  const headers = new Headers()
  object.writeHttpMetadata(headers)
  headers.set('etag', object.httpEtag)
  headers.set('x-content-type-options', 'nosniff')
  return new Response(object.body, { headers })
})

Always include x-content-type-options: nosniff on user-uploaded files so a browser never tries to sniff an uploaded image or PDF as executable HTML or JavaScript.

See Cloudflare R2: object storage without egress fees for bucket and CORS setup.

Background work and scheduling

Never make a user wait for an external webhook, an email provider, or a slow report export inside an HTTP request handler. Cloudflare gives you four tools for work outside the request lifecycle, and each handles a different level of failure.

ToolBest forRetries on failure?Survives isolate eviction?
ctx.waitUntil()Fire-and-forget cache fills, metricsNoNo (bounded ~30s after response)
Cron TriggersPeriodic polling, daily exports, cleanupNo (runs next tick)Yes (fresh invocation)
QueuesReliable async jobs, webhook/email fanoutYes + Dead Letter QueueYes (durable storage)
WorkflowsMulti-step jobs with sleeps and human approvalsYes, per individual stepYes (durable step state)

Be careful not to destructure ctx

Always call ctx.waitUntil(promise) or c.executionCtx.waitUntil(promise) as a method on ctx. Writing const { waitUntil } = ctx; waitUntil(p) strips this and throws TypeError: Illegal invocation at runtime in workerd.

Queues with idempotency keys and Dead Letter Queues

Cloudflare Queues guarantee at-least-once delivery. That means a network hiccup or batch retry can deliver the same alert message twice. If your consumer does not guard against duplicates, your user receives duplicate emails or duplicate charges.

Idempotent queue processing with Dead Letter QueueThe Worker enqueues an alert with an idempotency key. The consumer checks D1 INSERT OR IGNORE, skips duplicates, signs and delivers new alerts, retries failures up to 3 times, and sends poison messages to the DLQ.ALERTS_QUEUE.sendchanges = 0changes = 1Throws 3xWorker APIpulsewatch-alertsQueue ConsumerD1 alert_deliveriesDuplicate skipped +ackSign HMAC + deliver+ ackpulsewatch-alerts-dlq

In PulseWatch, every alert message carries a deterministic idempotencyKey (incident:${incidentId}:webhook). The consumer uses SQLite’s INSERT OR IGNORE against the PRIMARY KEY on alert_deliveries:

export async function processAlertBatch(batch: MessageBatch<AlertMessage>, env: Env) {
  for (const message of batch.messages) {
    const alert = message.body
    const inserted = await env.DB.prepare(
      `INSERT OR IGNORE INTO alert_deliveries (idempotency_key, incident_id, channel) VALUES (?, ?, 'webhook')`
    )
      .bind(alert.idempotencyKey, alert.incidentId)
      .run()

    if (inserted.meta.changes === 0) {
      logEvent('info', 'alert_duplicate_skipped', { idempotencyKey: alert.idempotencyKey })
      message.ack()
      continue
    }

    const body = JSON.stringify(alert)
    const timestamp = String(Math.floor(Date.now() / 1000))
    const signature = await signWebhookPayload(env.WEBHOOK_SECRET, timestamp, body)

    logEvent('info', 'alert_signed_and_delivered', {
      incidentId: alert.incidentId,
      signaturePrefix: signature.slice(0, 12),
    })
    message.ack()
  }
}

Always configure a dead_letter_queue on every production consumer ("dead_letter_queue": "pulsewatch-alerts-dlq"). Without one, messages that exceed max_retries disappear silently.

With one, failed payloads wait safely for inspection and replay. See Build an idempotent scheduled job with Cloudflare Queues and D1 and Cloudflare Queues for more patterns.

Cron Triggers and UTC time zones

PulseWatch runs its uptime checks every 5 minutes via triggers.crons: ["*/5 * * * *"]. Always cancel unused response bodies (await res.body?.cancel()) inside loops that fetch external URLs, and pass an AbortSignal.timeout(monitor.timeout_ms) so one hanging origin never stalls your entire cron run.

Remember that Cron Triggers fire in UTC. On this blog, my scheduled-rebuild Worker checks the Europe/Rome wall-clock time inside the handler so daylight saving transitions never require manual schedule edits.

See How I auto-publish scheduled posts with a Cloudflare Worker cron.

When to graduate to Workflows

If a background task has multiple external API calls that must not re-run from step 1 on a partial failure (for example: charge payment, provision account, wait 24 hours, send follow-up email), move from Queues to Cloudflare Workflows. Each step.do() persists its return value, retries independently, and step.sleep() pauses for hours or days without holding a Worker open.

Producer batching, retry backoff, and DLQ inspection

When a Cron Trigger finds 40 degraded monitors at once, calling env.ALERTS_QUEUE.send() forty separate times wastes subrequests. Use sendBatch() to enqueue up to 100 messages in a single call:

async function enqueueAlerts(
  queue: Queue<AlertMessage>,
  alerts: AlertMessage[]
) {
  const batch = alerts.map((body) => ({
    body,
    contentType: 'json' as const,
  }))
  await queue.sendBatch(batch)
}

Inside your consumer, avoid throwing an uncaught error for every transient failure. Catch upstream 5xx or timeout errors per message and call message.retry({ delaySeconds }) with exponential backoff so a struggling webhook endpoint gets breathing room:

export async function handleQueueWithBackoff(
  batch: MessageBatch<AlertMessage>,
  env: Env
) {
  for (const message of batch.messages) {
    const alert = message.body
    try {
      const inserted = await env.DB.prepare(
        `INSERT OR IGNORE INTO alert_deliveries
           (idempotency_key, incident_id, channel)
         VALUES (?, ?, 'webhook')`
      )
        .bind(alert.idempotencyKey, alert.incidentId)
        .run()

      if (inserted.meta.changes === 0) {
        message.ack()
        continue
      }

      const res = await fetch(alert.webhookUrl, {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify(alert),
        signal: AbortSignal.timeout(5000),
      })

      if (!res.ok) {
        await res.body?.cancel()
        throw new Error(`Webhook HTTP ${res.status}`)
      }
      await res.body?.cancel()
      message.ack()
    } catch (err) {
      const delaySeconds = Math.min(
        300,
        15 * 2 ** message.attempts
      )
      message.retry({ delaySeconds })
    }
  }
}

Notice why we guard idempotency in D1 instead of KV here. Two retries delivered close together in different regions can both read a KV miss before propagation finishes, whereas D1’s PRIMARY KEY enforces strict uniqueness on the primary database. Only use KV for idempotency when an occasional duplicate is harmless (like refreshing a search index).

What happens after a message fails max_retries times and lands in pulsewatch-alerts-dlq? Attach a tiny consumer to the dead-letter queue that archives failed payloads to R2 so they never expire silently after retention runs out:

async function archiveDeadLetters(
  batch: MessageBatch<AlertMessage>,
  env: Env
) {
  const day = new Date().toISOString().slice(0, 10)
  for (const message of batch.messages) {
    const key = `dlq/${day}/${message.id}.json`
    const payload = JSON.stringify({
      id: message.id,
      attempts: message.attempts,
      timestamp: message.timestamp.toISOString(),
      body: message.body,
    })
    await env.EXPORTS.put(key, payload, {
      httpMetadata: { contentType: 'application/json' },
    })
    message.ack()
  }
}

Now every failed alert sits safely in R2 as a plain JSON file you can inspect, fix, and re-enqueue once the downstream service recovers.

A concrete Cloudflare Workflow with durable steps

When a job spans hours or involves several external API calls, a Queue consumer is too short-lived and re-runs from the top on failure. Cloudflare Workflows solves that by persisting each step.do() result and pausing cleanly with step.sleep().

Here is an escalation Workflow for PulseWatch that alerts Slack immediately, waits 15 minutes without burning CPU, and only pages on-call if the incident is still open:

import {
  WorkflowEntrypoint,
  WorkflowEvent,
  WorkflowStep,
} from 'cloudflare:workers'

type EscalationParams = {
  incidentId: string
  summary: string
}

export class IncidentEscalation extends WorkflowEntrypoint<
  Env,
  EscalationParams
> {
  async run(
    event: WorkflowEvent<EscalationParams>,
    step: WorkflowStep
  ) {
    const { incidentId, summary } = event.payload

    await step.do(
      'notify-chat',
      { retries: { limit: 3, delay: '10 seconds' } },
      async () => {
        const res = await fetch(this.env.CHAT_WEBHOOK_URL, {
          method: 'POST',
          body: JSON.stringify({ incidentId, summary }),
        })
        if (!res.ok) throw new Error(`HTTP ${res.status}`)
        await res.body?.cancel()
        return { notified: true }
      }
    )

    await step.sleep('wait-for-ack', '15 minutes')

    const stillOpen = await step.do('check-state', async () => {
      const row = await this.env.DB.prepare(
        `SELECT state FROM incidents WHERE id = ?`
      )
        .bind(incidentId)
        .first<{ state: string }>()
      return row?.state === 'open'
    })

    if (stillOpen) {
      await step.do('page-on-call', async () => {
        await this.env.ALERTS_QUEUE.send({
          incidentId,
          idempotencyKey: `page:${incidentId}`,
          summary,
        })
      })
    }
  }
}

Register the Workflow in wrangler.jsonc alongside your other bindings:

"workflows": [
  {
    "name": "incident-escalation",
    "binding": "ESCALATION",
    "class_name": "IncidentEscalation"
  }
]

Trigger it from any route with await c.env.ESCALATION.create({ id: incidentId, params: { incidentId, summary } }). Using incidentId as the Workflow instance ID also prevents starting duplicate escalations for the same outage.

Choosing between Cron, Queues, Durable Objects, and Workflows

When you are deciding which background primitive fits a feature, match the tool to the failure and timing model rather than picking the newest product:

DimensionCron TriggersQueuesDurable ObjectsWorkflows
Trigger modelFixed UTC scheduleProducer send()HTTP, RPC, or AlarmExplicit create()
Failure retriesNone (next tick)Automatic + DLQManual or alarm retryPer-step retries
OrderingSingle tick runUnordered batchesStrict single-writerSequential steps
Pause / sleepNoDelayed retry onlyStorage AlarmsDays or weeks
Typical trapForgetting UTC/DSTMissing idempotencySingle global DO IDNon-serializable state
Best fit5-min uptime pollsWebhooks & emailsPer-room timers/locksOnboarding & billing

Durable Objects and when to skip them

Start with D1, KV, R2, and Queues, because most CRUD apps have no need for Durable Objects.

Graduate to a Durable Object when you hit one of three concrete requirements:

  1. Real-time WebSockets (live dashboards, chat rooms, multiplayer state) using the Hibernation API so idle sockets cost almost nothing.
  2. Strict per-entity serialization (preventing two concurrent requests from overselling the last seat or exceeding a strict per-tenant rate limit).
  3. Per-entity scheduled alarms (this.ctx.storage.setAlarm(...)) when thousands of users each need their own independent timer.

Each Durable Object instance is identified by a key you choose (env.MONITOR_ROOM.idFromName(monitorId)), runs single-threaded in one location, and includes its own private embedded SQLite database (this.ctx.storage.sql).

Here is the minimal modern Durable Object pattern using typed RPC (extending DurableObject, never implements):

import { DurableObject } from 'cloudflare:workers'

export class MonitorRoom extends DurableObject<Env> {
  async recordBeat(statusCode: number) {
    this.ctx.storage.sql.exec(
      `CREATE TABLE IF NOT EXISTS beats (ts INTEGER PRIMARY KEY, status INTEGER NOT NULL)`
    )
    this.ctx.storage.sql.exec(
      `INSERT INTO beats (ts, status) VALUES (?, ?)`,
      Date.now(),
      statusCode
    )
    return { ok: true }
  }
}

The one catastrophic Durable Object mistake is choosing a global key like idFromName('global'). Every request from every user on Earth then queues behind one single thread in one data center.

Always scope your Durable Object ID to the narrowest natural boundary: one per user, one per room, one per tenant, or one per monitor. Read Cloudflare Durable Objects tutorial for full migration and WebSocket hibernation details.

If you run your own servers, see how I self-hosted Durable Objects with workerd.

Auth, bots, abuse, and edge security

An AI-generated app usually works fine for its author on localhost. The moment it gets a public URL, automated scanners probe every form and admin route within hours.

Timing-safe secrets and HMAC webhook signing

Never compare API tokens or webhook signatures with ===. Standard string comparison exits on the first mismatched byte, leaking timing information.

With nodejs_compat enabled, use timingSafeEqual from node:crypto and Web Crypto (crypto.subtle) for HMAC-SHA256 signing:

import { timingSafeEqual } from 'node:crypto'

const encoder = new TextEncoder()

export function timingSafeEqualString(a: string, b: string): boolean {
  const aBytes = encoder.encode(a)
  const bBytes = encoder.encode(b)
  if (aBytes.byteLength !== bBytes.byteLength) return false
  return timingSafeEqual(aBytes, bBytes)
}

export async function signWebhookPayload(secret: string, timestamp: string, body: string): Promise<string> {
  const key = await crypto.subtle.importKey(
    'raw',
    encoder.encode(secret),
    { name: 'HMAC', hash: 'SHA-256' },
    false,
    ['sign']
  )
  const signature = await crypto.subtle.sign('HMAC', key, encoder.encode(`${timestamp}.${body}`))
  return [...new Uint8Array(signature)].map((b) => b.toString(16).padStart(2, '0')).join('')
}

Always sign ${timestamp}.${body} and reject timestamps older than 5 minutes on the receiving side to prevent replay attacks. For signed download links without database lookups, see HMAC-signed URLs on Cloudflare Workers.

Authentication on Workers + D1

Avoid bloated Node-only auth packages that break inside workerd. You have two clean options:

Turnstile + rate limiting on every public form

Public form protection boundaryA browser solves the Turnstile widget and submits to the Worker. The Worker checks rate limits, verifies the Turnstile token with siteverify using the secret key, fails closed on error, and only then runs business logic.NoYessuccess = falsesuccess = trueBrowser Form +Turnstile WidgetPOST /api/subscribeRate limit OK?429 Too ManyRequestsPOSTchallenges.cloudflare.com/siteverify403 ForbiddenAccept request

Adding <div class="cf-turnstile"> to HTML protects nothing by itself. Bots skip your browser page and POST straight to /api/subscribe. Always verify the token server-side and fail closed if the token is missing or siteverify fails:

const verifyRes = await fetch('https://challenges.cloudflare.com/turnstile/v0/siteverify', {
  method: 'POST',
  body: new URLSearchParams({
    secret: c.env.TURNSTILE_SECRET_KEY,
    response: token,
    remoteip: c.req.header('cf-connecting-ip') ?? '',
  }),
})
const outcome = await verifyRes.json<{ success: boolean; 'error-codes'?: string[] }>()
if (!outcome.success) {
  return c.json({ error: 'Verification failed' }, 403)
}

Layer rate limiting in front of Turnstile and any paid API call. On this site, every newsletter signup and AI tool runs through both Turnstile and rate-limit counters (hashing the client IP before storing keys).

For simple abuse protection, Cloudflare’s Workers Rate Limiting binding or Rate limiting with Cloudflare KV handles the bulk of bot floods. For strict per-user quotas, use a Durable Object.

Exposing private services with Cloudflare Tunnel

When part of your stack still runs on a VPS, home server, or Mac mini, never open port 80/443 or SSH to the public internet if you do not have to. Run cloudflared outbound from that machine to create a Cloudflare Tunnel, and put Cloudflare Access in front of internal admin panels so unauthenticated requests never even reach your server.

Transactional email on Cloudflare

Cloudflare now covers both halves of transactional email natively under Email Service:

  • Email Sending (send_email binding): Send outbound transactional emails (password resets, incident alerts, receipts) directly from a Worker without storing an API key in secrets.
  • Email Routing (Email Workers): Receive inbound emails on your domain and run a Worker email(message, env, ctx) handler when a message arrives.

For an alert Worker like PulseWatch, restrict allowed_destination_addresses in wrangler.jsonc so even a bug in application code cannot turn the Worker into an open relay:

"send_email": [
  {
    "name": "EMAIL",
    "allowed_destination_addresses": ["ops@flaviocopes.com"]
  }
]

If you need mature deliverability dashboards, inbound webhooks, or higher initial sending quotas right away, Resend pairs cleanly with Workers too.

Verifying inbound email senders

If you build an inbound email workflow (like replying to support tickets by email), never trust the From: header alone. Anyone on the internet can forge a From: address.

On support.flaviocopes.com, my Worker only posts an agent reply to a customer when the inbound mail both matches my address AND passes DKIM or DMARC authentication headers verified by the mail relay. Apply that same rule to any Email Worker that triggers state changes.

See How to send email with Cloudflare Email Service and Cloudflare Email Workers.

AI on Cloudflare without runaway bills

Cloudflare offers four main AI primitives:

  • Workers AI (env.AI): Serverless inference on Cloudflare’s GPUs with no third-party API key. Note that env.AI always runs remotely and bills usage even during wrangler dev.
  • AI Gateway: Put a proxy in front of OpenAI, Anthropic, Google, or Workers AI to get centralized request logging, response caching, rate limiting, and provider fallback without rewriting SDK calls. See Cloudflare AI Gateway.
  • Vectorize: Managed vector index for semantic search and RAG when SQL LIKE or FTS5 in D1 is no longer enough.
  • Agents SDK: Builds stateful per-user AI agents on top of Durable Objects with SQLite storage, WebSockets, and scheduled tasks.

The operational rule for any public AI endpoint is enforce hard budgets before calling the model. On flaviocopes.com, my interactive AI tools require a verified Turnstile token and check both a per-client daily counter and a global daily cap in KV before env.AI.run() is ever invoked.

A small model can still rack up a painful bill overnight if an unauthenticated loop hammers your endpoint.

Testing and observability

Testing Workers with mocked fetch stubs hides the bugs that break production: D1 SQLite syntax errors, unconsumed R2 streams, broken wrangler.jsonc bindings, and runtime incompatibilities.

Real integration tests in workerd

Use Vitest with Cloudflare’s Workers test runner (@cloudflare/vitest-pool-workers, recently renamed to @cloudflare/vitest-plugin for upcoming releases) so your tests execute inside the actual workerd runtime against real simulated D1, KV, R2, and Queue bindings.

Configure vitest.config.ts:

import { defineWorkersConfig } from '@cloudflare/vitest-pool-workers/config'

export default defineWorkersConfig({
  test: {
    poolOptions: {
      workers: {
        wrangler: { configPath: './wrangler.jsonc' },
      },
    },
  },
})

Add test/env.d.ts so env imported from cloudflare:test inherits your generated Env bindings:

declare module 'cloudflare:test' {
  interface ProvidedEnv extends Env {}
}

Here is a real integration test from PulseWatch (test/worker.test.ts) that tests auth rejection, D1 monitor creation, atomic incident creation, KV cache miss headers, R2 export verification, duplicate Queue deduplication, HMAC signatures, and Turnstile failure handling:

const obj = await env.EXPORTS.get(exported.key)
expect(obj).not.toBeNull()
const snapshot = JSON.parse(await obj!.text()) as { count: number }
expect(snapshot.count).toBe(1)

Running this suite caught a classic Workers testing bug on the very first run: before I added await obj!.text(), leaving the R2 ReadableStream unconsumed caused Failed to pop isolated storage stack frame: unable to pop R2 storage. Always consume or cancel R2ObjectBody and Response streams in tests and production code alike.

With that one line fixed, all five integration tests run inside workerd in 55 ms:

 ✓ test/worker.test.ts (5 tests) 55ms
   ✓ PulseWatch Worker in workerd > rejects unauthenticated admin requests 12ms
   ✓ PulseWatch Worker in workerd > creates a monitor, records a failed check, opens an incident, and exports to R2 23ms
   ✓ PulseWatch Worker in workerd > deduplicates duplicate queue deliveries via D1 idempotency keys 5ms
   ✓ PulseWatch Worker in workerd > signs and verifies webhook payloads with Web Crypto HMAC-SHA256 3ms
   ✓ PulseWatch Worker in workerd > rejects Turnstile form submissions when token is missing 4ms

 Test Files  1 passed (1)
      Tests  5 passed (5)

Structured JSON logs, wrangler tail, and Workers Traces

Plain console.log('error creating monitor') strings are useless once you have thousands of requests per hour. Emit one JSON object per event with requestId, path, status, and durationMs, and enable observability in wrangler.jsonc:

"observability": {
  "enabled": true,
  "head_sampling_rate": 1
}

In development, Local Explorer’s Traces tab records every request, span count, duration, and error automatically. Here are the live traces captured from PulseWatch showing our 401 unauthorized admin probe (red error count 1), POST /admin/export (9 ms, 3 spans), cold GET /api/status (16 ms, 5 spans), and cached GET /api/status (2 ms, 2 spans):

Local Explorer Traces view displaying PulseWatch request durations, span counts, and error flags

In production, inspect live requests from your terminal with:

npx wrangler tail --status error --format pretty

For high-traffic Workers, lower head_sampling_rate (for example 0.1 for 10% sampling) once your app stabilizes so observability volume stays within your included quota. See Cloudflare Workers observability: logs and traces for querying production logs in the dashboard.

CI/CD, gradual deployments, and rollbacks

The safest deployment is the one you can undo in ten seconds without touching your database.

Fig 3 · 1/4Gradual deploy, safe D1 migration, and rollback
Step 1 · Expand D1 schema while v1 serves 100% traffic

Gradual deployments with wrangler versions

Instead of jumping straight from 0% to 100% traffic with wrangler deploy, upload a new immutable Worker version and shift traffic gradually:

# 1. Upload the new build without sending it live traffic yet
npx wrangler versions upload --message "add monitor timeout_ms support"

# 2. Route 90% to the proven version, 10% to the new version
npx wrangler versions deploy

# 3. Inspect recent versions and active traffic split
npx wrangler versions list

Watch Workers Logs and wrangler tail --status error while 10% of real requests hit the new version. If error rates stay flat, promote the new version to 100%.

Instant rollback drill

When a deploy breaks production, do not spend fifteen minutes writing a hotfix under pressure. Roll back first, investigate second:

npx wrangler rollback

wrangler rollback shifts 100% of traffic back to the previous proven version in seconds. This only works cleanly if your D1 migrations follow the expand-and-contract rule so the previous Worker version can still read and write the current schema.

Minimal GitHub Actions pipeline

Automate typechecks, workerd tests, D1 migrations, and deploys in CI using a scoped Cloudflare API token stored in GitHub Secrets (never use your Global API Key):

name: Deploy PulseWatch
on:
  push:
    branches: [main]

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 22
          cache: npm
      - run: npm ci
      - run: npx wrangler types --check
      - run: npx tsc --noEmit
      - run: npm test
      - run: npx wrangler d1 migrations apply pulsewatch --remote
        env:
          CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
          CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
      - run: npx wrangler deploy
        env:
          CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
          CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}

Create a separate Cloudflare API token per project with least privilege: only the permissions that project actually needs (Workers Scripts: Edit, D1: Edit), scoped to the specific account. For pull-request preview environments before merging to main, see How to use Cloudflare Worker Previews.

Cost guardrails that prevent surprise bills

Cloudflare’s $5/month Workers Paid plan includes generous allowances (10 million requests, 30 million CPU milliseconds, 25 billion D1 rows read, 10 GB R2 with zero egress), yet a single coding mistake can blow past any allowance in hours:

  • Keep static assets off your Worker. Scope run_worker_first strictly to dynamic routes.
  • Avoid recursive self-fetches. A Worker that fetches its own public URL without a loop guard can trigger an infinite amplification storm. Use Service Bindings for Worker-to-Worker calls instead of public HTTP.
  • Index every D1 WHERE and ORDER BY column. Verify with EXPLAIN QUERY PLAN so a busy endpoint never runs SCAN.
  • Cap public AI and external API endpoints. Enforce Turnstile + per-IP and global daily limits before spending tokens.
  • Turn on Cloudflare billing notifications under Manage Account > Notifications so you hear about abnormal usage on day one instead of invoice day.

Production debugging, cost control, and Wrangler workflows

Shipping the first deploy is easy. Keeping that Worker calm at 2 a.m. when a webhook fails or a bot starts hammering a route comes down to three daily habits: reading live logs cleanly, knowing which bindings touch real cloud resources, and putting hard cost guardrails in config.

Reading live production logs with wrangler tail

When a user reports a 500 error, open a terminal and filter live logs with wrangler tail before guessing at code changes. You can filter by HTTP status, method, search string, or sampling rate right from the CLI:

# Pretty-print only failing POST requests in production
npx wrangler tail --status error --method POST \
  --format pretty

# Follow logs matching one event name or request ID
npx wrangler tail --search "http_error" --format pretty

# Sample 20% of a busy Worker and pipe JSON logs into jq
npx wrangler tail --sampling-rate 0.2 --format json | \
  jq -r '.logs[].message[0]'

Because our Hono middleware sends x-request-id back to the browser and logs that same ID in every JSON line, you can ask a user for the request ID from their error banner and run npx wrangler tail --search "<id>" or look it up directly in Workers Logs.

Remember that wrangler tail streams live events from the moment you connect. It does not replay past logs, so keep "observability": { "enabled": true } turned on in wrangler.jsonc for historical log search.

Local vs remote bindings in Wrangler 4

Wrangler 4 simulates most Cloudflare bindings locally inside .wrangler/state/v3/, yet a few AI and media bindings always execute remotely against your real Cloudflare account. Know which column every binding falls into before running npx wrangler dev:

BindingDefault in wrangler devTouches live billing?Notes
D1, KV, R2Local .wrangler/state/v3/NoSafe for destructive schema tests
Queues, DOsLocal .wrangler/state/v3/NoFull consumer and alarm support
Static AssetsLocal directoryNoMirrors run_worker_first rules
Workers AIRemote ("remote": true)YesBills real neurons during dev
VectorizeRemote ("remote": true)YesQueries your live vector index
Browser RenderingRemote ("remote": true)YesLaunches remote headless Chrome

If your project splits into two separate Workers in a monorepo (for example, an API Worker and a dedicated Queue consumer Worker), pass --persist-to so both dev servers read and write one shared local database and bucket:

# Terminal 1: API Worker
npx wrangler dev --persist-to ../.shared-state

# Terminal 2: Queue consumer Worker
npx wrangler dev --persist-to ../.shared-state

If local migrations ever get tangled after rebasing branches, wipe only the local simulation directory and re-run migrations from scratch:

rm -rf .wrangler/state
npx wrangler d1 migrations apply pulsewatch --local

Secrets management and zero-downtime rotation

Local secrets live in .dev.vars at your project root. When you test staging locally with npx wrangler dev --env staging, Wrangler looks for .dev.vars.staging first, which lets you keep staging API keys completely separate from default local fixtures.

Add .dev.vars* to .gitignore so neither file ever enters Git history.

On Cloudflare itself, manage secrets per environment with these Wrangler commands:

# Set one production secret interactively
npx wrangler secret put WEBHOOK_SECRET

# Upload a batch of staging secrets from a temporary JSON file
npx wrangler secret bulk staging-secrets.json --env staging
rm staging-secrets.json

# Verify secret names exist (values are never printed)
npx wrangler secret list --env staging

When you rotate a webhook signing secret in production, avoid a hard cutover that breaks in-flight deliveries. Store the old value in WEBHOOK_SECRET_PREVIOUS for 24 hours, update the sender to the new secret, and verify against both keys during the overlap window:

export async function verifyWithRotation(
  env: { WEBHOOK_SECRET: string; WEBHOOK_SECRET_PREVIOUS?: string },
  timestamp: string,
  body: string,
  providedSig: string
): Promise<boolean> {
  const current = await signWebhookPayload(
    env.WEBHOOK_SECRET,
    timestamp,
    body
  )
  if (timingSafeEqualString(providedSig, current)) return true

  if (!env.WEBHOOK_SECRET_PREVIOUS) return false
  const previous = await signWebhookPayload(
    env.WEBHOOK_SECRET_PREVIOUS,
    timestamp,
    body
  )
  return timingSafeEqualString(providedSig, previous)
}

Once the 24-hour window passes and your logs show zero deliveries using the old key, delete the fallback with npx wrangler secret delete WEBHOOK_SECRET_PREVIOUS.

Combined rate limiting and Turnstile middleware

Earlier we saw how to call Turnstile’s siteverify endpoint inside a route. In production, wrap both Cloudflare’s native Workers Rate Limiting binding and Turnstile verification into one reusable Hono middleware so you never forget either check on a new public form.

First, declare the rate limiter in wrangler.jsonc (this runs inside Cloudflare’s edge memory with zero KV write cost):

"ratelimits": [
  {
    "name": "FORM_LIMITER",
    "namespace_id": "1001",
    "simple": {
      "limit": 10,
      "period": 60
    }
  }
]

Now attach a middleware that enforces the rate limit first, calls siteverify, and checks outcome.hostname so an attacker cannot submit a valid Turnstile token copied from another website:

type TurnstileResult = {
  success: boolean
  hostname?: string
  'error-codes'?: string[]
}

export function protectPublicForm(expectedHost: string) {
  return async (c: Context<{ Bindings: Env }>, next: Next) => {
    const ip = c.req.header('cf-connecting-ip') ?? 'unknown'
    const rate = await c.env.FORM_LIMITER.limit({
      key: `${new URL(c.req.url).pathname}:${ip}`,
    })

    if (!rate.success) {
      c.header('retry-after', '60')
      return c.json({ error: 'Too many requests' }, 429)
    }

    const token = c.req.header('x-turnstile-token') ?? ''
    if (!token) {
      return c.json({ error: 'Missing Turnstile token' }, 403)
    }

    const res = await fetch(
      'https://challenges.cloudflare.com/turnstile/v0/siteverify',
      {
        method: 'POST',
        body: new URLSearchParams({
          secret: c.env.TURNSTILE_SECRET_KEY,
          response: token,
          remoteip: ip,
        }),
      }
    )

    const outcome = await res.json<TurnstileResult>()
    if (!outcome.success || outcome.hostname !== expectedHost) {
      return c.json({ error: 'Bot check failed' }, 403)
    }

    await next()
  }
}

Checking the rate limit before siteverify ensures a spam flood stops at the edge without wasting outbound subrequests.

Avoiding surprise billing on Workers, D1, R2, and Workers AI

Cloudflare’s pricing is generous for normal apps, yet every service has one specific coding mistake that can multiply usage overnight. Keep this billing map handy when reviewing pull requests:

ServicePrimary billable unitMistake that spikes billsConcrete guardrail
WorkersRequests + CPU msCatch-all middleware on static assets or self-fetch loopScope run_worker_first and set limits.cpu_ms
D1Rows read + writtenUnindexed WHERE, OFFSET paging, or hot COUNT(*)Check EXPLAIN QUERY PLAN and use cursors
KVReads, writes, listsWriting counters per page view or calling kv.list()Use KV for cached reads and D1 for writes
R2Class A + Class B opsCalling bucket.list() per request on a public pageKeep file indexes in D1 and cache reads
Workers AINeurons per inferenceOpen endpoint without caps or running AI in tight loopsRequire Turnstile, AI Gateway cache, and caps

You can also cap per-request CPU time directly inside wrangler.jsonc so a bad regex or accidental infinite loop fails fast instead of draining your monthly CPU budget:

"limits": {
  "cpu_ms": 50
}

For most CRUD APIs and Hono routes, 50 ms of CPU time is plenty because network waits on D1, R2, and fetch() do not count toward CPU milliseconds.

What I run in production

To ground all of this in systems that take real traffic every day, here is how I actually use Cloudflare across three live products (I also keep a running inventory in The Cloudflare products I actually use):

  1. flaviocopes.com (this blog): Astro static site on Cloudflare with a handful of explicit API functions (functions/api/newsletter/subscribe.js for Turnstile + rate-limited Sendy signups, plus AI tool routes guarded by TOOLS_USAGE KV daily caps), large books/downloads served from R2 at downloads.flaviocopes.com, and a tiny Cron Trigger Worker that rebuilds the site for scheduled posts. Adding .node-version to Git fixed dashboard-vs-wrangler.jsonc build drift, and removing a root middleware eliminated millions of unnecessary function invocations.
  2. support.flaviocopes.com (Mac app support portal): A single Cloudflare Worker backed by D1 for buyers, conversations, and messages, with Resend handling transactional email in both directions. Inbound email replies only post to a customer thread when DKIM/DMARC verification passes for my sender addresses.
  3. updates.flaviocopes.com (licensed Mac app updates): A Cloudflare Worker + D1 registry that verifies Creem purchase webhooks idempotently, stores versioned HMAC-SHA256 license fingerprints, and issues short-lived authorized download URLs for notarized app ZIPs while keeping updates working even if the payment provider has downtime.

Notice what those three production systems have in common: small scope per Worker, explicit wrangler.jsonc config, D1 for relational state, KV only for short-lived counters/cache, R2 for big files, and zero unnecessary services added just because they looked neat in the dashboard.

Six common beginner Cloudflare mistakes

When you deploy your first few sites and Workers on Cloudflare, these six small traps come up often:

  • Leaving SSL on Flexible with an HTTPS origin. That triggers an infinite redirect loop (ERR_TOO_MANY_REDIRECTS). Switch SSL mode to Full (Strict).
  • Putting API secrets inside wrangler.jsonc [vars]. [vars] is plain text committed to Git! Store local secrets in .dev.vars and production secrets with npx wrangler secret put.
  • Using KV as a primary database for relational writes. KV is eventually consistent across regions and can take up to 60 seconds to reflect updates everywhere. Use D1 for users, orders, and relational data.
  • Forgetting nodejs_compat when importing node:crypto. Add "compatibility_flags": ["nodejs_compat"] to wrangler.jsonc whenever you use Node built-in modules.
  • Orange-clouding an SSH or mail subdomain. Cloudflare’s standard proxy only forwards HTTP/HTTPS web traffic, so orange-clouding ssh.yourdomain.com breaks ssh. Keep non-HTTP hostnames gray-clouded (DNS only).
  • Forgetting ctx.waitUntil() for background promises. In Cloudflare Workers, any unawaited Promise gets killed the instant your Worker returns a Response unless you pass it to ctx.waitUntil().

Hands-on Cloudflare exercises

Reading about isolates and bindings only takes you halfway. Work through these ten progressive exercises inside a local Wrangler 4 project (npx wrangler dev and npm test) to build real muscle memory across the whole stack.

Try writing each solution yourself before reading the reference implementation below it.

Exercise 1: Typed Hono routing and security headers

Create a Hono Worker typed with Bindings: Env and Variables: { requestId: string }. Add global middleware that assigns a request ID (using cf-ray or crypto.randomUUID()), attaches x-request-id and x-content-type-options: nosniff to every response, serves GET /api/health with { ok: true, env: c.env.ENVIRONMENT }, and returns a clean JSON 404 for unknown /api/* paths.

Here is one clean solution:

import { Hono } from 'hono'

type AppEnv = {
  Bindings: Env
  Variables: { requestId: string }
}

const app = new Hono<AppEnv>()

app.use('*', async (c, next) => {
  const id = c.req.header('cf-ray') ?? crypto.randomUUID()
  c.set('requestId', id)
  await next()
  c.header('x-request-id', id)
  c.header('x-content-type-options', 'nosniff')
})

app.get('/api/health', (c) => {
  return c.json({
    ok: true,
    env: c.env.ENVIRONMENT,
    requestId: c.get('requestId'),
  })
})

app.notFound((c) => {
  return c.json(
    { error: 'Route not found', requestId: c.get('requestId') },
    404
  )
})

export default app

Exercise 2: KV cache-aside with negative caching

Build GET /api/flags/:name backed by D1 table feature_flags(name TEXT PRIMARY KEY, enabled INTEGER NOT NULL) and KV binding STATUS_CACHE. Read from key v1:flag:${name} first. On a miss, query D1, return the answer immediately, and populate KV via ctx.waitUntil() with a 120-second TTL for found flags and a 60-second TTL for { found: false } negative entries.

Here is one clean solution:

type CachedFlag =
  | { found: true; enabled: boolean }
  | { found: false }

app.get('/api/flags/:name', async (c) => {
  const name = c.req.param('name')
  const key = `v1:flag:${name}`

  const cached = await c.env.STATUS_CACHE.get<CachedFlag>(
    key,
    'json'
  )
  if (cached) {
    c.header('x-cache', cached.found ? 'HIT' : 'NEG-HIT')
    if (!cached.found) return c.json({ error: 'Not found' }, 404)
    return c.json({ name, enabled: cached.enabled })
  }

  const row = await c.env.DB.prepare(
    `SELECT enabled FROM feature_flags WHERE name = ?`
  )
    .bind(name)
    .first<{ enabled: number }>()

  const entry: CachedFlag = row
    ? { found: true, enabled: row.enabled === 1 }
    : { found: false }

  c.executionCtx.waitUntil(
    c.env.STATUS_CACHE.put(key, JSON.stringify(entry), {
      expirationTtl: row ? 120 : 60,
    })
  )

  c.header('x-cache', 'MISS')
  if (!row) return c.json({ error: 'Not found' }, 404)
  return c.json({ name, enabled: row.enabled === 1 })
})

Exercise 3: D1 CRUD API and versioned migration

Create a numbered SQL migration migrations/0003_notes.sql for a notes table with columns id, owner_id, body, and created_at, plus a composite index that speeds up listing one owner’s newest notes. Then write POST /api/notes and GET /api/notes?owner=... using bound parameters only, and show the Wrangler command that applies the migration locally.

Here is one clean solution:

-- migrations/0003_notes.sql
CREATE TABLE notes (
  id TEXT PRIMARY KEY,
  owner_id TEXT NOT NULL,
  body TEXT NOT NULL,
  created_at TEXT NOT NULL DEFAULT (datetime('now'))
);

CREATE INDEX idx_notes_owner_created
  ON notes(owner_id, created_at DESC);

Apply the migration locally before starting the Worker:

npx wrangler d1 migrations apply pulsewatch --local

Now wire the two parameterized Hono routes:

app.post('/api/notes', async (c) => {
  const input = await c.req.json<{
    ownerId?: string
    body?: string
  }>()
  if (!input.ownerId || !input.body) {
    return c.json({ error: 'ownerId and body required' }, 400)
  }

  const id = crypto.randomUUID()
  await c.env.DB.prepare(
    `INSERT INTO notes (id, owner_id, body) VALUES (?, ?, ?)`
  )
    .bind(id, input.ownerId, input.body)
    .run()

  return c.json({ id, ownerId: input.ownerId }, 201)
})

app.get('/api/notes', async (c) => {
  const owner = c.req.query('owner')
  if (!owner) return c.json({ error: 'owner is required' }, 400)

  const { results } = await c.env.DB.prepare(
    `SELECT id, body, created_at
     FROM notes
     WHERE owner_id = ?
     ORDER BY created_at DESC
     LIMIT 20`
  )
    .bind(owner)
    .all()

  return c.json({ notes: results })
})

Exercise 4: Validated R2 upload and streaming download

Implement PUT /api/avatars/:id using R2 binding EXPORTS. Accept only image/png or image/webp and reject uploads larger than 2 MB. Then implement GET /api/avatars/:id so it streams object.body, sets Cache-Control and ETag, and returns 304 Not Modified when If-None-Match matches.

Here is one clean solution:

const AVATAR_MIME = new Set(['image/png', 'image/webp'])
const MAX_AVATAR_BYTES = 2 * 1024 * 1024

app.put('/api/avatars/:id', async (c) => {
  const mime = (c.req.header('content-type') ?? '').split(';')[0]
  if (!AVATAR_MIME.has(mime)) {
    return c.json({ error: 'Only PNG and WebP allowed' }, 415)
  }

  const size = Number(c.req.header('content-length') ?? '0')
  if (size <= 0 || size > MAX_AVATAR_BYTES) {
    return c.json({ error: 'File must be under 2 MB' }, 413)
  }

  const data = await c.req.arrayBuffer()
  if (data.byteLength > MAX_AVATAR_BYTES) {
    return c.json({ error: 'File exceeds 2 MB limit' }, 413)
  }

  const key = `avatars/${c.req.param('id')}`
  await c.env.EXPORTS.put(key, data, {
    httpMetadata: {
      contentType: mime,
      cacheControl: 'public, max-age=86400',
    },
  })

  return c.json({ key, bytes: data.byteLength }, 201)
})

app.get('/api/avatars/:id', async (c) => {
  const object = await c.env.EXPORTS.get(
    `avatars/${c.req.param('id')}`
  )
  if (!object) return c.json({ error: 'Not found' }, 404)

  if (c.req.header('if-none-match') === object.httpEtag) {
    return new Response(null, {
      status: 304,
      headers: { etag: object.httpEtag },
    })
  }

  const headers = new Headers()
  object.writeHttpMetadata(headers)
  headers.set('etag', object.httpEtag)
  headers.set('x-content-type-options', 'nosniff')
  return new Response(object.body, { headers })
})

Exercise 5: Cron Trigger health checker with timeouts

Configure a Cron Trigger in wrangler.jsonc that runs every 10 minutes. Write a scheduled() handler that loads enabled monitors from D1, fetches each URL with AbortSignal.timeout(4000), cancels the response body to free the socket, and writes every check run in one env.DB.batch() call.

Here is one clean solution, starting with the wrangler.jsonc trigger block:

"triggers": {
  "crons": ["*/10 * * * *"]
}

Now implement the scheduled export:

export default {
  fetch: app.fetch,
  async scheduled(_ctrl: ScheduledController, env: Env) {
    const { results } = await env.DB.prepare(
      `SELECT id, url, expected_status
       FROM monitors WHERE enabled = 1`
    ).all<{
      id: string
      url: string
      expected_status: number
    }>()

    const writes: D1PreparedStatement[] = []
    for (const mon of results) {
      const started = Date.now()
      let statusCode = 0
      try {
        const res = await fetch(mon.url, {
          signal: AbortSignal.timeout(4000),
        })
        statusCode = res.status
        await res.body?.cancel()
      } catch {
        statusCode = 0
      }

      const ok = statusCode === mon.expected_status ? 1 : 0
      writes.push(
        env.DB.prepare(
          `INSERT INTO check_runs
             (id, monitor_id, status_code, latency_ms, ok)
           VALUES (?, ?, ?, ?, ?)`
        ).bind(
          crypto.randomUUID(),
          mon.id,
          statusCode,
          Date.now() - started,
          ok
        )
      )
    }

    if (writes.length > 0) await env.DB.batch(writes)
  },
}

Exercise 6: Queues producer, idempotent consumer, and DLQ

Configure a queue named jobs-queue with max_retries: 3 and dead_letter_queue: "jobs-dlq" in wrangler.jsonc. Add POST /api/jobs that enqueues { jobId, email }, and write a queue() handler that guards against duplicate delivery with INSERT OR IGNORE in D1 and retries transient failures with a 30-second delay.

Here is one clean solution, starting with wrangler.jsonc:

"queues": {
  "producers": [
    { "binding": "JOBS_QUEUE", "queue": "jobs-queue" }
  ],
  "consumers": [
    {
      "queue": "jobs-queue",
      "max_batch_size": 10,
      "max_retries": 3,
      "dead_letter_queue": "jobs-dlq"
    }
  ]
}

Now add the producer route and idempotent consumer:

type JobMsg = { jobId: string; email: string }

app.post('/api/jobs', async (c) => {
  const { email } = await c.req.json<{ email: string }>()
  const jobId = crypto.randomUUID()
  await c.env.JOBS_QUEUE.send({ jobId, email })
  return c.json({ queued: true, jobId }, 202)
})

export async function queue(
  batch: MessageBatch<JobMsg>,
  env: Env
) {
  for (const msg of batch.messages) {
    try {
      const res = await env.DB.prepare(
        `INSERT OR IGNORE INTO processed_jobs (job_id)
         VALUES (?)`
      )
        .bind(msg.body.jobId)
        .run()

      if (res.meta.changes === 0) {
        msg.ack()
        continue
      }

      console.log('Sending welcome mail to', msg.body.email)
      msg.ack()
    } catch {
      msg.retry({ delaySeconds: 30 })
    }
  }
}

Exercise 7: Edge cache and audit logging with ctx.waitUntil()

Write GET /api/changelog that checks caches.default using a normalized URL key without query parameters. On a hit, return immediately with x-edge-cache: HIT. On a miss, fetch the latest ten entries from D1, return the JSON with Cache-Control: public, s-maxage=300, and use c.executionCtx.waitUntil() to populate the edge cache and write a structured log event without delaying the response.

Here is one clean solution:

app.get('/api/changelog', async (c) => {
  const url = new URL(c.req.url)
  const key = new Request(`${url.origin}${url.pathname}`)
  const cache = caches.default

  const cached = await cache.match(key)
  if (cached) {
    const hit = new Response(cached.body, cached)
    hit.headers.set('x-edge-cache', 'HIT')
    return hit
  }

  const { results } = await c.env.DB.prepare(
    `SELECT id, summary, opened_at
     FROM incidents ORDER BY opened_at DESC LIMIT 10`
  ).all()

  const body = JSON.stringify({ entries: results })
  const res = new Response(body, {
    headers: {
      'content-type': 'application/json; charset=utf-8',
      'cache-control': 'public, s-maxage=300',
      'x-edge-cache': 'MISS',
    },
  })

  c.executionCtx.waitUntil(
    cache.put(key, res.clone()).then(() => {
      console.log(
        JSON.stringify({
          event: 'changelog_cache_filled',
          count: results.length,
        })
      )
    })
  )

  return res
})

Exercise 8: Turnstile verification and rate-limited contact form

Protect POST /api/contact by checking c.env.FORM_LIMITER.limit({ key }) keyed by client IP first. If allowed, read { email, message, turnstileToken } from the JSON body, verify the token against Cloudflare Turnstile siteverify, confirm outcome.hostname === 'example.com', and return 403 whenever verification fails.

Here is one clean solution:

app.post('/api/contact', async (c) => {
  const ip = c.req.header('cf-connecting-ip') ?? 'local'
  const limit = await c.env.FORM_LIMITER.limit({
    key: `contact:${ip}`,
  })
  if (!limit.success) {
    c.header('retry-after', '60')
    return c.json({ error: 'Rate limit exceeded' }, 429)
  }

  const body = await c.req.json<{
    email?: string
    message?: string
    turnstileToken?: string
  }>()
  if (!body.email || !body.message || !body.turnstileToken) {
    return c.json({ error: 'Missing required fields' }, 400)
  }

  const verifyRes = await fetch(
    'https://challenges.cloudflare.com/turnstile/v0/siteverify',
    {
      method: 'POST',
      body: new URLSearchParams({
        secret: c.env.TURNSTILE_SECRET_KEY,
        response: body.turnstileToken,
        remoteip: ip,
      }),
    }
  )

  const outcome = await verifyRes.json<{
    success: boolean
    hostname?: string
  }>()
  if (!outcome.success || outcome.hostname !== 'example.com') {
    return c.json({ error: 'Turnstile verification failed' }, 403)
  }

  return c.json({ received: true }, 201)
})

Exercise 9: Multi-environment wrangler.jsonc overrides

Write a complete wrangler.jsonc that defines a production Worker (myapp) with D1, KV, ENVIRONMENT: "production", and LOG_SAMPLE_RATE: "0.1". Add an env.staging block (myapp-staging) that explicitly declares its own isolated D1 database, KV namespace, and "LOG_SAMPLE_RATE": "1". Include the commands to set a staging secret and deploy to staging.

Here is one clean solution:

{
  "$schema": "./node_modules/wrangler/config-schema.json",
  "name": "myapp",
  "main": "src/index.ts",
  "compatibility_date": "2026-11-24",
  "compatibility_flags": ["nodejs_compat"],
  "vars": {
    "ENVIRONMENT": "production",
    "LOG_SAMPLE_RATE": "0.1"
  },
  "d1_databases": [
    {
      "binding": "DB",
      "database_name": "myapp-prod",
      "database_id": "11111111-1111-1111-1111-111111111111"
    }
  ],
  "kv_namespaces": [
    {
      "binding": "STATUS_CACHE",
      "id": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
    }
  ],
  "env": {
    "staging": {
      "name": "myapp-staging",
      "vars": {
        "ENVIRONMENT": "staging",
        "LOG_SAMPLE_RATE": "1"
      },
      "d1_databases": [
        {
          "binding": "DB",
          "database_name": "myapp-staging",
          "database_id": "22222222-2222-2222-2222-222222222222"
        }
      ],
      "kv_namespaces": [
        {
          "binding": "STATUS_CACHE",
          "id": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"
        }
      ]
    }
  }
}

Push the staging secret and deploy with --env staging:

npx wrangler secret put ADMIN_TOKEN --env staging
npx wrangler deploy --env staging

Exercise 10: Integration tests in workerd with Vitest

Write a Vitest integration test using cloudflare:test (env, SELF) that creates the notes table in the simulated D1 database, calls POST /api/notes and GET /api/notes?owner=u1 through SELF.fetch(), and writes then reads a small file in R2 while consuming the stream so isolated storage tears down cleanly.

Here is one clean solution:

import { env, SELF } from 'cloudflare:test'
import { beforeAll, describe, expect, it } from 'vitest'

describe('Notes API and R2 in workerd', () => {
  beforeAll(async () => {
    await env.DB.prepare(
      `CREATE TABLE IF NOT EXISTS notes (
         id TEXT PRIMARY KEY,
         owner_id TEXT NOT NULL,
         body TEXT NOT NULL,
         created_at TEXT NOT NULL DEFAULT (datetime('now'))
       )`
    ).run()
  })

  it('creates and lists notes for an owner', async () => {
    const createRes = await SELF.fetch(
      'https://example.com/api/notes',
      {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({
          ownerId: 'u1',
          body: 'Check D1 indexes',
        }),
      }
    )
    expect(createRes.status).toBe(201)

    const listRes = await SELF.fetch(
      'https://example.com/api/notes?owner=u1'
    )
    expect(listRes.status).toBe(200)
    const data = await listRes.json<{
      notes: Array<{ body: string }>
    }>()
    expect(data.notes[0].body).toBe('Check D1 indexes')
  })

  it('writes and fully reads an R2 object', async () => {
    await env.EXPORTS.put('test/hello.txt', 'ok')
    const obj = await env.EXPORTS.get('test/hello.txt')
    expect(obj).not.toBeNull()
    expect(await obj!.text()).toBe('ok')
  })
})

Run the suite with npx vitest run. Because await obj!.text() drains the R2ObjectBody stream before the test ends, workerd pops the isolated storage frame cleanly with zero warnings.

Everyday Wrangler CLI quick reference

What you wantCommand
Log in to Cloudflarenpx wrangler login
Run Worker locallynpx wrangler dev
Deploy to productionnpx wrangler deploy
Push a production secretnpx wrangler secret put API_KEY
Tail live production logsnpx wrangler tail
Run D1 SQL migrationnpx wrangler d1 migrations apply mydb --remote
Regenerate TypeScript typesnpx wrangler types

Pre-launch checklist and cheat sheet

Run through this operational checklist before pointing a custom domain at a new Cloudflare app:

  • wrangler.jsonc is the single source of truth (compatibility_date set, nodejs_compat enabled, env.staging bindings declared explicitly).
  • npx wrangler types --check and npx tsc --noEmit pass with zero errors.
  • Zero secrets in Git or wrangler.jsonc, .dev.vars is gitignored, and production secrets are pushed via wrangler secret put.
  • run_worker_first only matches API/SSR routes, so static images, fonts, and CSS serve directly from Static Assets.
  • Every hot D1 query returns SEARCH ... USING INDEX in EXPLAIN QUERY PLAN, and all schema changes live in migrations/.
  • Multi-statement D1 writes use env.DB.batch(), and migrations follow expand-and-contract.
  • Every Queue consumer is idempotent (INSERT OR IGNORE or unique constraint) and has a configured dead_letter_queue.
  • Every public form verifies Turnstile server-side and has rate limiting, and every authenticated route returns Cache-Control: private, no-store.
  • Every Worker secret/HMAC comparison uses timingSafeEqual, and every large R2 response streams object.body.
  • observability.enabled is true, logs are structured JSON with a request ID, and npx wrangler check startup is well under the 400 ms ceiling.
  • Vitest tests pass inside workerd (npm test), and you have tested npx wrangler rollback on staging at least once.
  • Cloudflare SSL/TLS is set to Full (strict), billing alerts are enabled, and CI deploys with a least-privilege API token.

Wrangler quick-reference cheat sheet

# Development & typing
npx wrangler dev                                        # Run locally with simulated bindings
npx wrangler types                                      # Generate worker-configuration.d.ts
npx wrangler types --check                              # Verify types match wrangler.jsonc (CI)
npx wrangler check startup                              # Profile Worker bundle & startup CPU

# D1 databases & recovery
npx wrangler d1 migrations create <db> <name>           # Create a new SQL migration file
npx wrangler d1 migrations apply <db> --local           # Apply pending migrations locally
npx wrangler d1 migrations apply <db> --remote          # Apply pending migrations to production
npx wrangler d1 execute <db> --local --command "..."    # Run ad-hoc SQL or EXPLAIN QUERY PLAN
npx wrangler d1 time-travel info <db>                   # Inspect current restore bookmark
npx wrangler d1 export <db> --remote --output dump.sql  # Export SQL snapshot

# Secrets, versions & rollbacks
npx wrangler secret put SECRET_NAME                     # Set production secret interactively
npx wrangler secret put SECRET_NAME --env staging       # Set staging secret interactively
npx wrangler versions upload --message "..."            # Upload new immutable Worker version
npx wrangler versions deploy                            # Shift traffic gradually across versions
npx wrangler rollback                                   # Restore previous proven version in seconds

# Live debugging
npx wrangler tail --status error --format pretty        # Stream production errors in real time

All individual Cloudflare deep dives and single-product tutorials stay indexed on the cloudflare tag page.

Want me to talk about your product? You can sponsor this site.

Related posts about cloudflare: