Back to Cloudflare

Test Workers and Release Changes Safely

November 5, 2026 Wasil Zafar 21 min read

Separate local confidence from hosted integration evidence

Table of Contents

  1. Tests Answer Different Questions at Each Layer
  2. Runtime Tests and Real Service Bindings
  3. Previews Are Not the Same as Production
  4. Rollbacks Need Code and Data Compatibility
  5. Build a Small Worker Release Gate
  6. Demonstrate a Failing Check Blocks a Bad Release

Tests Answer Different Questions at Each Layer

A green unit test can still deploy a broken Worker. Imagine a small webhook relay. It receives a payload, checks an HMAC signature against a secret, writes the event to KV, and returns 202. A developer writes a unit test that passes a hand-built environment object containing a fake binding, calls the handler, and asserts the fake recorded the write. The test is green. The code is then uploaded to a branch preview, where every request returns 500. The preview's configuration never declared the binding, so the real one is missing and the runtime throws before the handler writes anything. The unit test was not wrong about the logic. It was answering a different question.

That gap is the article's subject. A unit test exercises your code with dependencies replaced or simplified. A runtime integration test runs the whole Worker module inside the Workers runtime, with bindings backed by a local emulator such as Miniflare. A hosted smoke test sends a request to a deployed copy and checks the response, headers, and side effects that only exist on Cloudflare. None replaces the others, because each sits behind a different boundary.

Three terms matter before configuration. A version is an immutable snapshot of your Worker's bundled code, static assets, bindings, and compatibility settings. A deployment decides which version or versions receive traffic. A Preview is a branch-scoped hosted copy of the Worker with its own URL and, for some resources, its own storage. Keeping them distinct makes a safe release possible.

The useful analogy is flight testing: a simulator is cheap and repeatable, a taxi test proves the systems work together on the ground, and a supervised test flight proves the aircraft under real conditions. You would not board passengers after only the simulator, and you would not skip the simulator because you have a test flight. Figure 1 shows the same progression for a Worker, including the failure each layer is designed to catch.

Tests Answer Different Questions at Each Layer
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
    A["Unit test
handler + fake env"] --> B{"Logic correct?"} B -->|"yes"| C["Runtime integration
workerd + local bindings"] B -->|"no"| X["Fix code"] C --> D{"Bindings resolve
in local config?"} D -->|"no"| Y["Fail fast:
missing binding"] D -->|"yes"| E["Preview
branch-isolated resources"] E --> F{"Hosted route, secret,
and binding agree?"} F -->|"no"| Z["Block promotion:
1101 or auth drift"] F -->|"yes"| G["Hosted smoke
0% version or canary"] G --> H{"Production path
within budget?"} H -->|"no"| R["Roll back or hold"] H -->|"yes"| I["Promote to 100%"] classDef primary fill:#132440,color:#ffffff,stroke:#0b172b; classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a; classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f; classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420; classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f; class A,B,C,X,D,E,F,H,R,I secondary; class Y,Z danger; class G warn;

The trust boundary is the important part, not the number of tests. Everything left of the preview runs on hardware you control, so you can inspect it, reset it, and run it offline. Everything right of it runs on Cloudflare, where routes, secrets, service bindings, and resource identities come from account state rather than from your laptop. Figure 2 draws that boundary explicitly: the runtime can be identical on both sides while the configuration and data are not.

Test layers and trust boundaries for a Worker release Local unit and runtime tests run on CI hardware. A Preview runs in Cloudflare with isolated branch resources. Production runs the deployed version against live data. Laptop or CI runner Preview on Cloudflare Production You control the process Cloudflare controls the process Cloudflare controls the process Unit test fake env, mocked fetch Runtime integration workerd + Miniflare bindings Preview deployment branch URL, own secrets Hosted smoke test real DNS, TLS, routes Canary version 5–10% real traffic Promotion 100% or rollback same runtime promote no live data live data and routes Configuration is re-read from account state here

Runtime Tests and Real Service Bindings

Let the runtime execute the module. Cloudflare's current Vitest integration is a dedicated plugin package that replaced the older pool package in 2026. It runs Vitest inside the Workers runtime using Miniflare, gives tests access to the runtime modules, and isolates storage per test file. Setup is a plugin call pointed at your Wrangler configuration.

Two integration styles plus one escape hatch.

StyleWhat executesUse it when
Handler importYour Worker module and worker.fetch() with a context from createExecutionContext()You want the handler in the test runner's module graph
Default exportexports.default.fetch() as an entrypointYou want a real request shape but can still share Vite resolution
Auxiliary WorkerA separate Worker entrypoint in the test harnessModule-level state matters

The same webhook route can be checked at five levels, each with a different blind spot.

MechanismWhat executesIsolation boundaryEvidence it gives you
Unit test importing the handlerYour function with a hand-built env and stubbed dependenciesLocal process, no networkResponse shape, branching, and business logic
Vitest runtime test via exports.default.fetch()The Worker entrypoint in workerd with Miniflare-backed bindingsLocal per-test-file storageRouting, middleware, and binding calls through the runtime
wrangler dev --remoteThe Worker in a Cloudflare preview environment with remote bindingsOnly the resources you configureBehavior against real services while you debug
wrangler previewA branch copy under the same Worker with previews settingsPer-Preview Durable Objects and containers; KV, D1, and R2 only if separate IDsHosted routing, secrets, and bindings on a branch URL
Version URL after wrangler versions uploadOne uploaded versionProduction resources for that versionThe exact artifact you may later deploy
Gradual deployment at 0–10%Production deployment with two versionsReal production data and trafficProduction behavior before full promotion

The table also exposes a product boundary. Previews are the recommended branch workflow, but they are not a clone of production. A Preview gets its own Durable Object namespace and container instances automatically. KV, D1, R2, Queues, Vectorize, Hyperdrive, and Workflows are isolated only when bound to separate resources. Service bindings from a Preview call the bound Worker's production deployment. Queue consumers and Cron Triggers do not target a Preview. Version URLs run one uploaded version with production resources, so they inspect an artifact rather than test a branch.

Figure 3 traces a runtime test and a hosted check through a binding, including the two failure branches that matter most: a missing local binding and a drifted previews block.

Runtime Tests and Real Service Bindings
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
sequenceDiagram
    autonumber
    participant CI as CI job
    participant W as Worker in workerd
    participant B as Binding (KV, D1, R2)
    CI->>W: exports.default.fetch("/webhook")
    W->>B: env.HOOKS.put(key, body)
    alt binding exists
        B-->>W: success
        W-->>CI: 202 Accepted
    else binding missing or misnamed
        B-->>W: runtime error 1101
        W-->>CI: 500
    end
    CI->>W: GET preview URL /health
    alt previews block matches top level
        W-->>CI: 200 {"ok":true}
    else previews block drifted
        W-->>CI: 500 or stale response
    end

A test becomes evidence when the shell around it can fail. The widget below pairs a minimal release-gate test with the shell steps that turn it into a gate. The test panel assumes the plugin is registered in the Vitest config and that the Worker exposes a webhook route and a health route; the shell panel runs type generation, tests, uploads, a Preview deployment, a hosted smoke request, and promotion.

import { exports } from "cloudflare:workers";
import { describe, expect, it } from "vitest";

describe("release gate", () => {
	it("rejects an unsigned webhook", async () => {
		const response = await exports.default.fetch("https://gate.test/webhook", {
			method: "POST",
			headers: { "content-type": "application/json" },
			body: JSON.stringify({ id: "evt_1" }),
		});

		expect(response.status).toBe(401);
		await expect(response.json()).resolves.toMatchObject({
			error: "missing signature",
		});
	});

	it("reports healthy from the Worker entrypoint", async () => {
		const response = await exports.default.fetch("https://gate.test/health");

		expect(response.status).toBe(200);
		expect(response.headers.get("content-type")).toContain("application/json");
		await expect(response.json()).resolves.toMatchObject({ ok: true });
	});
});
set -euo pipefail
: "${WORKERS_SUBDOMAIN:?set WORKERS_SUBDOMAIN to your workers.dev subdomain}"
TAG="ci-${GITHUB_SHA::7}"
PREVIEW_NAME="pr-${GITHUB_REF_NAME//\//-}"
npm ci
npx wrangler types --check
npx vitest run
npx wrangler versions upload --tag "$TAG" --dry-run
npx wrangler versions upload --tag "$TAG"
npx wrangler preview --name "$PREVIEW_NAME" --tag "$TAG"
PREVIEW_URL="https://${PREVIEW_NAME}-gate-demo.${WORKERS_SUBDOMAIN}.workers.dev"
curl --fail --silent --show-error "$PREVIEW_URL/health" | jq -e '.ok == true'
curl --fail --silent --show-error -X POST "$PREVIEW_URL/webhook" -H 'content-type: application/json' -d '{"id":"evt_1"}' -o /dev/null -w '%{http_code}\n' | grep -qx '401'
npx wrangler versions deploy --version-tag "$TAG@100%" --yes
npx wrangler deployments list

Secrets follow their own lifecycle. A Preview is created with a copy of the base secret values, not a live link to production.

Secrets are copied at creation

Shared Preview secrets are set once in the Previews base configuration and copied into each new Preview at creation. Changing the base later affects only new Previews; an existing Preview keeps the old value until you update it. Previews do not inherit production secrets, and secrets.required is validated during a version upload or deploy, so a missing required secret can fail before traffic moves.

Previews Are Not the Same as Production

A green Preview is not a production proof. The most expensive misconception in this area is that a Preview passing its checks proves the production configuration is valid. It does not. A Preview is a separate environment with its own settings, and the things it cannot exercise are exactly the things that tend to break at 2 a.m.: Cron Triggers, Queue consumers, production routes, and cross-Worker service bindings.

Describe what a Preview does prove. A Preview is excellent evidence that the branch builds, that the route responds, that a secret is present, and that a binding points at something. It is weak evidence about production data shape, scheduled execution, and downstream Workers, because those live outside the Preview's boundary.

Drift arrives through ordinary settings. Four differences explain most false greens.

SettingPreview behaviorFailure it creates
Top-level varsNot inherited; the previews block must repeat themThe environment variable is undefined on the branch
D1 bindingIsolated only when the previews block names a separate databaseThe branch passes against stale staging rows
Preview URLPublic by default; workers.dev sends X-Robots-Tag: noindexNoindex is not access control; add Cloudflare Access for custom-domain hostnames with sensitive content
Base secretsCopied at Preview creation, not synchronized laterA rotation silently leaves old credentials in place

Make configuration observable. Return the environment name and the version ID from a health route, then compare the Preview response, the Version URL response, and the production response. A mismatch in APP_ENV is a configuration defect, not a routing mystery. The version metadata binding and structured logs support the same comparison without exposing internals.

Rollbacks Need Code and Data Compatibility

A rollback moves traffic, not data.

A rollback is not a time machine

wrangler rollback creates a new deployment that routes 100% of traffic to a previously published version. It does not restore deleted KV namespaces, undo a D1 migration, recreate an R2 bucket, or reverse a Durable Object class lifecycle change. It is refused if a bound resource was deleted or if a Durable Object lifecycle change occurred between the target and active versions, and it can target only the 100 most recently published versions.

The rule: the previous version must remain compatible with the data written by the version you are rolling back from. Schema changes need an expand-and-contract sequence. Add the new column or table, deploy code that can read both shapes, backfill, switch reads, and only then remove the old field in a later release. If the release drops a column that the previous version still selects, rollback either fails at the platform boundary or succeeds into a 500 loop.

A composite incident shows the shape. A team ships version 42 with a D1 migration that renames email to email_normalized and updates the query. Version 41 is still the rollback target. The migration runs before promotion, the rename drops the old column, and version 41's query for the old column fails. The deployment can move but the data cannot. The outage lasts until they add the old column back and backfill it.

The safe release is shown in the top half of Figure 4: the migration adds a column, both versions can read the old one, and rollback is boring. The bottom half shows the destructive version, where the rollback target no longer matches the schema.

Code and data compatibility during rollback An additive migration keeps the old column so the previous version still works. A destructive migration removes the old column and breaks the rollback target. Safe: additive migration Version 41 SELECT email still deployed D1 schema email retained email_normalized added Version 42 writes both columns reads new column reads writes Rollback works: the old column and old code still agree. Unsafe: destructive migration Version 41 SELECT email rollback target D1 schema email dropped email_normalized only Version 42 renames and drops in one migration reads drops Rollback target fails: column missing at runtime.

Canaries reduce rollback pressure, not compatibility work.

Version skew needs a data plan

Gradual deployments route a percentage of requests to a new version, and version overrides send a specific request to a version even when it is at 0%. That lets you smoke-test production code before exposing it to real traffic. The tradeoff is version skew: consecutive requests from one user can hit different versions unless you set the Cloudflare-Workers-Version-Key header for affinity. Any state that spans requests, including carts, sessions, and Durable Objects, needs a compatibility plan for the skew window.

Build a Small Worker Release Gate

A design-only lab: prove the gate fails before it passes. It has not been executed for this article, and no timing, error rate, or cost result is claimed. Run it against a controlled Worker and a dedicated preview namespace.

# 1. Toolchain: Wrangler 4.135+ is required for Previews.
npm i -D wrangler@^4.135.0 vitest@^4.1.0 @cloudflare/vitest-plugin

# 2. wrangler.jsonc: name gate-demo, main src/index.ts, current compatibility_date
#    secrets.required: ["WEBHOOK_SECRET"]
#    previews.vars: { "APP_ENV": "preview" }
#    previews.kv_namespaces: [{ "binding": "HOOKS", "id": "<dedicated-preview-namespace-id>" }]

# 3. Local suite
npx vitest run

# 4. Create the branch Preview, then smoke both routes.
npx wrangler preview --name gate-demo
PREVIEW_URL="https://<preview-name>-gate-demo.<workers-subdomain>.workers.dev"
curl --fail --silent --show-error "$PREVIEW_URL/health" | jq -e '.ok == true'
curl --silent --show-error -X POST "$PREVIEW_URL/webhook" -o /dev/null -w '%{http_code}\n'

# 5. Remove HOOKS from the previews block only, redeploy, and repeat step 4.

# 6. Restore the binding and promote only after the hosted checks pass.
TAG="lab-release"
npx wrangler versions upload --tag "$TAG"
npx wrangler versions deploy --version-tag "$TAG@100%" --yes

# 7. Cleanup
npx wrangler preview delete --name gate-demo --skip-confirmation
Guided exercise

Build a Small Worker Release Gate

Status: design-only, not executed. No Wrangler command, Preview deployment, or hosted request was run for this article.

Prerequisites. Node.js 20 or later, Wrangler 4.135.0 or later (required for Previews), Vitest 4.1 or later, the Vitest plugin, and a Cloudflare account with a workers.dev subdomain. Previews work on Free and Paid plans; documented limits are 100 Previews per Worker on Free, 500 on Paid, and 100 deployments per Preview. Use a dedicated KV namespace, never a production namespace.

Setup. Create a Worker named gate-demo with a current compatibility date, a required webhook secret, and a previews block that binds HOOKS to the dedicated namespace. The health route returns ok plus the environment name; the webhook route returns 401 unless an x-signature header is present. Keep the test-only secret in a local dev-vars file.

  1. Install the pinned toolchain from the widget.
  2. Run the suite. Expect two passing tests: the unsigned webhook returns 401, and the health route returns 200 with JSON.
  3. Create the Preview. Expect a Preview URL and a separate deployment URL.
  4. Request both routes on the Preview URL. Expect health 200 with the preview environment, and the unsigned webhook 401.
  5. Remove HOOKS from the previews block only, leaving the top-level binding intact, redeploy, and request both routes again.
  6. Restore the binding and promote only after the hosted check passes. For the full gate, upload a tag, create a 0% deployment, smoke it with the version-overrides header, then move traffic in steps.
ObservationLocal suiteHosted Preview
Before the defectTwo passing testsHealth 200, unsigned webhook 401
After removing the Preview bindingStill passingBinding error such as 1101

Expected observation. The defect is invisible locally and visible to the hosted check, so the gate stops before promotion.

Failure checks. If the local test fails after removing HOOKS, you edited the top-level block. If the hosted request still returns 200, confirm you are hitting the new deployment URL rather than an older Preview URL.

Cost. The exercise consumes Preview deployments, Worker requests, KV operations, and version storage. No paid add-ons are required, but repeated runs count against the limits above; check current pricing before running at scale.

Cleanup. Delete the Preview, delete the dedicated namespace, and remove the local secret file. Tagged versions age out of the 100-version retention window.

Demonstrate a Failing Check Blocks a Bad Release

Four independent signals, one gate. Each fails for a different reason, and any non-zero step stops the pipeline before deployment.

SignalCommandFails when
Logicnpx vitest runA handler assertion breaks
Typesnpx wrangler types --checkThe generated Env type no longer matches the configuration
Build and validationnpx wrangler versions upload --dry-runBundling or configuration validation fails
Hosted responsecurl --fail on the PreviewThe route returns non-2xx

The failing-check trace is deliberately simple. The unsigned webhook test expects 401. A regression changes the handler to return 200 for every request. Vitest reports one failed assertion and exits 1; the workflow never uploads a version. If the regression lives only in the hosted configuration, the local suite passes, the Preview smoke request returns 500 or a binding error, and the smoke check exits non-zero. Neither result was measured for this article.

Why can a green unit test still ship a 1101? The unit test supplied the binding object itself. 1101 means the Worker referenced a binding the runtime did not provide, a configuration fact the unit test never checked. The runtime test and Preview close that gap.

Does wrangler rollback undo a D1 migration? No. It creates a new deployment pointing at an older version; the schema and rows are unchanged. That is why the previous version must stay compatible with the new schema.

When should you use a Version URL instead of a Preview? Use a Version URL to inspect one exact uploaded artifact before deploying it, knowing it uses production resources. Use a Preview for an isolated branch environment.

Previews have hard edges

Previews cannot consume Queues, do not run Cron Triggers, and cannot bind to another Worker's matching Preview through a service binding. D1 isolation needs a separate database per branch; sharing one staging database is a common source of drift. Preview base secrets are copied at creation, not continuously synchronized.

The tooling moves quickly. The Vitest package was renamed in 2026, Version URLs were previously called preview URLs, and Previews require a recent Wrangler. Verify current commands and limits before copying any of this into a pipeline.

Verification and versions. Documentation was checked on 2026-11-05 against the pages listed below. Previews require Wrangler 4.135.0 or later. The Vitest integration is @cloudflare/vitest-plugin and requires Vitest 4.1 or later. Gradual deployments require Wrangler 3.40.0 or later, with older versions needing the --x-versions flag. Rollbacks cover the 100 most recently published versions. No command in this article was executed, and no pricing, latency, or error-rate measurement is claimed.

Authoritative references. Workers testing: https://developers.cloudflare.com/workers/testing/ · Vitest integration: https://developers.cloudflare.com/workers/testing/vitest-integration/ · Write your first test: https://developers.cloudflare.com/workers/testing/vitest-integration/write-your-first-test/ · Previews: https://developers.cloudflare.com/workers/previews/ · Preview configuration: https://developers.cloudflare.com/workers/previews/configuration/ · Preview resources and isolation: https://developers.cloudflare.com/workers/previews/resources/ · Versions and deployments: https://developers.cloudflare.com/workers/versions-and-deployments/ · Gradual deployments: https://developers.cloudflare.com/workers/versions-and-deployments/gradual-deployments/ · Rollbacks: https://developers.cloudflare.com/workers/versions-and-deployments/rollbacks/ · Version overrides: https://developers.cloudflare.com/workers/versions-and-deployments/version-overrides/ · Wrangler environments: https://developers.cloudflare.com/workers/wrangler/environments/ · Wrangler Workers commands: https://developers.cloudflare.com/workers/wrangler/commands/workers/ · CI/CD: https://developers.cloudflare.com/workers/ci-cd/ · Observability: https://developers.cloudflare.com/workers/observability/

Next in the Series

In Coordinate State With Durable Objects, we'll explore Model object identity, transactions, and realtime sessions.