Configuration is code: a tour of cloudflare.config.ts
A tested tour of the typed cloudflare.config.ts file used by the cf CLI: bindings, inferred types, modes, assets, dry runs, and what it costs.
- topic
- cloudflare workers
- date
- read
- 20 min
The Cloudflare CLI (cf) configures a Workers project with a TypeScript module, cloudflare.config.ts, where Wrangler reads wrangler.jsonc or wrangler.toml. The change goes further than syntax. The Env type is inferred from the file, and environments turn into ordinary control flow. In exchange, every command run inside the project executes code you wrote. This tour builds one configuration from the minimum upward, with the output of each step, and ends with the costs.
Everything was run with cf 1.0.0-rc.6, @cloudflare/vite-plugin 2.0.0-rc.6, TypeScript 7.0.2 and Node 24.22.2. Nothing was deployed: every deploy shown is cf deploy --dry-run.
pnpm dlx cf@1.0.0-rc.6 init config-tour --package-manager pnpm
cd config-tourThe minimum
A Worker needs a name and a compatibility date. One that runs code also needs an entrypoint.
import { defineConfig } from "cf/config";
import * as entrypoint from "./src/index.ts" with { type: "cf-worker" };
export default defineConfig({
worker: {
name: "config-tour",
compatibilityDate: "2026-11-23",
entrypoint,
},
});export default {
fetch() {
return new Response("ok\n");
},
} satisfies ExportedHandler<Env>;pnpm exec cf deploy --dry-run...
◆ Build complete
│
├ Deploy
│ Total Upload: 0.18 KiB / gzip: 0.16 KiB
│ No bindings found.
│ --dry-run: exiting now.defineConfig returns its argument unchanged and exists for the type checker. The file is checked a second time when it is loaded, and the two checks do not report equally well. With compatibilityDate removed, tsc prints a four-line TS2322 that spells out the whole expected ConfigInput<WorkerConfig> type and never says which field is missing. The loader does. cf build stops with an error that gives the reason, Invalid input: expected string, received undefined, and the path, at worker.compatibilityDate.
The entrypoint is an import
The second line of the file is the unusual one. with { type: "cf-worker" } is an import attribute, and the import means something different to each of its two readers. Adding console.error("entrypoint is", entrypoint) to the config shows what the loader gets:
entrypoint is [Module: null prototype] {
default: '<PROJECT>/src/index.ts'
}At load time the import resolves to the file’s path, and the Worker module is not executed. The type checker ignores the attribute and sees the real module with all of its exports. That is what makes features that refer to your own classes type-safe. Take a Worker that calls a named entrypoint class through ctx.exports, with a deliberate mistake in the call:
import { WorkerEntrypoint } from "cloudflare:workers";
export class Greeter extends WorkerEntrypoint {
greet(name: string): string {
return `Hello, ${name}`;
}
}
export default {
async fetch(request, env, ctx) {
const greeting = await ctx.exports.Greeter.greet(42);
return new Response(`${greeting}\n`);
},
} satisfies ExportedHandler<Env>;pnpm exec vp check --no-fmt --no-lint...
x typescript(TS2345): Argument of type 'number' is not assignable to parameter of type 'string'.
,-[src/index.ts:11:52]
10 | async fetch(request, env, ctx) {
11 | const greeting = await ctx.exports.Greeter.greet(42);
: ^^
12 | return new Response(`${greeting}\n`);
`----
...The checker knows Greeter and the signature of greet. The configuration also accepts a plain string, entrypoint: "./src/index.ts". With that form the same check loses the class:
...
x typescript(TS2339): Property 'greet' does not exist on type '(LoopbackDurableObjectClass<DurableObjectBranded> | LoopbackServiceStub<...> | LoopbackServiceStub<...> | undefined) & {}'.
...Binding types are inferred with either form. The import is what carries the shape of your module into ctx.exports and into bindings that point at your own Durable Objects or entrypoint classes.
Bindings and the Env type
Bindings go under worker.env, one builder call per name:
env: {
API_ORIGIN: bindings.text("https://api.example.com"),
FEATURES: bindings.json({ signup: false, maxUploadMb: 10 }),
ADMIN_TOKEN: bindings.secret(),
CACHE: bindings.kv(),
DB: bindings.d1({ name: "config-tour" }),
ASSETS: bindings.assets(),
},bindings is imported from cf/config next to defineConfig, and the configuration reference lists the other builders, from R2 buckets to Queues. The Worker uses each binding once:
export default {
async fetch(request, env) {
const url = new URL(request.url);
if (url.pathname === "/api/status") {
const hits = Number((await env.CACHE.get("hits")) ?? "0") + 1;
await env.CACHE.put("hits", String(hits));
const row = await env.DB.prepare("SELECT 1 + 1 AS two").first<{ two: number }>();
return Response.json({
origin: env.API_ORIGIN,
signup: env.FEATURES.signup,
maxUploadMb: env.FEATURES.maxUploadMb,
hasAdminToken: env.ADMIN_TOKEN !== undefined,
hits,
two: row?.two,
});
}
return env.ASSETS.fetch(request);
},
} satisfies ExportedHandler<Env>;With an index.html and a 404.html in public/, start the dev server and call the API route from a second terminal:
pnpm exec cf dev --port 8797 --host 127.0.0.1
curl -s http://127.0.0.1:8797/api/status{"origin":"https://api.example.com","signup":false,"maxUploadMb":10,"hasAdminToken":false,"hits":1,"two":2}KV and D1 work with no IDs and no setup because the dev server simulates both. The secret has no value, and the dev server says so when it starts:
Missing required secrets for Worker "config-tour": ADMIN_TOKEN. Add them to one of `.dev.vars.development`, `.dev.vars`, `.env.development.local`, `.env.development`, `.env.local`, or `.env`. Alternatively, set them as environment variables.Started with ADMIN_TOKEN set in the shell, the warning goes away and hasAdminToken becomes true.
No interface for env was written by hand, yet the checker knows it precisely. Two wrong lines demonstrate:
export default {
async fetch(request, env) {
const origin: "https://staging-api.example.com" = env.API_ORIGIN;
await env.CACH.get("hits");
return new Response(origin);
},
} satisfies ExportedHandler<Env>;...
x typescript(TS2322): Type '"https://api.example.com"' is not assignable to type '"https://staging-api.example.com"'.
...
x typescript(TS2551): Property 'CACH' does not exist on type 'Env'. Did you mean 'CACHE'?
...The generated types file shows where this comes from:
// Generated by @cloudflare/config
type __Config = import("cf/config").UnwrapConfig<typeof import("../../cloudflare.config").default>;
type __WorkerConfig = import("cf/config").UnwrapConfig<__Config["worker"]>;
type __Env = import("cf/config").InferEnv<__WorkerConfig>;
declare namespace Cloudflare {
interface GlobalProps {
mainModule: import("cf/config").InferMainModule<__WorkerConfig>;
durableNamespaces: import("cf/config").InferDurableNamespaces<__WorkerConfig>;
}
interface Env extends __Env {}
}
interface Env extends Cloudflare.Env {}Env is computed from the type of the configuration’s default export. Nothing is copied out of the config, so a new binding is visible to the checker as soon as the config is saved: in a test, an added REGION: bindings.text("eu") was checked as the literal "eu" while the generated file’s checksum stayed the same. The rest of that file (more than 16,000 lines here) holds the runtime API types for the configured compatibility date. That part did change when the date changed. cf workers types rewrites the file, and so do cf dev and cf build.
Assets and custom domains
The settings for static assets are split across two files. Which directory is uploaded is a build setting. In this Vite project it is public/, and the build copies it to .cloudflare/output/v1/workers/default/assets/. How requests are matched against those files is runtime behavior, and that part sits in the config next to the hostnames:
assets: {
htmlHandling: "drop-trailing-slash",
notFoundHandling: "404-page",
runWorkerFirst: ["/api/*"],
},
domains: ["tour.example.com"],
workersDev: false,
previewUrls: false,
observability: { enabled: true },With notFoundHandling: "404-page", a request for /nope returned status 404 with the body of public/404.html. runWorkerFirst lists the paths that go to the Worker before any asset lookup. htmlHandling is where the dev server and the build output disagreed: under cf dev, /index.html returned 200, while the built Worker (run with pnpm exec vp preview) answered 307 with a redirect to /. When URL shape matters, test against the preview.
A string in domains attaches a custom domain for production traffic. The object form, { hostname, production, previews }, can also serve Preview deployments on subdomains of that hostname. workersDev: false and previewUrls: false turn off the workers.dev hostname and the per-version preview URLs. Route patterns are declared separately, with triggers.fetch().
Modes replace environments
A Wrangler environment is a named block inside the config file. Deploying with --env staging creates a Worker named <name>-staging. The block inherits some top-level keys, while bindings and variables have to be repeated in every environment, and knowing which keys inherit is part of the job.
cloudflare.config.ts has no environments and no inheritance. The default export may be a function of { mode, isPreview } that returns one complete configuration, and --mode supplies the argument. Staging differs from production by whatever your code makes different:
import { bindings, defineConfig } from "cf/config";
import * as entrypoint from "./src/index.ts" with { type: "cf-worker" };
const targets = {
production: {
name: "config-tour",
hostname: "tour.example.com",
apiOrigin: "https://api.example.com",
},
staging: {
name: "config-tour-staging",
hostname: "staging.tour.example.com",
apiOrigin: "https://staging-api.example.com",
},
} as const;
function targetFor(mode: string | undefined) {
switch (mode) {
case "staging":
return targets.staging;
case "production":
case "development":
case "test":
case undefined:
return targets.production;
default:
throw new Error(`Unknown mode "${mode}". Use "staging" or "production".`);
}
}
export default defineConfig(({ mode }) => {
const target = targetFor(mode);
return {
worker: {
name: target.name,
compatibilityDate: "2026-11-23",
entrypoint,
assets: {
htmlHandling: "drop-trailing-slash",
notFoundHandling: "404-page",
runWorkerFirst: ["/api/*"],
},
domains: [target.hostname],
workersDev: false,
previewUrls: false,
observability: { enabled: true },
env: {
API_ORIGIN: bindings.text(target.apiOrigin),
FEATURES: bindings.json({ signup: false, maxUploadMb: 10 }),
ADMIN_TOKEN: bindings.secret(),
CACHE: bindings.kv(),
DB: bindings.d1({ name: target.name }),
ASSETS: bindings.assets(),
},
},
};
});pnpm exec cf deploy --dry-run --mode staging...
│ Your Worker has access to the following bindings:
│ Binding Resource
│ env.CACHE KV Namespace
│ env.DB (config-tour-staging) D1 Database
│ env.ASSETS Assets
│ env.API_ORIGIN ("https://staging-api.example.com") Environment Variable
│ env.FEATURES ({"signup":false,"maxUploadMb":10}) Environment Variable
│
│ --dry-run: exiting now.Staging is a separate Worker only because the function returns a different name for it.
The switch is longer than a ternary on purpose. Without --mode, the value depends on the command. Logged from inside the function, it was:
| Command | mode |
|---|---|
cf dev |
"development" |
cf build, cf deploy --dry-run |
"production" |
vp test run |
"test" |
cf kv namespaces list --local |
undefined |
The last row matters: API commands load the nearest config to read account settings, so the function has to accept undefined. It should also reject names it does not know. An earlier version of this file used mode === "staging" ? ... : ..., and cf deploy --dry-run --mode stagin built the production Worker without complaint. With the switch, the same typo stops the build:
...
error during build:
Error: Unknown mode "stagin". Use "staging" or "production".
...The types follow the code here too. The checker cannot know the mode, so env.API_ORIGIN is typed as the union "https://api.example.com" | "https://staging-api.example.com".
Build settings live with the bundler
Nothing about bundling goes in cloudflare.config.ts. cf hands the build to the project’s own tool, and define, aliases, minification and the assets directory are that tool’s settings. In a cf init project the tool is Vite:
import { cloudflare } from "@cloudflare/vite-plugin";
import { defineConfig } from "vite-plus";
export default defineConfig({
plugins: [cloudflare()],
define: {
__RELEASE__: JSON.stringify("2026.11.28"),
},
build: {
minify: true,
},
fmt: { useTabs: true },
lint: {
options: { typeAware: true, typeCheck: true },
},
});The Worker picks the constant up with two lines:
@@ -1,2 +1,4 @@
+declare const __RELEASE__: string;
+
export default {
async fetch(request, env) {
@@ -9,4 +11,5 @@
return Response.json({
+ release: __RELEASE__,
origin: env.API_ORIGIN,
signup: env.FEATURES.signup,/api/status now includes "release":"2026.11.28", and the build reported the bundle going from 0.67 kB to 0.46 kB once minify was on.
The split has a cost of its own. The test runner reads vitest.config.ts, a separate file, so the test run failed with ReferenceError: __RELEASE__ is not defined until a define for the constant was added there as well. Projects converted from Wrangler without Vite keep Wrangler’s bundler, and their build settings move to a generated wrangler.config.ts that the reference calls experimental.
What a dry run shows
cf deploy --dry-run runs the build and validates its output, then stops before any upload. According to the project documentation, it sends no API requests and needs no credentials.
pnpm exec cf deploy --dry-run...
│ Total Upload: 0.46 KiB / gzip: 0.35 KiB
│ Your Worker has access to the following bindings:
│ Binding Resource
│ env.CACHE KV Namespace
│ env.DB (config-tour) D1 Database
│ env.ASSETS Assets
│ env.API_ORIGIN ("https://api.example.com") Environment Variable
│ env.FEATURES ({"signup":false,"maxUploadMb":10}) Environment Variable
│
│ --dry-run: exiting now.The table is the place to catch a wrong value before it ships. It is also incomplete: the Worker name and the domains are absent, and so is the declared secret. The full resolved configuration is in the build output. Pretty-printed, it begins:
{
"name": "config-tour",
"compatibilityDate": "2026-11-23",
"assets": {
"htmlHandling": "drop-trailing-slash",
"notFoundHandling": "404-page",
"runWorkerFirst": [
"/api/*"
]
},
"domains": [
"tour.example.com"
],
...A real cf deploy does one thing the dry run cannot show. The same documentation says that bindings declared without a resource identifier, such as bindings.kv() above, can be provisioned during the deploy, and that the new IDs are not written back to the file. --no-provision makes those bindings fail instead.
The costs
The tool is a release candidate. The overview calls the configuration format, the build output and the project commands stable, and says some API commands can still change. A fresh project shows the seams: cf 1.0.0-rc.6 and the Vite plugin 2.0.0-rc.6 each install their own copy of the config loader, @cloudflare/config, at different versions (rc.4 and rc.5).
Wrangler does not disappear. The reference page currently gives cf equivalents for most Wrangler commands under new names: wrangler secret put becomes cf workers secrets update, and wrangler tail becomes cf observability tail --worker <name>, which needs Workers Logs turned on. Both exist in rc.6. Wrangler itself is still required in two cases. A project with a Wrangler file and no cloudflare.config.ts keeps wrangler dev and wrangler deploy until cf migrate converts it, because the cf project commands ignore Wrangler files. A migrated project that does not use Vite still builds through Wrangler. Workers Sites has no equivalent, and Durable Object migrations are not converted automatically.
The larger cost is in the title. The module runs more often than expected: a log line at the top of the file printed three times during one cf deploy --dry-run, and once for an unrelated local command. An exception in the config therefore breaks commands that have nothing to do with the Worker:
pnpm exec cf kv namespaces list --local --mode stagin┌ Error
│ Unknown mode "stagin". Use "staging" or "production".
└Inputs are the other hazard. bindings.text(process.env.API_ORIGIN ?? "http://localhost:9000") produced a production build pointing at localhost when the variable was unset, and bindings.text(new Date().toISOString()) produced a different Worker on every build. Neither is an error, and a JSON file could express neither.
The discipline that keeps this manageable is to write the file as a pure function from mode to configuration: no clock or network access, and environment reads that throw when a variable is missing. What the function returned is always on disk after a build, so reading worker.config.json before a deploy does the job that reading wrangler.jsonc used to do.