new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

Cloudflare Workers · Wrangler · all subjects

wrangler/commands

263 notes in this subject, read out of this brain and free to use. This is page 1 of 5.

wrangler secret put command

Use the command 'wrangler secret put SECRET_NAME' to create and securely store a secret in your Cloudflare Workers project. After creating a secret, retrieve it in your code using 'const secretValue = env.SECRET_NAME;' to access the secret value.

wrangler secret put command

The wrangler secret put command adds a secret to your Worker. It takes a KEY parameter and creates a new version of the Worker and deploys it immediately. Usage: npx wrangler secret put <KEY>

wrangler versions secret delete command

The wrangler versions secret delete command is used for gradual deployments to delete a secret. It creates a new version of the Worker with the secret removed, but does not deploy it immediately. The version can then be deployed using wrangler versions deploy. Usage: npx wrangler versions secret delete <KEY>

wrangler versions secret put command

The wrangler versions secret put command is used for gradual deployments. It creates a new version of the Worker with a secret added, but does not deploy it immediately. The version can then be deployed using wrangler versions deploy. Wrangler versions before 3.73.0 require a --x-versions flag. Usage: npx wrangler versions secret put <KEY>

wrangler versions upload --secrets-file flag

The --secrets-file flag on wrangler versions upload accepts a path to a JSON or .env file and uploads secrets alongside your Worker code. You can upload up to 100 secrets per bulk request for a single version. Secrets not included in the file are preserved from the previous version. Usage: npx wrangler versions upload --secrets-file secrets.json

wrangler dev command for local preview

Use the wrangler dev command to preview a Workers site locally before deployment.

worker-sites-template starter repository

The Cloudflare worker-sites-template is a starter repository for creating Workers Sites projects. Clone it with the command: git clone --depth=1 --branch=wrangler2 https://github.com/cloudflare/worker-sites-template my-site

npx wrangler deploy for deployment

Use the npx wrangler deploy command to deploy a Workers site to Cloudflare.

wrangler dev and wrangler deploy commands for static sites

Use 'wrangler dev' to preview your static site locally or 'npx wrangler deploy' to deploy it to Cloudflare. Wrangler automatically uploads assets found in the configured site.bucket directory.

wrangler init command creates initial Worker files

Running 'wrangler init -y' in your project root generates or updates: wrangler.jsonc (project configuration), package.json (Wrangler devDependencies added), tsconfig.json (added if not present for TypeScript support), and src/index.ts (basic Cloudflare Worker in TypeScript).

wrangler deploy uploads configured static assets automatically

When running 'wrangler deploy' or 'npx wrangler deploy', Wrangler automatically uploads the static assets found in the directory configured in the site.bucket setting without requiring any additional manual steps.

Disable bundling with --no-bundle flag

You can opt out of Wrangler bundling by using the '--no-bundle' command line flag: 'npx wrangler deploy --no-bundle'. When bundling is disabled, Wrangler will not process your code and features like minification and polyfills injection will not be available. This option is only recommended when deploying code pre-processed by other tooling.

View bundled Worker code with --dry-run and --outdir

To review the exact code that Wrangler will upload to Cloudflare, run 'npx wrangler deploy --dry-run --outdir dist', which shows the Worker code after Wrangler's bundling.

Wrangler artifacts command namespace

Wrangler provides an 'artifacts' command namespace for managing Artifacts namespaces, repositories, and repo-scoped tokens. This feature is currently in private beta.

wrangler browser command

The wrangler browser command is used to interact with Cloudflare Browser Run service. This is a reference for Wrangler commands related to the Browser Run product.

cert list command

The `npx wrangler cert list` command lists all uploaded mTLS and CA certificates. It displays the certificate ID, name, issuer information, creation date, and expiration date for each certificate.

cert delete command

The `npx wrangler cert delete` command deletes an mTLS or CA certificate. It requires the `--id` flag with the certificate ID. The command prompts for confirmation before deleting.

cert upload mtls-certificate command

The `npx wrangler cert upload` command uploads an mTLS certificate for use with Hyperdrive configurations. It requires the following flags: `--cert` (certificate file), `--key` (private key file), and `--name` (certificate name). Example: `npx wrangler cert upload --cert cert.pem --key key.pem --name my-origin-cert`. The certificate and private keys must be in separate files, typically `.pem` files.

cert upload certificate-authority command

The `npx wrangler cert upload certificate-authority` command uploads a Certificate Authority (CA) chain certificate for use with Hyperdrive configurations. It requires the following flags: `--ca-cert` (CA certificate file) and `--name` (certificate name). Example: `npx wrangler cert upload certificate-authority --ca-cert server-ca-chain.pem --name SERVER_CA_CHAIN`.

wrangler d1 namespace exists for D1 database commands

Wrangler has a d1 namespace that provides commands for interacting with Cloudflare D1 databases. The d1 command group is used to manage D1 resources.

createTestHarness TestHarness return type methods

createTestHarness() returns a TestHarness object with methods: listen() returns Promise<{ url: URL }> - starts the server and returns its current URL, repeated calls return the same session until closed or reset; fetch(input, init) returns Promise<Response> - dispatches a fetch request through the server, relative URLs resolve against current server URL, absolute URLs follow configured Worker routes and fall back to primary Worker; getWorker(name?) returns WorkerHandle - returns a handle for dispatching events directly to a Worker, when no name provided returns primary Worker; getLogs() returns WorkerdStructuredLog[] - returns captured Workers runtime logs since current server session started or clearLogs() was last called; clearLogs() returns void - clears captured Workers runtime logs; debug() returns void - prints a diagnostic timeline for this test server; update(optionsOrUpdater) returns Promise<void> - updates server configuration with TestHarnessOptions object or function, if server not started configures options used by listen(), if running reloads Workers, updating number of Workers in running server not supported; reset() returns Promise<void> - restores server to options used when current session first started, storage recreated and server URL may change; close() returns Promise<void> - stops server and releases all runtime resources.

getPlatformProxy usage example with environment variables

Example using getPlatformProxy with environment variables configured in wrangler.json: Wrangler configuration: { "vars": { "MY_VARIABLE": "test" } } Code to access bindings: import { getPlatformProxy } from "wrangler"; const { env } = await getPlatformProxy(); console.log(`MY_VARIABLE = ${env.MY_VARIABLE}`); This prints: MY_VARIABLE = test

createTestHarness API overview

createTestHarness() starts one or more Workers for integration tests from any Node.js test runner. It runs production build output from Wrangler configuration files, Vite-generated configuration files, or inline Wrangler configuration objects. The API wraps Miniflare and provides methods for dispatching requests and scheduled events.

createTestHarness WorkerInput configuration file fields

Each WorkerInput loading from a Wrangler configuration file supports: configPath (string | URL, required) - path to a Wrangler configuration file, relative paths resolve from root; env (string, optional) - Wrangler environment to load from the configuration file; vars (Record<string, Json>, optional) - test-only variables that override variables from the Wrangler configuration file; secrets (Record<string, string>, optional) - test-only secrets that override values loaded from .dev.vars and .env files; bindingOverrides (Record<string, string>, optional) - test-only service binding overrides, keys are binding names in this Worker's environment, values are Worker names in this test harness.

Binding proxy emulation limitations

Binding proxies provided by getPlatformProxy are a best effort emulation of real production bindings. Although designed to be as close as possible to real bindings, there might be slight differences and inconsistencies between the two. In particular, all cache operations via the caches emulation do nothing, and a more accurate emulation will be made available in the future.

unstable_dev multi-Worker example with JavaScript

Example testing Workers that call other Workers using unstable_dev with JavaScript (deprecated, use createTestHarness instead): import { unstable_dev } from "wrangler"; describe("multi-worker testing", () => { let childWorker; let parentWorker; beforeAll(async () => { childWorker = await unstable_dev("src/child-worker.js", { config: "src/child-wrangler.toml", experimental: { disableExperimentalWarning: true }, }); parentWorker = await unstable_dev("src/parent-worker.js", { config: "src/parent-wrangler.toml", experimental: { disableExperimentalWarning: true }, }); }); afterAll(async () => { await childWorker.stop(); await parentWorker.stop(); }); it("childWorker should return Hello World itself", async () => { const resp = await childWorker.fetch(); const text = await resp.text(); expect(text).toMatchInlineSnapshot(`"Hello World!"`); }); it("parentWorker should return Hello World by invoking the child worker", async () => { const resp = await parentWorker.fetch(); const parsedResp = await resp.text(); expect(parsedResp).toEqual("Parent worker sees: Hello World!"); }); }); Note: if child Worker is shut down prematurely, parent Worker will not know child Worker exists and tests will fail.

unstable_dev single Worker example with JavaScript

Example using unstable_dev with JavaScript (deprecated, use createTestHarness instead): const { unstable_dev } = require("wrangler"); describe("Worker", () => { let worker; beforeAll(async () => { worker = await unstable_dev("src/index.js", { experimental: { disableExperimentalWarning: true }, }); }); afterAll(async () => { await worker.stop(); }); it("should return Hello World", async () => { const resp = await worker.fetch(); const text = await resp.text(); expect(text).toMatchInlineSnapshot(`"Hello World!"`); }); });

unstable_startWorker usage example

Example using unstable_startWorker (deprecated, use createTestHarness instead): import assert from "node:assert"; import test, { after, before, describe } from "node:test"; import { unstable_startWorker } from "wrangler"; describe("worker", () => { let worker; before(async () => { worker = await unstable_startWorker({ config: "wrangler.json" }); }); test("hello world", async () => { assert.strictEqual( await (await worker.fetch("http://example.com")).text(), "Hello world", ); }); after(async () => { await worker.dispose(); }); });

experimental_generateTypes usage example

Example generating types programmatically and writing to disk: import { experimental_generateTypes } from "wrangler"; import * as fs from "node:fs"; const result = await experimental_generateTypes({ config: "wrangler.json", includeRuntime: true, includeEnv: true, }); // Write the combined content to the path specified in options fs.writeFileSync(result.path, result.content, "utf-8"); To generate only env types without runtime types: const result = await experimental_generateTypes({ includeRuntime: false, }); To generate types for a specific environment with a custom interface name: const result = await experimental_generateTypes({ env: "staging", envInterface: "StagingEnv", path: "./types/staging.d.ts", });

experimental_generateTypes API overview

experimental_generateTypes() generates TypeScript type definitions from Worker configuration. It uses the same core logic as the wrangler types CLI command. Unlike the CLI command, it does not write to disk automatically. Instead, it returns the generated type content as structured strings for the caller to handle as needed. The function has an experimental_ prefix because the API is experimental and may change in the future.

createTestHarness usage example with Node.js test runner

Example using Node.js built-in test runner: import assert from "node:assert/strict"; import { after, afterEach, before, describe, test } from "node:test"; import { createTestHarness } from "wrangler"; const server = createTestHarness({ workers: [ { configPath: "./wrangler.web.jsonc" }, { configPath: "./wrangler.api.jsonc" }, ], }); const apiWorker = server.getWorker("api-worker"); describe("Worker", () => { before(async () => { await server.listen(); }); afterEach(async () => { await server.reset(); }); after(async () => { await server.close(); }); test("dispatches through configured routes", async () => { const response = await server.fetch("http://example.com/users/123"); assert.equal(response.status, 200); }); test("calls a specific Worker directly", async () => { const response = await apiWorker.fetch( "http://api.example.com/v1/users/123", ); assert.equal(response.status, 200); }); test("triggers a scheduled handler", async () => { const result = await apiWorker.scheduled({ cron: "0 0 * * *", scheduledTime: new Date(), }); assert.equal(result.outcome, "ok"); }); }); This example shows dispatching through configured routes, calling a specific Worker directly, and triggering a scheduled handler.

WorkerHandle return type methods

getWorker(name?) returns a WorkerHandle object with methods: fetch(input, init) returns Promise<Response> - dispatches a fetch event directly to this Worker; scheduled(options) returns Promise<{ outcome: "ok" | "canceled" | "exception"; noRetry: boolean }> - dispatches a scheduled event directly to this Worker; getEnv() returns Promise<Env> - returns the full environment object configured for this Worker, including variables, secrets, and bindings; getExport() returns Promise<Service<Module['default']>> - returns the default Worker export, including RPC methods; applyD1Migrations(bindingName) returns Promise<void> - applies local D1 migration files that have not already run to a D1 binding on this Worker; getDurableObjectStorage(classNameOrBindingName, options) returns Promise<DurableObjectStorageHandle> - returns SQL storage access for a Durable Object instance; introspectWorkflow(bindingName) returns Promise<WorkflowIntrospector> - creates an introspector for Workflow instances created after this method is called; introspectWorkflowInstance(bindingName, instanceId) returns Promise<WorkflowInstanceIntrospector> - creates an introspector for a specific Workflow instance.

getPlatformProxy API overview

getPlatformProxy() provides a way to obtain an object containing proxies to local workerd bindings and emulations of Cloudflare Workers specific values, allowing emulation in a Node.js process. getPlatformProxy is designed exclusively for use in Node.js applications and cannot be run inside the Workers runtime. One general use case is emulating bindings in applications targeting Workers but running outside the Workers runtime, such as framework local development servers in Node.js, or for testing purposes.

getPlatformProxy parameters

getPlatformProxy(options) accepts an optional options object: environment (string) - the environment to use; configPath (string) - path to config file, if not specified searches from current directory up filesystem for Wrangler configuration file, must point to valid file if specified; persist (boolean | { path: string }) - indicates if and where to persist bindings data, if true or undefined defaults to same location used by Wrangler so data can be shared, if false no data persisted, note that wrangler's --persist-to adds subdirectory v3 while getPlatformProxy persist does not; remoteBindings (boolean, optional, default true) - whether remote bindings should be enabled.

unstable_dev parameters and return type

unstable_dev(script, options) accepts script (string, required) - path to Worker script relative to project root; options (object, optional) - optional options object containing wrangler dev configuration settings, can include experimental object with disableExperimentalWarning to disable warning about unstable_ APIs. Returns object with methods: fetch() returns Promise<Response> - send request to Worker; stop() returns Promise<void> - shut down dev server.

unstable_dev API deprecated

unstable_dev() is deprecated. Cloudflare recommends createTestHarness() for integration testing. To start a development server programmatically, use the Vite createServer() API with the Cloudflare Vite plugin.

experimental_generateTypes return type

experimental_generateTypes() returns a Promise resolving to an object with fields: content (string) - combined formatted output containing all generated sections, including headers and both env and runtime types; env (string | null) - generated environment and bindings types, or null when env types are excluded; path (string) - target declaration file path associated with this generation run; runtime (string | null) - generated runtime types, or null when runtime types are excluded.

getPlatformProxy return type

getPlatformProxy() returns a Promise resolving to an object with fields: env (Record<string, unknown>) - object containing proxies to bindings usable in same way as production bindings, matches shape of env object passed as second argument to modules-format workers, proxies to binding implementations run inside workerd, supports generic type argument for TypeScript typing; cf (IncomingRequestCfProperties, read-only) - mock of Request's cf property with data similar to production; ctx (object) - mock object containing implementations of waitUntil and passThroughOnException functions that do nothing; caches (object) - emulation of Workers caches runtime API, all cache operations currently do nothing; dispose() returns Promise<void> - terminates underlying workerd process, call after platform proxy no longer required, not needed for long running processes.

experimental_generateTypes parameters

experimental_generateTypes(options) accepts an optional options object mirroring wrangler types CLI flags: config (string | string[]) - path to Wrangler configuration file, can be an array for multi-config type resolution; env (string) - name of Wrangler environment to generate types for; envFile (string[]) - paths to .env files to load when inferring local variables and secrets; envInterface (string) - name of generated environment interface, defaults to Env; includeEnv (boolean) - whether to include environment and bindings types in output, defaults to true; includeRuntime (boolean) - whether to include runtime types in output, defaults to true; path (string) - path to declaration file for generated types, defaults to worker-configuration.d.ts; strictVars (boolean) - whether to generate strict literal and union types for variables, defaults to true.

createTestHarness parameters

createTestHarness(options) accepts an optional options object with: root (string, optional) - base directory used to resolve relative Worker configuration paths, defaults to process.cwd(); workers (WorkerInput[]) - workers to run in the test server, first Worker is the primary Worker.

wrangler flagship overview and availability

Use `wrangler flagship` to manage Flagship apps and feature flags from the command line. This command is available in Wrangler v4.107.0 and later.

wrangler flagship flags delete command

Delete feature flags using `wrangler flagship flags delete <APP_ID> <FLAG_KEY>`. Delete can also be used with multiple flag keys: `wrangler flagship flags delete <APP_ID> flag1 flag2 --force`. The `--force` flag is required when used with `--json` to prevent prompts from corrupting JSON output. The `--force` flag is also required when `rollout` and `split` would replace existing targeting rules that have conditions.

wrangler flagship flags evaluate command

Evaluate a feature flag for a specific user context using `wrangler flagship flags evaluate <APP_ID> <FLAG_KEY> --context <KEY>=<VALUE> --targeting-key <KEY>`. For example: `wrangler flagship flags evaluate <APP_ID> premium-banner --context plan=enterprise --context country=US --targeting-key user-42`. Use multiple `--context` flags to specify context values.

wrangler flagship flags rules update command

Change an existing targeting rule without rewriting the full rule set using `wrangler flagship flags rules update <APP_ID> <FLAG_KEY> --priority <PRIORITY_NUMBER> --rollout <ROLLOUT>`. For example: `wrangler flagship flags rules update <APP_ID> premium-banner --priority 1 --rollout 50%@user_id`.

wrangler flagship flags create compact rule syntax

The compact rule syntax for `wrangler flagship flags create` follows the pattern: `serve=<VARIATION>; when=<CONDITIONS>; rollout=<ROLLOUT>`. For example: `serve=on; when=plan equals enterprise AND country in [US,CA]; rollout=25%@user_id`. Use uppercase `AND` and `OR` outside quoted values to combine conditions. Quote values that contain reserved words or separators. For deeply nested condition groups, use the `--rule-json` flag instead.

wrangler flagship flags create with variations and rules

Create a feature flag with custom variations and targeting rules using the syntax: `wrangler flagship flags create <APP_ID> <FLAG_KEY> -V <VARIATION> -V <VARIATION> --default <DEFAULT_VALUE> --rule "<RULE_SYNTAX>"`. Use the `-V` flag to define variations (e.g., `-V on=true -V off=false`), the `--default` flag to set the default value, and the `--rule` flag to add targeting rules with compact rule syntax.

wrangler flagship flags create command basic usage

Create a boolean feature flag with `wrangler flagship flags create <APP_ID> <FLAG_KEY>`. With no variations specified, Wrangler automatically creates two variations: `on=true` and `off=false`, and serves `off` by default.

wrangler flagship flags list command

List all feature flags for an app using `wrangler flagship flags list <APP_ID>`. This command takes only the app ID, not individual flag keys.

wrangler flagship flags disable command

Disable a feature flag using `wrangler flagship flags disable <APP_ID> <FLAG_KEY>`. Disable can also be used with multiple flag keys: `wrangler flagship flags disable <APP_ID> flag1 flag2 flag3` disables all specified flags in a single command.

wrangler flagship flags get command

Retrieve a specific feature flag using `wrangler flagship flags get <APP_ID> <FLAG_KEY>`. The app ID is required as the first argument, followed by the flag key.

wrangler flagship apps create command and binding option

Create a Flagship app using `wrangler flagship apps create <APP_NAME>`. Pass `--binding <NAME>` when creating an app to add it to your `wrangler.json` or `wrangler.jsonc` file as a Worker binding.

wrangler flagship API token permissions table

Flagship API token permissions: `flagship:read` is required for listing apps, inspecting flags, evaluating flags, and reading changelogs. `flagship:write` is required for creating, updating, deleting, enabling, disabling, rolling out, and splitting apps or flags.

Hyperdrive wrangler commands

Wrangler provides commands to manage Hyperdrive database configurations. To manage mTLS client certificates and CA chain certificates used by Hyperdrive, refer to the Certificate commands documentation.

Core Wrangler commands for Workers

The core commands for creating, developing, and deploying Workers include wrangler dev, wrangler deploy, and wrangler versions. These commands are detailed on the Workers commands page.

Running Wrangler with package managers

Cloudflare recommends installing Wrangler locally in your project rather than globally. Wrangler commands are run via package manager exec syntax (e.g., npm exec, yarn exec, or pnpm exec). You can also add frequently-used Wrangler commands as scripts in package.json and invoke them with the package manager's run command (e.g., npm run deploy).

Wrangler command syntax structure

The general syntax for running Wrangler commands is: wrangler <COMMAND> <SUBCOMMAND> [PARAMETERS] [OPTIONS]. Commands may be run via package manager exec (e.g., npm exec wrangler <COMMAND>) or by adding them as scripts in package.json and running via package manager run command.

wrangler kv command purpose

The wrangler kv command is used to manage Workers KV namespaces and key-value pairs. It provides Wrangler commands for interacting with Workers KV storage.

wrangler pages command namespace

Wrangler provides a 'pages' command namespace for configuring Cloudflare Pages through Wrangler.

wrangler pipelines get commands accept resource ID or name

The wrangler get commands in the Pipelines namespace (pipelines get, pipelines streams get, and pipelines sinks get) accept either a resource ID or resource name as an argument.

wrangler queues namespace and commands

Wrangler provides a 'queues' namespace containing commands for managing Workers Queues configurations. Commands can be accessed via the wrangler queues command hierarchy.

Give your agent this brain