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 4 of 7.

Pywrangler CLI tool for Python Workers

Pywrangler is a CLI tool for managing packages and Python Workers. It is a wrapper for wrangler that sets up a full environment and bundles packages into the worker bundle on deployment.

Python Workers pyproject.toml configuration

A Python Workers project requires a pyproject.toml file. It should include a [project] section with name, version, description, and requires-python specification (e.g., ">=3.13"), plus a dependencies list. A [dependency-groups] section with dev dependencies should include "workers-py" and "workers-runtime-sdk".

Running Python worker locally

To run a Python worker locally, use the command: uv run pywrangler dev

Deploying Python worker

To deploy a Python worker, use the command: uv run pywrangler deploy. Dependencies are automatically bundled with the worker on deployment.

Pywrangler supports all wrangler commands

The pywrangler CLI supports all commands that the wrangler tool supports. Run uv run pywrangler --help to see the full list of available commands.

Example package.json scripts for wrangler types

Example scripts to integrate wrangler types generation: {"scripts": {"dev": "existing-dev-command", "build": "existing-build-command", "generate-types": "wrangler types", "type-check": "generate-types && tsc"}}. This generates types before type-checking.

Example tsconfig.json with generated types

Example tsconfig.json configuration: {"compilerOptions": {"types": ["./worker-configuration.d.ts"]}}. If using nodejs_compat flag, also include: {"compilerOptions": {"types": ["./worker-configuration.d.ts", "node"]}}

wrangler types --include-env flag

The `wrangler types` command generates `Env` types by default. If you do not want to include `Env` types for some reason, use the `--include-env=false` flag.

TypeScript is a first-class language on Cloudflare Workers

TypeScript is fully supported on Cloudflare Workers. All APIs provided in Workers are fully typed, and type definitions are generated directly from workerd, the open-source Workers runtime.

Generate types with wrangler types command

Run `wrangler types` to generate TypeScript type definitions for your Worker. This command generates a `.d.ts` file (saved to `worker-configuration.d.ts` by default) that includes both runtime types based on your Worker's compatibility date and flags, and `Env` types based on your bindings.

Type definitions depend on compatibility date, flags, and bindings

The correct TypeScript types for a Worker depend on three factors: the Worker's compatibility date, the Worker's compatibility flags, and the Worker's bindings defined in the Wrangler configuration file. Additionally, any module rules specified in the Wrangler configuration file under `rules` can affect types.

AsyncLocalStorage requires nodejs_als compatibility flag

The `AsyncLocalStorage` class from Node.js is only available at runtime if you have `compatibility_flags = ["nodejs_als"]` in your Wrangler configuration file. This availability is reflected in the generated type definitions.

Add generated types file to tsconfig.json

After running `wrangler types`, add the generated file to your `tsconfig.json`'s `compilerOptions.types` array. The default path is `./worker-configuration.d.ts`. If you have the `nodejs_compat` compatibility flag, also add `"node"` to the types array.

Regenerate types after wrangler.toml changes

Ensure that you run `wrangler types` after any changes to your Wrangler configuration file to keep type definitions up-to-date with your Worker's configuration.

Migrate from @cloudflare/workers-types to wrangler types

It is recommended to use `wrangler types` to generate runtime types rather than using the `@cloudflare/workers-types` npm package. The `wrangler types` approach generates types based on your Worker's specific compatibility date and flags, ensuring types match the exact runtime APIs available to your Worker. The `@cloudflare/workers-types` package will continue to be published and is still recommended for typing libraries and shared packages.

wrangler types migration steps

To migrate from @cloudflare/workers-types to wrangler types: (1) Uninstall @cloudflare/workers-types; (2) Run `wrangler types` to generate a .d.ts file (saved to worker-configuration.d.ts by default); (3) Update tsconfig.json to include the generated types file in compilerOptions.types array; (4) If using nodejs_compat flag, install @types/node and add "node" to compilerOptions.types; (5) Update your scripts and CI pipelines to run `wrangler types` before TypeScript-dependent tasks.

Run wrangler types before TypeScript type-checking

Add the `wrangler types` command to your build and CI scripts, running it before any tasks that rely on TypeScript. This ensures types are always up-to-date with your configuration.

wrangler types --check flag for CI verification

Use the `--check` flag with `wrangler types` in CI pipelines to verify that committed type files are up-to-date. This fails the CI job if the committed types file is out-of-date, prompting developers to regenerate and commit the updated types.

Install @types/node for nodejs_compat compatibility flag

If you are using the `nodejs_compat` compatibility flag in your Wrangler configuration, you should also install the `@types/node` package and add `"node"` to your `tsconfig.json`'s `compilerOptions.types` array.

@cloudflare/workers-types version 5 changes

Version 5 and later of `@cloudflare/workers-types` exposes only the latest runtime types. Dated entrypoints such as `@cloudflare/workers-types/2022-11-30` have been removed. Import from `@cloudflare/workers-types` for the latest stable types, or from `@cloudflare/workers-types/experimental` for APIs behind experimental compatibility flags.

.env file for local environment variables

To set up environment variables for local development in the Vite plugin, create an `.env` file in your project root and add key-value pairs in ini format. After creating the file, run `vite dev` to use these variables.

Difference between .dev.vars and .env file precedence

When using environment-specific files, `.dev.vars.<environment-name>` completely replaces the default `.dev.vars` file. However, `.env.<environment-name>` files are merged with base `.env` files, with the most specific file taking precedence over less specific ones.

Example environment-specific configuration

Create a `.dev.vars.staging` or `.env.staging` file with staging-specific values such as: API_HOST="staging.localhost:3000", DEBUG="false", SECRET_TOKEN="staging-token".

.dev.vars file for local environment variables

To set up environment variables for local development in Wrangler, create a `.dev.vars` file in your project root and add key-value pairs in ini format. For example: API_HOST="localhost:3000", DEBUG="true", SECRET_TOKEN="my-local-secret-token". After creating the file, run `wrangler dev` to use these variables.

Environment-specific variable files for local development

To simulate different local environments, create environment-specific files named `.dev.vars.<environment-name>` or `.env.<environment-name>`. For Wrangler, run `wrangler dev --env <environment-name>` to use an environment-specific `.dev.vars` file, which will replace the default `.dev.vars` file entirely. For the Vite plugin, run `CLOUDFLARE_ENV=<environment-name> vite dev`, which will merge values from the specific `.env.<environment-name>` file with the base `.env` file, with the most specific file taking precedence.

Add local persistence folder to .gitignore

The local persistence folder (such as .wrangler/state or any custom folder you set) should be added to your .gitignore to avoid committing local development data to version control.

Use --persist-to with data modification commands

When you run wrangler dev --persist-to <DIRECTORY> with a custom location, you must also include the same --persist-to <DIRECTORY> flag and the --local flag when running other Wrangler commands that modify local data. Example: wrangler kv key put test 12345 --binding MY_KV_NAMESPACE --local --persist-to worker-local

Vite plugin persistState configuration

To customize where the Vite plugin stores local data, configure the persistState option in your vite.config.js file. Example: cloudflare({ persistState: { path: "./my-custom-directory" } })

Share state between Wrangler and Vite plugin

To make Wrangler and the Vite plugin share the same local state, configure them to use the same persistence path.

Use --persist-to flag with wrangler dev

Use the --persist-to flag with wrangler dev to specify a custom directory for local storage. You must specify this flag every time you run the dev command. Example: wrangler dev --persist-to <DIRECTORY>

Axiom destination configuration in wrangler.json

To enable telemetry export to Axiom, add an observability section to wrangler.json with traces and logs configuration. Under each, set enabled to true and specify destinations as an array containing the destination name created in the Cloudflare dashboard. Example: {"observability": {"traces": {"enabled": true, "destinations": ["axiom-traces"]}, "logs": {"enabled": true, "destinations": ["axiom-logs"]}}}

Wrangler configuration for Grafana Cloud telemetry export

To enable telemetry export to Grafana Cloud, add the following observability configuration to wrangler.json: {"observability": {"traces": {"enabled": true, "destinations": ["grafana-traces"]}, "logs": {"enabled": true, "destinations": ["grafana-logs"]}}}. The destination names must match the destination names configured in the Cloudflare dashboard.

Wrangler configuration for Honeycomb telemetry export

To enable telemetry export to Honeycomb in wrangler.json, add an observability object with traces and logs sub-objects. Each sub-object must have enabled set to true and destinations set to an array containing the destination names matching those created in the Cloudflare dashboard (e.g., ["honeycomb-traces"] for traces and ["honeycomb-logs"] for logs). Example configuration: {"observability": {"traces": {"enabled": true, "destinations": ["honeycomb-traces"]}, "logs": {"enabled": true, "destinations": ["honeycomb-logs"]}}}

wrangler.json observability logs configuration for PostHog

To enable logs export to PostHog in wrangler.json, add the following configuration: ```json { "observability": { "logs": { "enabled": true, "destinations": ["posthog-logs"] } } } ``` The destination name must match the name created in the Cloudflare dashboard.

Wrangler observability configuration

Configure OpenTelemetry export in wrangler.json with the observability field: ```json { "observability": { "traces": { "enabled": true, "destinations": ["tracing-destination-name"], "head_sampling_rate": 0.05, "persist": false }, "logs": { "enabled": true, "destinations": ["logs-destination-name"], "head_sampling_rate": 0.6, "persist": false } } } ``` The destination names must match those configured in the Cloudflare dashboard. The head_sampling_rate controls what percentage of events are sampled (0.05 = 5%, 0.6 = 60%). The persist field (default true) controls whether data is also stored in the Cloudflare dashboard; set to false to only export to your external destination.

Enable Sentry observability in wrangler.toml

Add observability configuration to wrangler.toml to enable telemetry export to Sentry. Set observability.traces.enabled to true with destinations matching the dashboard destination name (e.g., 'sentry-traces'). Set observability.logs.enabled to true with destinations matching the dashboard destination name (e.g., 'sentry-logs'). Deploy the Worker after updating configuration.

Sentry observability wrangler configuration example

To enable Sentry observability export, use this wrangler.toml configuration: ```json { "observability": { "traces": { "enabled": true, "destinations": ["sentry-traces"] }, "logs": { "enabled": true, "destinations": ["sentry-logs"] } } } ``` The destination names must match the destination names created in the Cloudflare dashboard.

Example wrangler configuration with logpush enabled

Example of enabling logpush in wrangler.json: ```jsonc { "$schema": "./node_modules/wrangler/config-schema.json", "name": "my-worker", "main": "src/index.js", "compatibility_date": "$today", "workers_dev": false, "logpush": true, "route": { "pattern": "example.org/*", "zone_name": "example.org" } } ```

Enable logpush in wrangler.json

Enable logging on your Worker by adding the property logpush = true to your wrangler.json file. This can be added either in the top-level configuration or under an environment configuration. Any new Workers with this property will automatically get picked up by the Logpush job.

Enable source maps with upload_source_maps configuration

To enable source maps for a Worker, add `"upload_source_maps": true` to the Wrangler configuration file. When this setting is enabled, Wrangler will automatically generate and upload source map files when you run `wrangler deploy` or `wrangler versions deploy`.

Built with Cloudflare button HTML syntax

To embed the Built with Cloudflare button in HTML, use the following snippet: <a href="https://cloudflare.com"><img src="https://workers.cloudflare.com/built-with-cloudflare.svg" alt="Built with Cloudflare"/></a>

Built with Cloudflare button versus Deploy to Cloudflare buttons

The Built with Cloudflare button is used to share that you are using Cloudflare products on your website or application. This is different from Deploy to Cloudflare buttons, which allow people to deploy your application on their own account.

Built with Cloudflare button SVG URL

The Built with Cloudflare button is available as an SVG at https://workers.cloudflare.com/built-with-cloudflare.svg. It can be embedded in READMEs, blog posts, and documentation to indicate that an application or website is built on Cloudflare products.

Built with Cloudflare button Markdown syntax

To embed the Built with Cloudflare button in Markdown, use the following snippet: [![Built with Cloudflare](https://workers.cloudflare.com/built-with-cloudflare.svg)](https://cloudflare.com)

Changelog differs from compatibility dates and flags

The Workers changelog is different from compatibility dates and compatibility flags, which let you explicitly opt-in to or opt-out of specific changes to the Workers Runtime.

url_standard feature flag for spec-compliant URL API

As of 2022-02-05, a new spec-compliant URL API implementation is available. Use the url_standard feature flag to enable it.

streams_byob_reader_detaches_buffer compatibility flag

As of 2021-11-05, the streams_byob_reader_detaches_buffer compatibility flag was introduced and enabled by default on 2021-11-10. Per Streams spec, when using BYOB reader, the ArrayBuffer of provided TypedArray should be detached. Code should never reuse an ArrayBuffer passed to BYOB reader read() method.

workers_api_getters_setters_on_prototype flag

As of 2022-01-07, the workers_api_getters_setters_on_prototype configuration flag corrects the way Workers attaches property getters and setters to API objects so they can be properly subclassed.

minimal_subrequests compatibility flag

As of 2022-03-24, a new compatibility flag minimal_subrequests removes features that were unintentionally being applied to same-zone fetch() calls. The flag defaulted to enabled on 2022-04-05.

capture_async_api_throws flag behavior

As of 2022-03-17, when the capture_async_api_throws flag is set, built-in Cloudflare-specific and Web Platform Standard APIs that return Promises will no longer throw synchronously and instead return rejected promises, except for fatal errors like out of memory.

global_navigator flag for navigator.userAgent

As of 2022-03-04, with the global_navigator compatibility flag set, the navigator.userAgent property can be used to detect when code is running within the Workers environment.

Increasing CPU time limit in Wrangler configuration

To increase the maximum CPU time from the default 30 seconds to 5 minutes (300,000 ms) on Workers Paid plan, set this in wrangler.jsonc: ```jsonc { "limits": { "cpu_ms": 300000, }, } ``` You can also change this in the dashboard by going to Workers & Pages > select your Worker > Settings > adjust the CPU time limit.

CPU time limits configuration

To prevent accidental runaway bills or denial-of-wallet attacks, you can configure the maximum amount of CPU time that can be used per invocation by defining limits in your Worker's Wrangler file or via the Cloudflare dashboard (Workers & Pages > Select your Worker > Settings > CPU Limits). If a Worker on the Bundled usage model was migrated to Standard pricing on March 1, 2024, Cloudflare automatically added a 50 ms CPU limit to that Worker.

Environment variables in ES modules format

In ES modules format, environment variables are available through the env parameter provided at the Worker entrypoint, accessed as env.VARIABLE_NAME. Alternatively, you can import env from cloudflare:workers to access environment variables from anywhere in your code.

Environment variables in Service Worker format

In Service Worker format, environment variables defined in wrangler.json via vars are available in global scope and can be accessed directly by name, for example: console.log(API_ACCOUNT_ID).

Importing env from cloudflare:workers

In ES modules, you can import env from 'cloudflare:workers' to access environment variables at the top level or from deeply nested functions without passing env through every function call: import { env } from 'cloudflare:workers'; const accountId = env.API_ACCOUNT_ID;

run_worker_first configuration option

The run_worker_first setting controls whether to invoke the Worker script regardless of a request that would have otherwise matched an asset. When run_worker_first = false (default), any static asset matching a request will be served. When run_worker_first = true, the Worker script will be unconditionally invoked. The setting can also be specified as an array of route patterns to selectively run the Worker script first only for specific routes, using glob patterns with * for deep matching and negative patterns with ! prefix. Negative patterns have precedence over non-negative patterns.

.assetsignore file for excluding assets

Create a .assetsignore file in the root of the assets directory to prevent certain files from being uploaded as static assets. This file takes the same format as .gitignore. Wrangler will not upload asset files that match lines in this file. Common use cases include excluding server-side Worker code like _worker.js and configuration files like _redirects and _headers when migrating from a Pages project.

run_worker_first with glob patterns example

Example configuration using run_worker_first as an array of route patterns. In this configuration, requests to /api/* routes will invoke the Worker script first, except for /api/docs/* which will follow the default asset-first routing behavior: ```json { "name": "my-spa-worker", "compatibility_date": "$today", "main": "./src/index.ts", "assets": { "directory": "./dist/", "not_found_handling": "single-page-application", "binding": "ASSETS", "run_worker_first": ["/api/*", "!/api/docs/*"] } } ``` Common uses for run_worker_first include authentication checks, A/B testing, and injecting bootstrap data into SPA shells.

Static assets directory configuration

To configure static assets in a Worker, specify the directory containing static assets in the Wrangler configuration file under the assets.directory property. The folder of static assets to be served is typically the ./public/, ./dist/, or ./build/ folder. Only one collection of static assets can be configured in each Worker.

Give your agent this brain