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 2 of 3.

Miniflare API is for advanced use cases only

The Miniflare API documentation is relevant only for advanced use cases. Most users should use Wrangler instead to build, run, and deploy their Workers locally.

reload() method removed in Miniflare v3

The reload() method has been removed from Miniflare v3. Call setOptions() with the original configuration object to reload Miniflare instead.

Miniflare v3 uses workerd runtime

Miniflare v3 now uses workerd, the open-source Cloudflare Workers runtime that is deployed on Cloudflare's network. This provides bug-for-bug compatibility and practically eliminates behavior mismatches between local development and production.

Miniflare v3 no longer includes standalone CLI

Miniflare v3 does not include a standalone CLI. To get the same functionality, use Wrangler v3 instead, which uses Miniflare v3 by default. Run 'npx wrangler@3 dev' to start a local development server.

wranglerConfigPath and wranglerConfigEnv removed in Miniflare v3

Miniflare v3 no longer handles Wrangler's configuration. To programmatically start up a Worker based on Wrangler configuration, use the unstable_dev() API instead.

watch option removed in Miniflare v3

The watch option has been removed from Miniflare v3 because the API is primarily intended for testing use cases where file watching is not usually required. If you need to watch files, use a separate file watcher like fs.watch() or chokidar, and call setOptions() with your original configuration on change.

HTTPS server options removed in Miniflare v3

Miniflare v3 does not support starting HTTPS servers. The options https, httpsKey, httpsKeyPath, httpsCert, httpsCertPath, httpsPfx, httpsPfxPath, and httpsPassphrase have been removed. These options may be added back in a future release.

inaccurateCpu option replaced with inspectorPort in Miniflare v3

The inaccurateCpu option has been removed from Miniflare v3. To enable CPU profiling, set the inspectorPort option to 9229 to enable the V8 inspector. Then visit chrome://inspect in Google Chrome to open DevTools and perform CPU profiling.

setOptions() now requires full configuration in Miniflare v3

In Miniflare v3, setOptions() requires a full configuration object to be passed, instead of a partial patch as in v2.

createServer() and startServer() methods removed in Miniflare v3

The createServer() and startServer() methods have been removed from Miniflare v3. Miniflare now always starts a workerd server listening on the configured host and port, making these methods redundant.

dispatchScheduled() and startScheduled() methods removed in Miniflare v3

The dispatchScheduled() and startScheduled() methods have been removed from Miniflare v3. The functionality of dispatchScheduled() can now be done via getWorker(). Refer to the scheduled events documentation for more information.

dispatchQueue() method removed in Miniflare v3

The dispatchQueue() method has been removed from Miniflare v3. Use the queue() method on service bindings or queue producer bindings instead.

getGlobalScope(), getBindings(), getModuleExports() methods removed in Miniflare v3

The getGlobalScope(), getBindings(), and getModuleExports() methods have been removed from Miniflare v3 because these methods returned objects from inside the Workers sandbox. Since Miniflare now uses workerd which runs in a different process, these methods can no longer be supported.

addEventListener() and removeEventListener() methods removed in Miniflare v3

The addEventListener() and removeEventListener() methods have been removed from Miniflare v3. Miniflare no longer emits reload events. Reloads are only triggered by initialisation or setOptions() calls. To wait for a reload, use 'await mf.ready' or 'await mf.setOptions()' respectively.

@miniflare/* packages consolidated into single miniflare package

Miniflare v3 is contained within a single 'miniflare' package. The @miniflare/* scoped packages have been removed.

Miniflare installation as dev dependency

Miniflare is installed using npm as a dev dependency. The command is `npm install --save-dev miniflare` or equivalent in other package managers.

Miniflare requires Node.js ES module mode

To use Miniflare examples, Node.js must run in ES module mode. Set the `type` field to `"module"` in package.json.

Initialize Miniflare with Miniflare class

Import the `Miniflare` class from the `miniflare` package and instantiate it with a configuration object containing either `script` (inline string) or `scriptPath` (file path) and other options.

Miniflare basic example with inline script

Example showing how to initialize Miniflare with an inline script and dispatch a fetch event: ```js import { Miniflare } from "miniflare"; const mf = new Miniflare({ modules: true, script: ` export default { async fetch(request, env, ctx) { return new Response("Hello Miniflare!"); } } `, }); const res = await mf.dispatchFetch("http://localhost:8787/"); console.log(await res.text()); // Hello Miniflare! await mf.dispose(); ```

Miniflare with external script file

Instead of passing an inline `script` string, use `scriptPath` to specify a worker file path: ```js const mf = new Miniflare({ scriptPath: "worker.js", }); ```

Miniflare file watching and reloading

Miniflare's API does not include built-in file watching. For file watching, use a separate file watcher like fs.watch() or chokidar, then call setOptions() with the original configuration when files change.

Miniflare dispose method

Call `await mf.dispose()` to cleanup and stop listening for requests. This closes storage database connections and stops any watcher.

Miniflare setOptions method

Use the `setOptions` method to update options of an existing Miniflare instance. It accepts the same options object as the constructor, applies those options, and reloads the worker.

Dispatch events with Miniflare getWorker

`getWorker` returns an object that can dispatch `fetch`, `scheduled`, and `queue` events to workers. Call `await mf.getWorker()` to get the worker instance.

Miniflare scheduled event example

Example of dispatching a scheduled event to a worker: ```js const worker = await mf.getWorker(); const scheduledResult = await worker.scheduled({ cron: "* * * * *", }); console.log(scheduledResult); // { outcome: "ok", noRetry: true } ```

Miniflare queue event example

Example of dispatching a queue event to a worker: ```js const queueResult = await worker.queue("needy", [ { id: "a", timestamp: new Date(1000), body: "a", attempts: 1 }, { id: "b", timestamp: new Date(2000), body: { b: 1 }, attempts: 1 }, ]); console.log(queueResult); // { outcome: "ok", retryAll: true, ackAll: false, explicitRetries: [], explicitAcks: []} ```

Miniflare HTTP server auto-start

Miniflare starts an HTTP server automatically. To wait for it to be ready, `await` the `ready` property.

Miniflare Request cf object handling

By default, Miniflare fetches the `Request#cf` object from a trusted Cloudflare endpoint and caches it to `node_modules/.mf/cf.json`. Disable with `cf: false` option, or provide a custom path: `cf: "cf.json"`. The `cf` option takes precedence over environment variables.

Miniflare cf object environment variables

Control cf object behavior via environment variables (useful when not using Miniflare API directly, e.g., with `wrangler dev`): - `CLOUDFLARE_CF_FETCH_ENABLED=false` disables cf fetching entirely - `CLOUDFLARE_CF_FETCH_PATH=/tmp/.cf-cache.json` sets custom cache location

Miniflare HTTPS server setup

Set `https: true` to start an HTTPS server with a default self-signed certificate. To use custom certificates, set `httpsKeyPath` and `httpsCertPath` to file paths, or `httpsKey` and `httpsCert` to PEM-formatted strings. String values take precedence over path values if both are specified.

Miniflare logging configuration

Logs with `[mf:*]` prefix are disabled by default. Enable them by setting the `log` property to an instance of the `Log` class with a `LogLevel` parameter. Example: ```js import { Miniflare, Log, LogLevel } from "miniflare"; const mf = new Miniflare({ scriptPath: "worker.js", log: new Log(LogLevel.DEBUG), // Enable debug messages }); ```

Miniflare constructor options reference

Miniflare constructor accepts these options: **Logging**: `log` (Log instance) **Script**: `script` (string), `scriptPath` (file path) - one required **Modules**: `modules` (boolean), `modulesRules` (array of rule objects) **Compatibility**: `compatibilityDate` (string), `compatibilityFlags` (array) **Routing**: `upstream` (URL string), `workers` (array of worker objects), `name` (string), `routes` (array) **HTTP Server**: `host` (string, default "127.0.0.1"), `port` (number, default 8787), `https` (boolean), `httpsKey` (string), `httpsKeyPath` (string), `httpsCert` (string), `httpsCertPath` (string), `cf` (boolean or string), `liveReload` (boolean) **KV**: `kvNamespaces` (array), `kvPersist` (path string) **R2**: `r2Buckets` (array), `r2Persist` (path string) **Durable Objects**: `durableObjects` (object), `durableObjectsPersist` (path string) **Cache**: `cache` (boolean, default true), `cachePersist` (path string), `cacheWarnUsage` (boolean) **Sites**: `sitePath` (path string), `siteInclude` (glob array), `siteExclude` (glob array) **Bindings**: `bindings` (object), `wasmBindings` (object), `textBlobBindings` (object), `dataBlobBindings` (object)

Miniflare dispatchFetch method

Dispatch a fetch event to a worker without making actual HTTP requests: ```js const res = await mf.dispatchFetch("http://localhost:8787/", { headers: { Authorization: "Bearer ..." }, }); const text = await res.text(); ```

Miniflare getBindings method

Get bindings (KV/Durable Object namespaces, variables, etc) from an instance: ```js const bindings = await mf.getBindings(); ```

Miniflare multiple workers configuration

Configure multiple named workers in a single Miniflare instance using the `workers` option. Each worker object can have its own `name`, `kvNamespaces`, `serviceBindings`, `modules`, and `script`.

Miniflare: Configure Durable Objects in environment

Specify Durable Objects to add to a Miniflare environment using the durableObjects option. The durableObjects object maps binding names to class names exported from the main script. Example: durableObjects: { OBJECT1: "Object1" } where Object1 is exported from the script.

Miniflare: Durable Object persistence options

By default, Durable Object data in Miniflare is stored in memory and persists between reloads but not across different Miniflare instances. Set durableObjectsPersist: true to enable persistence to the file system (defaults to ./.mf/do directory), or durableObjectsPersist: "./custom/path" to specify a custom path.

Miniflare: Access Durable Objects outside workers using getDurableObjectNamespace

Use the getDurableObjectNamespace(bindingName) method to obtain a namespace for a Durable Object binding defined in Miniflare. Call getByName(name) on the returned namespace to get a stub, then call fetch() on the stub to make requests to the Durable Object from outside a worker for testing purposes.

Miniflare: Durable Objects from other scripts using script_name

Miniflare supports the script_name option for accessing Durable Objects exported by other scripts. This requires mounting the other worker as described in the Multiple Workers documentation.

Miniflare: Test Durable Object with getDurableObjectNamespace example

Example showing how to use getDurableObjectNamespace to test Durable Objects. Create a Miniflare instance with a TestObject class, call mf.getDurableObjectNamespace("TEST_OBJECT") to get the namespace, then stub.fetch() to make requests to the object outside a worker context.

Miniflare storage simulators overview

Miniflare provides local storage simulators for Workers bindings including KV, R2, and D1. These simulators allow developers to configure and manage local storage during testing and development.

Miniflare storage configuration scope

Miniflare storage simulators are organized in the /storage directory with separate configuration sections for different binding types: KV, R2, and D1.

Using create-cloudflare CLI to create Workers project

Create a new Cloudflare Workers project using: npm create cloudflare@latest -- <project-name>. This initializes a project with the default Hello World template. The entry point is index.js which exports a default handler with the fetch method.

Create new Workers project with create-cloudflare

Use the create-cloudflare CLI tool to generate a new Cloudflare Workers project. Run: npm create cloudflare@latest -- qr-code-generator (or equivalent with yarn/pnpm). The CLI will prompt you to select 'Worker only' as the type and 'JavaScript' as the language.

Entry point to Workers application

In a newly created Workers project, index.js represents the entry point to the Cloudflare Workers application. All Workers applications start by listening for fetch events.

Authenticate to Turso CLI with GitHub

Run 'turso auth login' to authenticate to Turso using your GitHub account. This opens a browser window for you to sign in and grant the Turso application permission to use your account.

.dev.vars file for local Turso database development

Create a .dev.vars file in your project root with the structure LIBSQL_DB_AUTH_TOKEN="<YOUR_AUTH_TOKEN>" to provide the authentication token for local development. Do not commit this file to source control; add .dev.vars to .gitignore.

Get Turso database URL with CLI command

To retrieve the connection URL for your Turso database, run 'turso db show <DATABASE_NAME> --url'. This returns the libsql:// format URL needed for the LIBSQL_DB_URL environment variable.

Run Worker locally with wrangler dev

Execute 'npx wrangler dev' to run a local instance of your Worker on your machine. The command starts a web server accessible at http://127.0.0.1:8787 by default, and displays the available bindings and local addresses.

Create Turso database with CLI

Run 'turso db create <DATABASE_NAME>' to create a new Turso database. Turso automatically selects a location closest to you. The command displays progress and confirms creation with the database name and location.

Connect to Turso database shell

Run 'turso db shell <DATABASE_NAME>' to connect directly to your Turso database and execute SQL commands interactively. Exit the shell by typing .quit.

Destroy Turso database with CLI

Run 'turso db destroy <DATABASE_NAME>' to delete a Turso database.

Create Hono TypeScript project

Use `c3` CLI to scaffold a new Cloudflare Workers project: `npm create cloudflare@latest finetune-chatgpt-model`. Then select 'Worker only' and 'TypeScript' language options.

Worker entry point location

The entry point to a Cloudflare Workers application is located at `src/index.js` by default. This file contains the worker handler and is where most configuration for the worker is done.

Create a Worker project with npm create cloudflare

Run `npm create cloudflare@latest` to create a new Worker project. The command accepts a project name as an argument, for example `npm create cloudflare@latest github-twilio-notifications`. After running the command, select "Worker only" and "JavaScript" for the project type and language.

Node.js version requirement for Workers

Wrangler requires Node.js version 16.17.0 or later. Use a Node version manager like Volta or nvm to manage Node.js versions and avoid permission issues.

Store Postmark API token in .dev.vars for local development

For local development, store the Postmark API token in a .dev.vars file which works like a .env file. The file should contain POSTMARK_API_TOKEN=your_postmark_api_token_here. This allows local testing without hardcoding secrets.

Create a hello-world Worker project with C3

Use npm create cloudflare@latest to scaffold a new Worker project. For faster setup, use: npm create cloudflare@latest email-with-resend -- --type=hello-world --ts=false --git=true --deploy=false

Test Worker locally before deployment

Run npm start to test a Worker locally. This starts a development server accessible at http://localhost:8787/ in a browser.

Vite plugin development workflow npm scripts

The package.json scripts are: "dev": "vite dev" for development, "build": "vite build" for building, "preview": "npm run build && vite preview" for previewing, and "deploy": "npm run build && wrangler deploy" for deployment.

Give your agent this brain