Programmatic configuration (2)·续1

<code>defineConfig<T extends ConfigInput<CloudflareConfig>>(config: T): T;</code>

Defines the default export of <code>cloudflare.config.ts</code>. Pass a configuration object, a promise that resolves to one, or a function that receives the config context (<code>isPreview</code> and <code>mode</code>) and returns either.

<details>

<summary>Options (4)</summary>

<dl>

<dt><code>accountId?: string</code></dt> <dd>This is the ID of the account associated with your zone. It can also be specified through the <code>CLOUDFLARE_ACCOUNT_ID</code> environment variable.</dd>

<dt><code>complianceRegion?: "public" | "fedramp-high"</code></dt> <dd>The compliance boundary in which commands should operate. When omitted, this can be supplied through <code>CLOUDFLARE_COMPLIANCE_REGION</code>.</dd>

<dt><code>worker?: ConfigInput<WorkerConfig></code></dt> <dd>The Worker defined by this configuration.</dd>

<dt><code>containers?: ConfigInput<ContainerConfig>[]</code></dt> <dd>Container applications defined by this configuration.</dd></dl></details>

</details>

<details>

<summary>worker: { (worker reference)</summary>

<code>worker</code>Optional<a href="#config-bindings-cloudflareconfig-worker">Link to worker</a>

<code>worker?: ConfigInput<WorkerConfig></code>

The Worker defined by this configuration.

</details>

<details>

<summary>name: "example-worker", (name reference)</summary>

<code>name</code>Required<a href="#config-bindings-workerconfig-name">Link to name</a>

<code>name: string</code>

The name of your Worker.

</details>

<details>

<summary>entrypoint, (entrypoint reference)</summary>

<code>entrypoint</code>Optional<a href="#config-bindings-workerconfig-entrypoint">Link to entrypoint</a>

<code>entrypoint?: string | WorkerModule</code>

The entrypoint module that will be executed. May be either a path string (e.g. <code>"./src/index.ts"</code>) or a module namespace imported with the <code>cf-worker</code> import attribute.

</details>

<details>

<summary>compatibilityDate: "<COMPATIBILITY_DATE>", (compatibilityDate reference)</summary>

<code>compatibilityDate</code>Required<a href="#config-bindings-workerconfig-compatibilitydate">Link to compatibilityDate</a>

<code>compatibilityDate: string</code>

A date in the form yyyy-mm-dd, which will be used to determine which version of the Workers runtime is used. More details at <a href="https://developers.cloudflare.com/workers/configuration/compatibility-dates">https://developers.cloudflare.com/workers/configuration/compatibility-dates</a>

</details>

<details>

<summary>env: { (env reference)</summary>

<code>env</code>Optional<a href="#config-bindings-workerconfig-env">Link to env</a>

<code>env?: Record<string, Binding | false | null | undefined></code>

Bindings exposed on the Worker's <code>env</code> object. Construct entries with <code>bindings.kv(...)</code>, <code>bindings.r2(...)</code>, etc. Entries set to <code>false</code>, <code>null</code>, or <code>undefined</code> are omitted, which allows bindings to be included conditionally.

</details>

<details>

<summary>API_ORIGIN: bindings.text("https://api.example.com"), (text reference)</summary>

<code>text</code>Builder<a href="#config-bindings-bindings-text-default">Link to text</a>

<code>text<T$1 extends string>(value: T$1): TextBinding<T$1>;</code>

Inline string value made available to the Worker on <code>env</code> under the binding name. For reference, see <a href="https://developers.cloudflare.com/workers/wrangler/configuration/#environment-variables">https://developers.cloudflare.com/workers/wrangler/configuration/#environment-variables</a>

</details>

<details>

<summary>FEATURES: bindings.json({ search: true }), (json reference)</summary>

<code>json</code>Builder<a href="#config-bindings-bindings-json-default">Link to json</a>

<code>json<T$1 extends Json>(value: T$1): JsonBinding<T$1>;</code>

Inline JSON value made available to the Worker on <code>env</code> under the binding name.

</details>

<details>

<summary>DATABASE: bindings.d1({ name: "application-db" }), (d1, name reference)</summary>

<code>d1</code>Builder<a href="#config-bindings-bindings-d1-default">Link to d1</a>

<code>d1(options?: D1BindingOptions): D1Binding;</code>

Binding to a D1 database. For reference, see <a href="https://developers.cloudflare.com/workers/wrangler/configuration/#d1-databases">https://developers.cloudflare.com/workers/wrangler/configuration/#d1-databases</a>

<details>

<summary>Options (3)</summary>

<dl>

<dt><code>id?: string</code></dt> <dd>The UUID of this D1 database (not required).</dd>

<dt><code>name?: string</code></dt> <dd>The name of this D1 database.</dd>

<dt><code>dev?: BindingDevOptions</code></dt> <dd>Options that only apply during local development.</dd></dl></details>

<code>name</code>Optional<a href="#config-bindings-bindings-d1-default">Link to name</a>

<code>name?: string</code>

The name of this D1 database.

</details>

<details>

<summary>JOBS: bindings.queue<Job>({ name: "application-jobs" }), (queue, name reference)</summary>

<code>queue</code>Builder<a href="#config-bindings-bindings-queue-default">Link to queue</a>

<code>queue<TBody = unknown>(options?: QueueBindingOptions): TypedQueueBinding<TBody>;</code>

Producer binding to a Cloudflare Queue. For reference, see <a href="https://developers.cloudflare.com/workers/wrangler/configuration/#queues">https://developers.cloudflare.com/workers/wrangler/configuration/#queues</a>

<details>

<summary>Options (3)</summary>

<dl>

<dt><code>name?: string</code></dt> <dd>The name of this Queue.</dd>

<dt><code>deliveryDelay?: number</code></dt> <dd>The number of seconds to wait before delivering a message.</dd>

<dt><code>dev?: BindingDevOptions</code></dt> <dd>Options that only apply during local development.</dd></dl></details>

<code>name</code>Optional<a href="#config-bindings-bindings-queue-default">Link to name</a>

<code>name?: string</code>

The name of this Queue.

</details>

<details>

<summary>API_KEY: bindings.secret(), (secret reference)</summary>

<code>secret</code>Builder<a href="#config-bindings-bindings-secret-default">Link to secret</a>

<code>secret(): SecretBinding;</code>

Declares a secret that is required by your Worker, exposed on <code>env</code> under the binding name. When defined, this binding: - Replaces .dev.vars/.env/process.env inference for type generation - Enables local dev validation with warnings for missing secrets For reference, see <a href="https://developers.cloudflare.com/workers/wrangler/configuration/#secrets-configuration-property">https://developers.cloudflare.com/workers/wrangler/configuration/#secrets-configuration-property</a>

</details>

},

},

});

The generated Env type contains these runtime types:

Binding Inferred runtime type
API_ORIGIN "https://api.example.com"
FEATURES { search: true }
DATABASE D1Database
JOBS Queue<Job>
API_KEY string

Your Worker receives the inferred type through env:

src/index.jsjs

export default {
    async fetch(_request, env) {
        await env.JOBS.send({
            id: "example-job",
            operation: "index",
        });

const result = await env.DATABASE.prepare("SELECT 1").first();
        return Response.json({
            origin: env.API_ORIGIN,
            search: env.FEATURES.search,
            result,
        });
    },
};

src/index.tsts

export default {
    async fetch(_request, env) {
        await env.JOBS.send({
            id: "example-job",
            operation: "index",
        });

const result = await env.DATABASE.prepare("SELECT 1").first();
        return Response.json({
            origin: env.API_ORIGIN,
            search: env.FEATURES.search,
            result,
        });
    },
} satisfies ExportedHandler<Env>;

The Cloudflare Vite plugin writes .cloudflare/types/index.d.ts during development and builds. Outside the Vite workflow, cf workers types writes the same file.

TypeScript wildcard patterns skip dot-prefixed directories, so include the generated directory explicitly. The .ts extensions in the examples on this page also need allowImportingTsExtensions:

tsconfig.jsonjson

{
    "compilerOptions": {
        "allowImportingTsExtensions": true,
        "noEmit": true
    },
    "include": ["src", "cloudflare.config.ts", ".cloudflare/types"]
}

The builder API includes these methods:

Area Builder methods
Inline values text, json, secret
Storage and data d1, kv, r2, hyperdrive, analyticsEngineDataset, artifacts, pipeline
AI and media ai, aiSearch, aiSearchNamespace, agentMemory, browser, images, media, stream, vectorize
Messaging queue, sendEmail
Worker composition assets, dispatchNamespace, durableObject, worker, workerLoader, workflow
Network and security mtlsCertificate, rateLimit, secretsStoreSecret, vpcNetwork, vpcService
Platform metadata flagship, logfwdr, versionMetadata

Required options differ by binding. TypeScript completion shows the options for each builder.

Type cross-Worker bindings

bindings.worker(), bindings.durableObject(), and bindings.workflow() accept a Worker name or a Worker definition. Import a Worker definition to validate its export names at compile time.

For example, an API Worker can export its definition:

Select a highlighted line to show its type and description below it.

api/cloudflare.config.ts

Expand allCopy

import { defineConfig, defineWorker, exports } from "cf/config";

import * as entrypoint from "./src/index.ts" with { type: "cf-worker" };

<details>

<summary>export const apiWorker = defineWorker({ (defineWorker reference)</summary>

<code>defineWorker</code>Function<a href="#config-cross-worker-api-defineworker">Link to defineWorker</a>

<code>defineWorker<T extends ConfigInput<WorkerConfig>>(config: T): T;</code>

Defines a Worker configuration that you can pass to <code>worker</code> in <code>defineConfig()</code>. Pass a Worker configuration object, a promise that resolves to one, or a function that receives the config context (<code>isPreview</code> and <code>mode</code>) and returns either.

<details>

<summary>Options (19)</summary>

<dl>

<dt><code>name: string</code></dt> <dd>The name of your Worker.</dd>

<dt><code>compatibilityDate: string</code></dt> <dd>A date in the form yyyy-mm-dd, which will be used to determine which version of the Workers runtime is used. More details at <a href="https://developers.cloudflare.com/workers/configuration/compatibility-dates">https://developers.cloudflare.com/workers/configuration/compatibility-dates</a></dd>

<dt><code>compatibilityFlags?: string[]</code></dt> <dd>A list of flags that enable features from upcoming features of the Workers runtime, usually used together with <code>compatibilityDate</code>. More details at <a href="https://developers.cloudflare.com/workers/configuration/compatibility-flags/">https://developers.cloudflare.com/workers/configuration/compatibility-flags/</a></dd>

<dt><code>entrypoint?: string | WorkerModule</code></dt> <dd>The entrypoint module that will be executed. May be either a path string (e.g. <code>"./src/index.ts"</code>) or a module namespace imported with the <code>cf-worker</code> import attribute.</dd>

<dt><code>assets?: { / How to handle HTML requests. */ htmlHandling?: "auto-trailing-slash" | "drop-trailing-slash" | "force-trailing-slash" | "none"; / How to handle requests that do not match an asset. / notFoundHandling?: "single-page-application" | "404-page" | "none"; / * The public URL prefix under which the application is served. / basePath?: string; /* * Matches will be routed to the User Worker, and matches to negative rules will go to the Asset Worker. * * Can also be true, indicating that every request should be routed to the User Worker. / runWorkerFirst?: string[] | boolean; }</code></dt> <dd>Specify the directory of static assets to deploy/serve. More details at <a href="https://developers.cloudflare.com/workers/frameworks/">https://developers.cloudflare.com/workers/frameworks/</a> For reference, see <a href="https://developers.cloudflare.com/workers/wrangler/configuration/#assets">https://developers.cloudflare.com/workers/wrangler/configuration/#assets</a></dd>

<dt><code>domains?: Array<string | CustomDomain></code></dt> <dd>Custom domains that your Worker should be published to. Strings serve production traffic only. Objects select production, Preview traffic, or both; at least one must be enabled. Domain settings are applied when deploying the parent Worker. Preview uploads use the parent's existing hosting without applying domains. For reference, see <a href="https://developers.cloudflare.com/workers/wrangler/configuration/#types-of-routes">https://developers.cloudflare.com/workers/wrangler/configuration/#types-of-routes</a></dd>

<dt><code>triggers?: Trigger[]</code></dt> <dd>Event triggers — fetch routes, queue consumers, cron schedules, Email Routing addresses, and raw sockets — that invoke this Worker. Construct entries with <code>triggers.fetch(...)</code>, <code>triggers.queue(...)</code>, <code>triggers.scheduled(...)</code>, <code>triggers.email(...)</code>, or <code>triggers.connect(...)</code>. For reference, see <a href="https://developers.cloudflare.com/workers/wrangler/configuration/#triggers">https://developers.cloudflare.com/workers/wrangler/configuration/#triggers</a></dd>

<dt><code>tailConsumers?: Array<{ / The name of the service tail events will be forwarded to. */ worker: string; / Whether to stream tail events in real time. */ streaming?: boolean; }></code></dt> <dd>A list of Tail Workers that are bound to this Worker. <code>@cloudflare/config</code> unifies regular and streaming tail consumers under a single field; pass <code>streaming: true</code> to forward streaming tail events.</dd>

<dt><code>cache?: { / If cache is enabled for this Worker. */ enabled: boolean; / Whether cached assets may be reused across Worker versions. */ crossVersionCache?: boolean; }</code></dt> <dd>Specify the cache behavior of the Worker.</dd>

<dt><code>placement?: { mode: "off" | "smart"; hint?: string; } | { mode?: "targeted"; region: string; } | { mode?: "targeted"; host: string; } | { mode?: "targeted"; hostname: string; }</code></dt> <dd>Specify how the Worker should be located to minimize round-trip time. More details: <a href="https://developers.cloudflare.com/workers/platform/smart-placement/">https://developers.cloudflare.com/workers/platform/smart-placement/</a></dd>

<dt><code>limits?: { / Maximum allowed CPU time for a Worker's invocation in milliseconds. */ cpuMs?: number; / Maximum allowed number of fetch requests that a Worker's invocation can execute. */ subrequests?: number; }</code></dt> <dd>Specify limits for runtime behavior. Only supported for the "standard" Usage Model. For reference, see <a href="https://developers.cloudflare.com/workers/wrangler/configuration/#limits">https://developers.cloudflare.com/workers/wrangler/configuration/#limits</a></dd>

<dt><code>logpush?: boolean</code></dt> <dd>Send Trace Events from this Worker to Workers Logpush. This will not configure a corresponding Logpush job automatically. For more information about Workers Logpush, see: <a href="https://blog.cloudflare.com/logpush-for-workers/">https://blog.cloudflare.com/logpush-for-workers/</a></dd>

<dt><code>observability?: { / If observability is enabled for this Worker. */ enabled?: boolean; / The sampling rate. / headSamplingRate?: number; / * Whether query strings are removed from request URLs in logs and traces. * * @default false / redactQueryString?: boolean; / Real-time Issues settings for this Worker. */ issues?: { / Whether real-time Issues are enabled. / enabled?: boolean; }; logs?: { enabled?: boolean; / The sampling rate. / headSamplingRate?: number; / Set to false to disable invocation logs. */ invocationLogs?: boolean; / * If logs should be persisted to the Cloudflare observability platform where they can be queried in the dashboard. * * @default true / persist?: boolean; / * What destinations logs emitted from the Worker should be sent to. * * @default [] / destinations?: string[]; }; traces?: { enabled?: boolean; / The sampling rate. */ headSamplingRate?: number; / * If traces should be persisted to the Cloudflare observability platform where they can be queried in the dashboard. * * @default true / persist?: boolean; / * What destinations traces emitted from the Worker should be sent to. * * @default [] / destinations?: string[]; }; }</code></dt> <dd>Specify the observability behavior of the Worker. For reference, see <a href="https://developers.cloudflare.com/workers/wrangler/configuration/#observability">https://developers.cloudflare.com/workers/wrangler/configuration/#observability</a></dd>

<dt><code>access?: { / Local development simulation of Cloudflare Access authentication. */ dev?: { / The Access application audience tag (aud). / aud: string; / Mock identity returned by ctx.access.getIdentity(). / identity?: Record<string, unknown>; }; }</code></dt> <dd>Cloudflare Access configuration for this Worker.</dd>

<dt><code>workersDev?: boolean</code></dt> <dd>Whether we use <code><name>.<subdomain>.workers.dev</code> to test and deploy your Worker. For reference, see <a href="https://developers.cloudflare.com/workers/wrangler/configuration/#workersdev">https://developers.cloudflare.com/workers/wrangler/configuration/#workersdev</a></dd>