Testing and shipping
Write tests that run inside the Workers runtime, inspect the build, then deploy with real resources, secrets, a domain and logs.
- lesson
- 08 of 08
- read
- 13 min
The project works on your machine and has one test. This lesson gives it a test suite, looks at what cf build produces, and walks through deployment: resources, the secret, a domain, versions and logs. Everything up to and including the build section runs locally. From “Create the resources” onward the commands change a Cloudflare account. They were not executed for this course, and any output shown for them comes from --dry-run, which prints the request without sending it.
Tests that run in the runtime
The generated vitest.config.ts already loads the Worker’s configuration. Extend it with two test-only bindings and a setup file:
import { cloudflareTest, readD1Migrations } from "@cloudflare/vitest-plugin";
import { defineConfig } from "vite-plus";
export default defineConfig({
plugins: [
cloudflareTest(async () => ({
config: true,
miniflare: {
bindings: {
ADMIN_TOKEN: "test-token",
TEST_MIGRATIONS: await readD1Migrations("./migrations"),
},
},
})),
],
test: {
setupFiles: ["./test/apply-migrations.ts"],
},
});cloudflareTest({ config: true }) evaluates cloudflare.config.ts in test mode and runs each test file inside workerd with the Worker’s bindings. Storage is isolated per test file, so tests never see your development data and start from an empty KV namespace and an empty database.
The miniflare.bindings object adds values that exist only in tests. ADMIN_TOKEN gets a fixed value so that the tests do not depend on what is in your .dev.vars. TEST_MIGRATIONS carries the migration files, read from disk by readD1Migrations() while the configuration is evaluated in Node.js, into the runtime, where a setup file applies them:
import { applyD1Migrations } from "cloudflare:test";
import { env } from "cloudflare:workers";
await applyD1Migrations(env.DB, env.TEST_MIGRATIONS);declare namespace Cloudflare {
interface Env {
TEST_MIGRATIONS: import("cloudflare:test").D1Migration[];
}
}Now replace the single test with a suite:
import { createExecutionContext, waitOnExecutionContext } from "cloudflare:test";
import { env, exports } from "cloudflare:workers";
import { describe, expect, it } from "vite-plus/test";
import worker from "../src/index.ts";
const BASE = "https://shortlinks.test";
function post(body: unknown, token = "test-token"): Promise<Response> {
return exports.default.fetch(`${BASE}/api/links`, {
method: "POST",
headers: { Authorization: `Bearer ${token}` },
body: JSON.stringify(body),
});
}
describe("POST /api/links", () => {
it("rejects a wrong token", async () => {
const response = await post({ url: "https://example.org/" }, "wrong");
expect(response.status).toBe(401);
expect(response.headers.get("WWW-Authenticate")).toBe("Bearer");
});
it("rejects URLs that are not http or https", async () => {
const response = await post({ url: "javascript:alert(1)" });
expect(response.status).toBe(400);
expect(await response.json()).toEqual({ error: "url must use http or https" });
});
it("stores the link in KV", async () => {
const response = await post({ url: "https://example.org/docs" });
expect(response.status).toBe(201);
const body = await response.json<{ code: string; short: string }>();
expect(body.code).toMatch(/^[0-9a-hjkmnp-tv-z]{6}$/);
expect(body.short).toBe(`${env.PUBLIC_ORIGIN}/${body.code}`);
expect(await env.LINKS.get(body.code, "json")).toMatchObject({
url: "https://example.org/docs",
});
});
});
describe("GET /:code", () => {
it("redirects and records the visit after the response", async () => {
await env.LINKS.put(
"abc123",
JSON.stringify({ url: "https://example.org/", createdAt: "2026-11-28T00:00:00.000Z" }),
);
const request = new Request<unknown, IncomingRequestCfProperties>(`${BASE}/abc123`, {
headers: { Referer: "https://news.example.com/" },
});
const ctx = createExecutionContext();
const response = await worker.fetch(request, env, ctx);
expect(response.status).toBe(302);
expect(response.headers.get("Location")).toBe("https://example.org/");
await waitOnExecutionContext(ctx);
const row = await env.DB.prepare("SELECT code, referrer FROM visits").first();
expect(row).toEqual({ code: "abc123", referrer: "https://news.example.com/" });
});
it("returns JSON 404 for an unknown code", async () => {
const response = await exports.default.fetch(`${BASE}/zzzzzz`);
expect(response.status).toBe(404);
expect(await response.json()).toEqual({ error: "no such link" });
});
});Two styles are in use. exports.default.fetch() sends a request to the Worker’s default export and gives back the response, like a client would. The test from cf init used SELF from cloudflare:test for this, which the plugin’s type definitions now mark as deprecated in favor of exports.
The redirect test calls the handler directly so that it can supply its own execution context. waitOnExecutionContext(ctx) resolves once every promise passed to ctx.waitUntil() has settled, which is what allows the next line to query D1 without racing the write.
Tests can use the bindings themselves. One test seeds KV with env.LINKS.put(), and others read back from KV and D1 to check what the handler stored.
pnpm test...
Test Files 1 passed (1)
Tests 5 passed (5)
...These tests call your handler. They do not pass through the asset router, and env.ASSETS is undefined in this setup, so the HTML branch of linkNotFound is not covered (an exercise addresses that). Routing between assets and code is checked against the preview, as in lesson 7. The Vitest integration guide documents the rest of the test APIs.
Build and inspect
pnpm exec cf build
find .cloudflare/output -type f | sort...
.cloudflare/output/v1/config.json
.cloudflare/output/v1/workers/default/assets/404.html
.cloudflare/output/v1/workers/default/assets/index.html
.cloudflare/output/v1/workers/default/bundle/index.js
.cloudflare/output/v1/workers/default/bundle/index.js.map
.cloudflare/output/v1/workers/default/worker.config.jsonThis directory is what gets uploaded. bundle/index.js is the whole Worker in one file, 5.92 kB here. worker.config.json is your configuration resolved for one mode. Open it and you will find PUBLIC_ORIGIN set to https://go.example.com, because builds default to production. config.json records that mode.
cf deploy --dry-run builds and then validates what a deploy would upload. It makes no API requests and needs no sign-in:
pnpm exec cf deploy --dry-run...
│ Total Upload: 5.78 KiB / gzip: 2.31 KiB
│ Your Worker has access to the following bindings:
│ Binding Resource
│ env.LINKS KV Namespace
│ env.DB (shortlinks) D1 Database
│ env.ASSETS Assets
│ env.PUBLIC_ORIGIN ("https://go.example.com") Environment Variable
│ env.LIMITS ({"codeLength":6,"maxUrlLength":2048}) Environment Variable
│
│ --dry-run: exiting now.A dry run does not execute the Worker. The module-scope mistake from lesson 1 passes it without a word, and the preview is still the check that catches startup errors.
Create the resources
Sign in once with cf auth login, then create the namespace and the database:
pnpm exec cf kv namespaces create --title shortlinks-links
pnpm exec cf d1 create --name shortlinksWith --dry-run appended, the second command prints the request it would make:
{
"command": "cf d1 create",
"method": "POST",
"url": "https://api.cloudflare.com/client/v4/accounts/<account-id>/d1/database",
"pathParams": {},
"bodyKind": "json",
"body": {
"name": "shortlinks"
}
}The response to each command includes the new resource’s ID. Put both in the configuration:
LINKS: bindings.kv({ id: "<KV_NAMESPACE_ID>" }),
DB: bindings.d1({ name: "shortlinks", id: "<DATABASE_ID>" }),cf deploy can also create resources for bindings that have no ID. It does not write the new IDs back to your file, though, and you need the database ID for migrations anyway. With explicit IDs the configuration says exactly which resources the Worker uses.
Changing the IDs has a local side effect. Local data is stored per ID, so your development links are no longer visible and the local database is empty again. Re-apply the migration with --local and the new ID.
The remote database needs the schema before any code that queries it goes live. The same command without --local applies the migration to it:
pnpm exec cf d1 migrations apply <DATABASE_ID>Deploy
Two more settings belong in the configuration:
@@ -9,6 +9,8 @@
assets: {
runWorkerFirst: ["/api/*"],
},
+ observability: { enabled: true },
+ domains: ["go.example.com"],
env: {
PUBLIC_ORIGIN: bindings.text(
mode === "production" ? "https://go.example.com" : "http://localhost:8791",observability turns on Workers Logs. domains attaches the Worker to a custom domain. Replace go.example.com here and in PUBLIC_ORIGIN with a hostname in a zone that is active on your account. Cloudflare creates the DNS record and the certificate. The hostname must not already have a CNAME record. If you have no domain, leave domains out. The Worker is then served at shortlinks.<your-subdomain>.workers.dev, and PUBLIC_ORIGIN should say so.
The production secret travels with the first deploy. Generate a long random value, for example with openssl rand -hex 32, and put it in a dotenv file that the generated .gitignore already covers:
ADMIN_TOKEN=<LONG_RANDOM_VALUE>A dry run with the file confirms that the secret is picked up and that its value is not printed:
pnpm exec cf deploy --dry-run --secrets-file .env.deploy...
│ env.LIMITS ({"codeLength":6,"maxUrlLength":2048}) Environment Variable
│ env.ADMIN_TOKEN ("(hidden)") Environment Variable
│
│ --dry-run: exiting now.The deploy itself is the same command without --dry-run:
pnpm exec cf deploy --secrets-file .env.deploy --message "First deploy"It builds, uploads a new version of the Worker and routes all traffic to it. Delete .env.deploy afterwards, since the secret is now stored with the Worker. To rotate it later, cf workers secrets update ADMIN_TOKEN --worker shortlinks --type secret_text --text <NEW_VALUE> creates a new version with the new value.
Versions, rollbacks and previews
Every upload is a version: code, assets, bindings and settings frozen together. A deployment says which version receives traffic. cf deploy does both steps. They can be separated:
pnpm exec cf workers versions create --message "Stats page"
pnpm exec cf workers deployments create --worker shortlinks --strategy percentage --versions '[{"version_id":"<VERSION_ID>","percentage":100}]'The first command uploads without changing what visitors get. The second moves traffic. Two entries in --versions that add up to 100 split traffic between an old and a new version, and a rollback is a deployment that names the previous version at 100.
Stored data is not part of a version. Rolling back the code does not roll back a migration or the contents of KV, so a schema change has to work with both the old and the new code: add a column in one deploy and start using it in the next.
cf previews deploy builds with isPreview set to true and publishes the result under its own URL, named after the current Git branch. Because the configuration function receives isPreview, a preview can be given a different KV namespace and database, which keeps test links out of production data. Develop, build, and deploy describes the options.
Logs
With observability on, console.log and console.error output from every invocation is kept in Workers Logs, next to an entry for the invocation itself. The dashboard shows them under the Worker’s Observability tab. To follow them from a terminal:
pnpm exec cf observability tail --worker shortlinksThe command streams events as newline-delimited JSON. The two places this project logs on purpose are the ones to watch after a deploy: the error boundary’s console.error for unexpected exceptions, and recordVisit failed for visits that were not stored.
Exercises
- Add two tests for
ttl. A value of 30 should return 400 with the exact error message, and 3600 should return 201 with anexpiresAtexactly one hour aftercreatedAt.pnpm testshould report seven passed tests. - Make the HTML 404 testable. In
vitest.config.ts, add a stub underminiflare.serviceBindingsnamedASSETS: a function that returns a small HTMLResponse. Then test that an unknown code requested withAccept: text/htmlreturns 404 and the stub’s body. - Add a
verifyscript topackage.jsonthat runspnpm check,pnpm testandcf deploy --dry-runin sequence, stopping at the first failure.pnpm verifyshould exit with status 0 and end with the dry run’s table of bindings. Break a test on purpose and confirm that the dry run no longer runs.