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 · all subjects

configuration

366 notes in this subject, read out of this brain and free to use. This is page 6 of 7.

Store Turso database secrets using wrangler secret put

To store the Turso authentication token as a secret for production, run 'npx wrangler secret put LIBSQL_DB_AUTH_TOKEN' and paste your token when prompted. The secret name must match exactly what your Worker code references.

Wrangler vars section for Turso database URL

In the wrangler.json or wrangler.toml configuration file, add a [vars] section (or vars object for JSON) containing LIBSQL_DB_URL with your Turso database connection string. This makes the URL available as an environment variable to your Worker.

Set secrets with wrangler

Use `npx wrangler secret put OPENAI_API_KEY` to set environment secrets for a Worker. This command prompts for the secret value interactively and stores it securely.

nodejs_compat compatibility flag for Node.js APIs

To use Node.js APIs like `crypto` in Cloudflare Workers, add the `nodejs_compat` compatibility flag to the `compatibility_flags` array in the wrangler configuration file.

Configure GitHub webhook for Worker

To set up a GitHub webhook: Go to your repository's Settings > Webhooks > Add webhook. Set the Payload URL to the `/webhook` path on your deployed Worker URL. Select 'application/json' as the content type. Enter a secret key. Select the specific events to trigger the webhook (such as Push, Pull request, or Branch or tag creation).

Set Worker secrets with wrangler secret put

Use the command `npx wrangler secret put SECRET_NAME` to set environment variables that should be kept secret. The command prompts for the value interactively. These secrets are stored securely and are accessible via the `env` parameter in the fetch handler.

Using wrangler vars for public environment variables

Add a 'vars' table to wrangler.toml to define public environment variables that can be safely committed to version control. These variables are accessible in Worker code via env.VARIABLE_NAME. Use vars for non-sensitive configuration like base IDs and table names.

Using wrangler secret for sensitive environment variables

Store sensitive values like API tokens using 'wrangler secret put SECRET_NAME'. This encrypts and stores the environment variable securely so it is not revealed in version control or to users. The secret becomes available as env.SECRET_NAME in the Worker code. Use this for tokens that should not be publicly visible.

wrangler.toml vars configuration example

The wrangler.toml file can include a 'vars' section as a JSON object with key-value pairs. Example: ```jsonc { "name": "workers-airtable-form", "main": "src/index.js", "compatibility_date": "2024-01-01", "vars": { "AIRTABLE_BASE_ID": "exampleBaseId", "AIRTABLE_TABLE_NAME": "Form Submissions" } } ```

Node.js compatibility required for database drivers

Node.js compatibility must be enabled in a Workers project to use database drivers, including mysql2. This is configured in the wrangler configuration file.

Node.js minimum version for Wrangler

Wrangler requires a Node.js version of 16.17.0 or later.

PostgreSQL connection string format

A PostgreSQL connection string follows the format: postgresql://username:password@host:port/database. Connection strings should be stored as secrets using wrangler secret put to avoid storing credentials as plain text.

PostgreSQL explicit parameters configuration in wrangler

PostgreSQL can be configured with explicit parameters in the wrangler configuration file: DB_USERNAME (string), DB_HOST (string), DB_PORT (number, default 5432), DB_NAME (string), and DB_PASSWORD (should be set as a secret). SSL should be enabled for secure connections.

Local PostgreSQL secrets configuration

For local development with secrets, create a .dev.vars file with format: DB_URL='<YOUR_POSTGRESQL_CONNECTION_STRING>'. This file stores secrets locally for use with wrangler dev without committing credentials.

Store OpenAI API key as secret

Use wrangler secret put OPENAI_API_KEY to set the API key as an environment secret. For local development, create a .dev.vars file in the Worker project root and add OPENAI_API_KEY = "<YOUR_OPENAI_API_KEY>" to make it available during local testing.

Add Postmark secret to deployed Worker with wrangler

To add the Postmark API token as a secret to a deployed Worker, run the command: npx wrangler secret put POSTMARK_API_TOKEN. You will be prompted to enter the token value.

Use .dev.vars instead of .env in Cloudflare Workers

Cloudflare Workers do not support .env files. Rename the .env file created by Prisma init to .dev.vars using: mv .env .dev.vars

wrangler.json KV namespace configuration

Configure KV namespaces in wrangler.json with a kv_namespaces array containing objects with 'binding' (the variable name to access the namespace) and 'id' (the namespace ID) properties. Example: {"binding": "cities", "id": "e29b263ab50e42ce9b637fa8370175e8"}

Toggle Preview URLs with wrangler configuration

Preview URLs can be toggled in the Wrangler configuration file using the `preview_urls` setting. Set `"preview_urls": true` to enable or `"preview_urls": false` to disable. If not specified, `preview_urls = workers_dev` is the default. Wrangler 3.91.0 or higher is required. Older Wrangler versions will default to Preview URLs being enabled.

Preview URLs configuration file examples

To enable Preview URLs in wrangler.json: ```jsonc { "preview_urls": true } ``` To disable Preview URLs in wrangler.json: ```jsonc { "preview_urls": false } ```

Vite plugin locates config file automatically

The Cloudflare Vite plugin looks for a wrangler.jsonc, wrangler.json, or wrangler.toml file in the root of the application by default and requires no configuration.

Wrangler config main field specifies entry file

The "main" field in wrangler.jsonc specifies the entry file for the Worker code, such as "./src/index.ts".

Wrangler config name field and Vite Environment

The "name" field in wrangler.jsonc specifies the Worker name and is also used as the name of the Worker's Vite Environment by default.

package.json requires ES modules

Include "type": "module" in package.json to use ES modules by default when using the Vite plugin.

Vite plugin generates flattened wrangler.json combining all config types

When building with the Cloudflare Vite plugin, the output wrangler.json file is flattened to contain only the selected Cloudflare environment configuration. This flattened configuration combines top-level only keys, inheritable keys, and non-inheritable keys from the original wrangler.json file. Environment-specific values override top-level values.

CLOUDFLARE_ENV has no effect with vite preview or wrangler deploy

Specifying CLOUDFLARE_ENV when running 'vite preview' or 'wrangler deploy' will have no effect. The CLOUDFLARE_ENV variable is only applied at dev and build time, not at preview or deployment time.

Combine Cloudflare environments with Vite modes using .env files

You can combine Cloudflare environments with Vite modes by using .env files. Create files like .env.staging and .env.production, each containing the appropriate CLOUDFLARE_ENV value. By default, 'vite build' uses the 'production' Vite mode and loads .env.production. Running 'vite build --mode staging' will use the .env.staging file instead. This allows a single method to determine environment-specific configuration and code.

Environment-specific vars override top-level vars in flattened config

When a Cloudflare environment defines vars with the same name as top-level vars, the environment-specific values take precedence in the flattened wrangler.json output. For example, if the top-level 'MY_VAR' is set to 'Top-level var' but the 'production' environment sets it to 'Production var', the flattened production config will contain 'Production var'.

CLOUDFLARE_ENV environment variable selects Cloudflare environment at dev/build time

The Cloudflare Vite plugin allows you to select a Cloudflare environment during development or build time by providing the CLOUDFLARE_ENV environment variable. For example, running 'CLOUDFLARE_ENV=production vite build' will generate output with the 'production' Cloudflare environment configuration. Running 'vite dev' or 'vite build' without providing CLOUDFLARE_ENV will use the default top-level Cloudflare environment.

PluginConfig.config field

config is an optional field of type WorkerConfigCustomizer<true> that allows customizing or overriding Worker configuration programmatically. It accepts a partial configuration object or a function that receives the current config. It is applied after any config file loads and can be used to override values, modify the existing config, or define Workers entirely in code.

PluginConfig.persistState field

persistState is an optional field that can be a boolean or an object with a path property. By default, state is persisted to .wrangler/state. A custom path can be provided via the path property, or persistence can be disabled by setting the value to false.

PluginConfig.inspectorPort field

inspectorPort is an optional field that can be a number or false. By default, the debugging inspector is enabled and listens on port 9229. A custom port can be provided or debugging can be disabled by setting this to false.

PluginConfig.auxiliaryWorkers field

auxiliaryWorkers is an optional array of AuxiliaryWorkerConfig objects that specifies additional Workers used as part of the application. Auxiliary Workers can be called from the main entry Worker using service bindings. All requests are routed through the entry Worker. During build, each Worker is output to a separate subdirectory of dist. When running 'wrangler deploy', only the main entry Worker is deployed; each auxiliary Worker must be deployed individually using 'wrangler deploy -c dist/<auxiliary-worker>/wrangler.json'.

AuxiliaryWorkerConfig.configPath field

configPath is an optional string field in AuxiliaryWorkerConfig that specifies the path to the Worker config file. This field is required unless config is provided. The CLOUDFLARE_VITE_WRANGLER_CONFIG_PATH environment variable only applies to the entry Worker and not to auxiliary Workers, so configPath must be set explicitly for auxiliary Workers that use a config file.

cloudflare() plugin inclusion in Vite config

The cloudflare plugin from @cloudflare/vite-plugin should be included in the Vite plugins array. It accepts an optional PluginConfig parameter.

AuxiliaryWorkerConfig.config field

config is an optional field of type WorkerConfigCustomizer<false> in AuxiliaryWorkerConfig that allows customizing or overriding Worker configuration programmatically. When used without configPath, it allows defining auxiliary Workers entirely in code.

AuxiliaryWorkerConfig.viteEnvironment field

viteEnvironment is an optional field in AuxiliaryWorkerConfig that accepts an object with name and childEnvironments properties. By default, the environment name is the Worker name with hyphens replaced by underscores. The name property overrides this default. The childEnvironments property supports React Server Components via @vitejs/plugin-rsc and frameworks built on top of it, enabling embedding of additional environments with separate module graphs inside a single Worker.

cloudflare() plugin Vite config example

Example of including the cloudflare plugin in vite.config.ts: ```ts import { defineConfig } from "vite"; import { cloudflare } from "@cloudflare/vite-plugin"; export default defineConfig({ plugins: [cloudflare()], }); ```

PluginConfig.configPath field

configPath is an optional string field that specifies a path to the entry Worker config file. The plugin resolves the config path in this order: 1) configPath, 2) CLOUDFLARE_VITE_WRANGLER_CONFIG_PATH environment variable (typically set by a framework or external tool), 3) wrangler.jsonc, wrangler.json, or wrangler.toml in the root of the application. This applies to both 'vite dev' and 'vite build'.

Wrangler config options ignored by Vite plugin: build-related fields

The following build-related options in the Worker config file are handled by Vite and are not applicable when using the Cloudflare Vite plugin: tsconfig, rules, build, no_bundle, find_additional_modules, base_dir, preserve_file_names. If these options are provided, warnings will be printed to the console with suggestions for how to proceed.

Vite plugin creates separate output configuration file

With the Cloudflare Vite plugin, your Worker config file (for example, wrangler.jsonc) is the input configuration. A separate output configuration is created as part of the build. This output file is a snapshot of your configuration at the time of the build and is modified to reference your build artifacts. The output configuration is what is used for preview and deployment. After running vite build, running wrangler deploy or vite preview will automatically locate this output configuration file.

Set Cloudflare environment for Vite build using CLOUDFLARE_ENV variable

With the Cloudflare Vite plugin, Cloudflare Environments are applied at dev and build time. To deploy to a specific environment, set the environment by running CLOUDFLARE_ENV=some-env vite build. Running wrangler deploy --env some-env is not applicable with the Vite plugin.

Sourcemaps automatically uploaded when build.sourcemap enabled

If build.sourcemap is enabled for a given Worker environment in the Vite config, upload_source_maps: true is automatically added to the output Wrangler configuration file. This means generated sourcemaps are uploaded by default. To override this setting, you can set the value of upload_source_maps explicitly in the input Worker config.

Wrangler site option not supported by Vite plugin

The site option is not supported when using the Cloudflare Vite plugin. Use Workers Assets instead.

Wrangler config options replaced by Vite equivalents

The following Wrangler options have Vite equivalents that should be used instead: | Wrangler option | Vite equivalent | | --- | --- | | define | define (https://vite.dev/config/shared-options.html#define) | | alias | resolve.alias (https://vite.dev/config/shared-options.html#resolve-alias) | | minify | build.minify (https://vite.dev/config/build-options.html#build-minify) | | Local dev settings (ip, port, local_protocol, etc.) | Server options (https://vite.dev/config/server-options.html) |

Programmatic configuration example with function

Example of setting config as a function that accesses userConfig: ```ts import { defineConfig } from "vite"; import { cloudflare } from "@cloudflare/vite-plugin"; export default defineConfig({ plugins: [ cloudflare({ config: (userConfig) => ({ vars: { WORKER_NAME: userConfig.name, BUILD_TIME: new Date().toISOString(), }, }), }), ], }); ```

Config function can mutate configuration in place

A config function can mutate the config object directly instead of returning overrides. This is useful for deleting properties or removing array items. When editing in place, do not return a value from the function.

Wrangler config file is optional with Vite plugin

When using the Cloudflare Vite plugin, the Wrangler configuration file is optional. Without one, the plugin uses default values for Worker configuration.

Default Vite plugin configuration for assets-only Worker

Without a configuration file, the Vite plugin generates sensible defaults for an assets-only Worker. The name comes from package.json or the project directory name. The compatibility_date uses the latest date supported by the installed Miniflare version.

Programmatic config not included in wrangler types or resource CLI commands

Configuration set via the config option will not be included when running wrangler types or resource-based Wrangler CLI commands such as wrangler kv or wrangler d1.

Config option accepts any Wrangler configuration property

The config option in the Vite plugin accepts any property from the Wrangler configuration file. However, some options are ignored or replaced by Vite equivalents.

Cannot define Cloudflare environments via config option

Cloudflare environments cannot be defined via the config option because they are resolved before this option is applied.

Config as object merges with defaults and Wrangler file

When config is set to an object, those values merge with defaults and Wrangler config file settings, with config values taking precedence.

Config as function receives current configuration

When config is a function, it receives the current configuration (defaults or loaded config file) as a parameter and should return an object with values to merge.

Configuration merging behavior with defu

The config option uses defu for merging configuration objects. Object properties are recursively merged, arrays are concatenated with config values first then existing values, primitive values from config override existing values, and undefined values in config do not override existing values.

Programmatic configuration example with object

Example of setting config as an object: ```ts import { defineConfig } from "vite"; import { cloudflare } from "@cloudflare/vite-plugin"; export default defineConfig({ plugins: [ cloudflare({ config: { compatibility_date: "2025-01-01", vars: { API_URL: "https://api.example.com", }, }, }), ], }); ```

In-place config mutation example

Example of mutating config in place to replace compatibility flags: ```ts import { defineConfig } from "vite"; import { cloudflare } from "@cloudflare/vite-plugin"; export default defineConfig({ plugins: [ cloudflare({ config: (userConfig) => { userConfig.compatibility_flags = ["nodejs_compat"]; }, }), ], }); ```

Combining config file with config overrides

Example of combining a config file with config to override specific values: ```ts import { defineConfig } from "vite"; import { cloudflare } from "@cloudflare/vite-plugin"; export default defineConfig({ plugins: [ cloudflare({ configPath: "./wrangler.jsonc", auxiliaryWorkers: [ { configPath: "./workers/api/wrangler.jsonc", config: { vars: { ENDPOINT: "https://api.example.com/v2", }, }, }, ], }), ], }); ```

Programmatic configuration intended for frameworks and plugin developers

Programmatic configuration via the config option is primarily designed for use by frameworks and plugin developers. Users should normally use Wrangler config files instead.

Vite plugin does not require configuration by default

The Cloudflare Vite plugin requires no default configuration and automatically discovers wrangler configuration files in the root of the application.

Give your agent this brain