Loading source
Pulling the file list, source metadata, and syntax-aware rendering for this listing.
Source from repo
Comprehensive Cloudflare platform skill covering Workers, D1, R2, KV, AI, Durable Objects, and security.
Files
Skill
Size
Entrypoint
Format
Open file
Syntax-highlighted preview of this file as included in the skill package.
references/miniflare/api.md
1# Programmatic API23## Miniflare Class45```typescript6class Miniflare {7constructor(options: MiniflareOptions);89// Lifecycle10ready: Promise<URL>; // Resolves when server ready, returns URL11dispose(): Promise<void>; // Cleanup resources12setOptions(options: MiniflareOptions): Promise<void>; // Reload config1314// Event dispatching15dispatchFetch(url: string | URL | Request, init?: RequestInit): Promise<Response>;16getWorker(name?: string): Promise<Worker>;1718// Bindings access19getBindings<Bindings = Record<string, unknown>>(name?: string): Promise<Bindings>;20getCf(name?: string): Promise<IncomingRequestCfProperties | undefined>;21getKVNamespace(name: string): Promise<KVNamespace>;22getR2Bucket(name: string): Promise<R2Bucket>;23getDurableObjectNamespace(name: string): Promise<DurableObjectNamespace>;24getDurableObjectStorage(id: DurableObjectId): Promise<DurableObjectStorage>;25getD1Database(name: string): Promise<D1Database>;26getCaches(): Promise<CacheStorage>;27getQueueProducer(name: string): Promise<QueueProducer>;2829// Debugging30getInspectorURL(): Promise<URL>; // Chrome DevTools inspector URL31}32```3334## Event Dispatching3536**Fetch (no HTTP server):**37```js38const res = await mf.dispatchFetch("http://localhost:8787/path", {39method: "POST",40headers: { "Authorization": "Bearer token" },41body: JSON.stringify({ data: "value" }),42});43```4445**Custom Host routing:**46```js47const res = await mf.dispatchFetch("http://localhost:8787/", {48headers: { "Host": "api.example.com" },49});50```5152**Scheduled:**53```js54const worker = await mf.getWorker();55const result = await worker.scheduled({ cron: "30 * * * *" });56// result: { outcome: "ok", noRetry: false }57```5859**Queue:**60```js61const worker = await mf.getWorker();62const result = await worker.queue("queue-name", [63{ id: "msg1", timestamp: new Date(), body: "data", attempts: 1 },64]);65// result: { outcome: "ok", retryAll: false, ackAll: false, ... }66```6768## Bindings Access6970**Environment variables:**71```js72// Basic usage73const bindings = await mf.getBindings();74console.log(bindings.SECRET_KEY);7576// With type safety (recommended):77interface Env {78SECRET_KEY: string;79API_URL: string;80KV: KVNamespace;81}82const env = await mf.getBindings<Env>();83env.SECRET_KEY; // string (typed!)84env.KV.get("key"); // KVNamespace methods available85```8687**Request.cf object:**88```js89const cf = await mf.getCf();90console.log(cf?.colo); // "DFW"91console.log(cf?.country); // "US"92```9394**KV:**95```js96const ns = await mf.getKVNamespace("TEST_NAMESPACE");97await ns.put("key", "value");98const value = await ns.get("key");99```100101**R2:**102```js103const bucket = await mf.getR2Bucket("BUCKET");104await bucket.put("file.txt", "content");105const object = await bucket.get("file.txt");106```107108**Durable Objects:**109```js110const ns = await mf.getDurableObjectNamespace("COUNTER");111const id = ns.idFromName("test");112const stub = ns.get(id);113const res = await stub.fetch("http://localhost/");114115// Access storage directly:116const storage = await mf.getDurableObjectStorage(id);117await storage.put("key", "value");118```119120**D1:**121```js122const db = await mf.getD1Database("DB");123await db.exec(`CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)`);124await db.prepare("INSERT INTO users (name) VALUES (?)").bind("Alice").run();125```126127**Cache:**128```js129const caches = await mf.getCaches();130const defaultCache = caches.default;131await defaultCache.put("http://example.com", new Response("cached"));132```133134**Queue producer:**135```js136const producer = await mf.getQueueProducer("QUEUE");137await producer.send({ body: "message data" });138```139140## Lifecycle141142**Reload:**143```js144await mf.setOptions({145scriptPath: "worker.js",146bindings: { VERSION: "2.0" },147});148```149150**Watch (manual):**151```js152import { watch } from "fs";153154const config = { scriptPath: "worker.js" };155const mf = new Miniflare(config);156157watch("worker.js", async () => {158console.log("Reloading...");159await mf.setOptions(config);160});161```162163**Cleanup:**164```js165await mf.dispose();166```167168## Debugging169170**Inspector URL for DevTools:**171```js172const url = await mf.getInspectorURL();173console.log(`DevTools: ${url}`);174// Open in Chrome DevTools for breakpoints, profiling175```176177**Wait for server ready:**178```js179const mf = new Miniflare({ scriptPath: "worker.js" });180const url = await mf.ready; // Promise<URL>181console.log(`Server running at ${url}`); // http://127.0.0.1:8787182183// Note: dispatchFetch() waits automatically, no need to await ready184const res = await mf.dispatchFetch("http://localhost/"); // Works immediately185```186187See [configuration.md](./configuration.md) for all constructor options.188