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

local-development

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

Vite plugin documentation location

The Vite plugin documentation for Cloudflare Workers is available at the external link /workers/vite-plugin/.

Vite Plugin for Cloudflare Workers

Cloudflare Workers provides a Vite plugin to develop and build Cloudflare Workers projects. The plugin enables integration with Vite for local development and build processes.

Wrangler vs Vite plugin capability comparison

Both Wrangler and the Cloudflare Vite plugin support: standalone JavaScript or TypeScript Workers, full-stack and backend Workers, local binding simulations via Miniflare, remote bindings, and multi-Worker development. Wrangler supports Rust Workers and Python Workers (via pywrangler), while the Vite plugin does not. Wrangler uses its own bundler or custom builds, while Vite plugin uses Vite transformations, Hot Module Replacement, and plugins. Wrangler supports deployment and resource management directly, while Vite plugin requires running `wrangler build` after `vite build`.

When to use Wrangler dev

Use `wrangler dev` when your project does not use Vite or you want a direct command-line workflow. Wrangler provides deployment and resource management commands in addition to local development.

When to use Cloudflare Vite plugin

Use the Cloudflare Vite plugin when your project already uses Vite or would benefit from its build pipeline. The Vite plugin integrates with Vite-powered frameworks and is valid for standalone backend Workers, not only frontend applications.

Hybrid Wrangler and Vite workflow

You can use the Vite plugin for development and builds while using Wrangler for deployment and other Workers commands. For local development requiring deployed resources, both tools support remote bindings where your Worker runs locally while selected bindings connect to deployed Cloudflare resources.

Replicating production behavior in local CPU profiling

When using DevTools to monitor CPU usage, requests sent to the local Worker should be similar to requests in production to mimic production behavior. This might mean sending a large volume of requests, making requests to specific routes, or using production-like data via remote bindings.

Rust Workers require DWARF debug symbols for CPU profiling

For Rust Workers, add `dwarf-debug-info = true` to the `[package.metadata.wasm-pack.profile.dev.wasm-bindgen]` section of `Cargo.toml` to preserve DWARF debug symbols. Then update `wrangler.toml` to configure wasm-pack via worker-build to use the `dev` profile: `[build] command = "cargo install -q worker-build && worker-build --dev"`

DevTools access in Cloudflare dashboard and Playground

Both the Cloudflare dashboard and the Worker's Playground include DevTools directly in their UI.

DevTools access with wrangler dev

When running a Worker locally using `wrangler dev`, Chrome DevTools are automatically available. Press the D key from the terminal to open DevTools in a browser tab.

DevTools access with Vite

When running a Worker locally using `vite` with the Cloudflare Vite plugin, Chrome DevTools are automatically available. Open the debug URL that appears in the console (for example, http://localhost:5173/__debug) in a new Chrome tab to access DevTools.

Debug exceptions from Wrangler with wrangler tail

To debug your worker via wrangler, use 'wrangler tail' to inspect and fix exceptions. Exceptions will show up under the 'exceptions' field in the JSON returned by wrangler tail. After identifying the exception causing errors, redeploy your code with a fix and continue tailing the logs to confirm it is fixed.

wrangler tail JSON output structure

The output of 'wrangler tail' is a structured JSON object with the following fields: outcome (string), scriptName (string or null), exceptions (array), logs (array), eventTimestamp (number in milliseconds), and event (object containing request details like url, method, headers, and cf).

View real-time logs with wrangler tail command

To view real-time logs using Wrangler, go to your Worker project directory and run 'npx wrangler tail'. This will log any incoming requests to your application in your local terminal. The output is a structured JSON object containing fields like outcome, scriptName, exceptions, logs, eventTimestamp, and event (which includes request details).

Parse wrangler tail output with jq

The output of 'wrangler tail' can be piped to tools like jq to query and manipulate requests. For example, 'npx wrangler tail | jq .event.request.url' will extract only the request URLs from the log stream.

WebSocket console.log visibility in wrangler tail

When using 'wrangler tail' with WebSocket event handlers, any console.log statements within those handlers are hidden until the WebSocket client closes the connection. Once the close event is received, all messages are flushed and printed to the terminal at once.

Minimum Wrangler version for Logpush

The minimum required Wrangler version for configuring Logpush jobs is 2.2.0. You can check your version by running wrangler --version.

Miniflare can output source maps for local development and testing

Miniflare can also output source maps for use in local development or testing, in addition to Wrangler's upload_source_maps functionality.

Refreshing expired temporary credentials

With Wrangler, rerun `wrangler deploy --temporary` if the temporary credentials or claim URL expire. Wrangler provisions a new account and prints a new claim URL. For REST integrations, request a new challenge and account if account.expiresAt or claim.expiresAt passes before the claim.

Wrangler temporary deployment output

When deploying with `wrangler deploy --temporary`, Wrangler prints output including: the account name and whether it was created or reused, the deadline to claim the account (60 minutes), and the claim URL in the format `https://dash.cloudflare.com/claim-preview?claimToken=<CLAIM_TOKEN>`. The output also shows the deployed Worker's accessible URL on `workers.dev`.

Wrangler deploy --temporary command

Use `wrangler deploy --temporary` when an AI agent or tool runs deployment commands. Wrangler manages the proof-of-work challenge, credentials, and claim URL. Wrangler 4.102.0 or later supports this flag. In an unauthenticated, non-interactive session, Wrangler will print output prompting to rerun with `--temporary`. Wrangler caches and reuses the account while its credentials and claim URL remain valid. Wrangler clears the cached account when you run `wrangler login` or `wrangler logout`. Wrangler stores temporary values in the current operating-system user's global configuration directory and should not be shared between platform users.

wrangler tail Durable Objects support

As of 2021-06-17, wrangler tail works on Durable Objects. Logs from long-lived WebSockets are not visible until the WebSocket closes.

wrangler dev alarm scheduling in global network preview

As of 2022-06-24, wrangler dev in global network preview mode supports scheduling alarms for Durable Objects.

wrangler dev --remote adds cf-workers-preview-token header

When running `wrangler dev --remote`, all outgoing requests are given the `cf-workers-preview-token` header, which Cloudflare recognizes as a preview request. This applies to the entire Cloudflare network, so making HTTP requests to other Cloudflare zones is currently discarded for security reasons. To work around this, delete the header before fetching: use `request.headers.delete('cf-workers-preview-token')` on the request object before calling fetch.

Checking compressed bundle size with Wrangler

To check your compressed bundle size, run: ```sh wrangler deploy --outdir bundled/ --dry-run ``` Output will resemble: ``` Total Upload: 259.61 KiB / gzip: 47.23 KiB ```

Routes with wrangler dev --remote limit

When you run a remote development session using the --remote flag, Cloudflare enforces a limit of 50 routes per zone. The Quick Editor in the Cloudflare dashboard also uses wrangler dev --remote, so the same limit applies. If your zone has more than 50 routes, you cannot run a remote session until you remove routes to get under the limit.

Playground editor features

The Playground uses the same editor as the authenticated experience and provides type-checking via JSDoc comments and the @cloudflare/workers-types package. It includes pretty error pages for application errors.

Playground requires no setup or authentication

The Cloudflare Workers Playground provides a sandbox environment for experimenting with Workers without requiring any setup or authentication.

Cloudflare Workers Playground browser support

The Cloudflare Workers Playground is supported in Firefox and Chrome desktop browsers. It does not work in Safari, which shows a PreviewRequestFailed error message.

Playground auto-updates on code changes

As you edit code in the Playground, the Worker auto-updates such that the preview on the right shows the Worker running as it would in a browser. URL paths can be entered in the input field on the right to navigate to them.

Full debugging with Wrangler for local development

For a more complete development experience with full debugging capabilities beyond the Playground, Wrangler can be used locally. Existing Workers from the dashboard can be cloned for local development using the wrangler init --from-dash command.

Playground share links do not expire

Shared links from the Playground can be copied via the Copy Link button in the top right of the screen. These links do not expire and can be bookmarked and shared at any time. Users who open a shared link see the Playground with the shared code and preview.

assets.bucket field error resolution

If you see the error 'assets.bucket is a required field', you need to update Wrangler to at least version 3.78.10 or later. The bucket field is not actually a required field in current versions.

C3 CLI creates new Worker projects

C3 (create-cloudflare-cli) is a command-line tool designed to help you set up and deploy new applications to Cloudflare. Use `npx create-cloudflare@latest <project-name>` to create a Worker project.

wrangler dev starts local development server

Run `npx wrangler dev` in the project directory to start a local server. This allows you to preview your project locally during development before deployment.

Default local development port differs between Pages and Workers

wrangler pages dev exposes the local development server at http://localhost:8788 by default, while wrangler dev exposes it at http://localhost:8787/ by default. The port can be customized using the --port flag.

Wrangler commands migration from Pages

When migrating from Pages, replace 'wrangler pages dev' with 'wrangler dev' and 'wrangler pages deploy' with 'wrangler deploy'. Additionally, if using a Vite-powered framework, consider using the Cloudflare Vite plugin for a simpler development experience.

Vite plugin for local development of SPA frameworks

If you are using a Vite-powered SPA framework, you can use the Vite plugin for Workers which offers a Vite-native developer experience.

SPA local development with Vite plugin

When using a Vite-powered SPA framework, the Cloudflare Vite plugin offers a Vite-native developer experience for local development.

Miniflare compatibility flags configuration

Miniflare allows you to opt-in or opt-out of specific backwards-incompatible changes using compatibility flags. Compatibility flags are passed as an array of strings to the compatibilityFlags property of the Miniflare constructor options. Example flags include "formdata_parser_supports_files" and "durable_object_fetch_allows_relative_url".

Miniflare compatibility date configuration

Miniflare uses compatibility dates to opt-into backwards-incompatible changes from a specific date. If a compatibility date is not set, Miniflare defaults to some time far in the past. Set the compatibility date by passing a compatibilityDate string property (e.g., "2021-11-12") to the Miniflare constructor options.

Miniflare constructor compatibility date example

To configure a compatibility date in Miniflare, instantiate with: const mf = new Miniflare({ compatibilityDate: "2021-11-12" });

Miniflare constructor compatibility flags example

To configure compatibility flags in Miniflare, instantiate with: const mf = new Miniflare({ compatibilityFlags: ["formdata_parser_supports_files", "durable_object_fetch_allows_relative_url"] });

Miniflare supported module types

Miniflare supports five module types: ESModule, CommonJS, Text, Data, and CompiledWasm.

Configure module resolution rules in Miniflare

Module resolution rules can be specified via the `modulesRules` option as an array of rule objects. Each rule has `type` (the module type), `include` (a glob pattern array), and optionally `fallthrough` (boolean). Rules are matched in order, and default rules are automatically appended at the end.

String scripts cannot import other modules in Miniflare

When using the `script` option with string content, the modules format is supported but you cannot import other modules. To use module imports, you must use a script file via the `scriptPath` option instead.

Enable modules format in Miniflare

To use the modules format with Miniflare, pass the `modules: true` option to the Miniflare constructor.

Miniflare default module rules

Miniflare automatically adds default module rules at the end of the modulesRules list: ESModule for files matching `**/*.mjs`, and CommonJS for files matching `**/*.js` and `**/*.cjs`. These default rules can be overridden by specifying rules with matching globs.

Custom hostnames in Miniflare require hosts file configuration

When using hostnames that aren't `localhost` or `127.0.0.1` with Miniflare, you may need to edit your computer's `hosts` file so those hostnames resolve to localhost. On Linux and macOS, this is at `/etc/hosts`. On Windows, it's at `C:\Windows\System32\drivers\etc\hosts`. Add entries like '127.0.0.1 api.mf'.

Multiple workers in same Miniflare instance with workers option

Miniflare allows you to run multiple workers in the same instance. All workers can be defined at the same level using the `workers` option, which accepts an array of worker configurations.

Miniflare multiple workers code example with KV and service bindings

Example showing two workers in Miniflare: one uses service bindings to call an incrementer worker and a custom function, while accessing a shared KV namespace. The incrementer worker also accesses the same KV namespace under a different binding name. Both worker format styles (modules and addEventListener) can be mixed and matched.

Miniflare dispatchFetch uses request URL for worker routing

When using the Miniflare API, dispatchFetch will use the request's URL to determine which Worker to dispatch to. For example, `mf.dispatchFetch("http://api.mf/todos/update/1")` dispatches based on the hostname in the URL.

Customize Host header for Miniflare requests

Instead of editing the hosts file, you can customize the `Host` header when sending requests to Miniflare to route to specific workers. For example, `curl "http://localhost:8787/todos/update/1" -H "Host: api.mf"` dispatches to the 'api' worker.

Service bindings as custom functions in Miniflare

Service bindings in Miniflare can be defined as custom async functions with access to the incoming Request object and anything defined outside Miniflare. The function receives the `request` parameter and must return a Response object.

Miniflare top-level options shared between workers

Options shared between workers such as HTTP and persistence configuration should always be defined at the top level of the Miniflare configuration, not within individual worker objects. Examples include `host`, `port`, and `kvPersist`.

Miniflare liveReload script injection requirements

Miniflare will only inject the <script> tag required for live-reload at the end of responses with the Content-Type header set to text/html. Responses with other content types will not receive the live-reload script.

Enable Miniflare live-reload example

This example shows how to enable live-reload in Miniflare: const mf = new Miniflare({ liveReload: true, });

Miniflare liveReload configuration option

Miniflare has a liveReload option that can be set to true in the Miniflare constructor. When enabled, Miniflare automatically refreshes the browser when your Worker script changes during local development.

Miniflare features and capabilities

Miniflare is fully-featured and supports most Workers features including KV, Durable Objects, WebSockets, and modules. It is fully-local, allowing you to test and develop Workers without an Internet connection, with quick code reload on change.

Miniflare is a local simulator for Workers development and testing

Miniflare is a simulator for developing and testing Cloudflare Workers. It is written in TypeScript and runs your code in a sandbox implementing Workers' runtime APIs. It enables developing Workers easily with detailed logging, file watching and pretty error pages supporting source maps.

Give your agent this brain