Wrangler exports a programmatic API that allows you to use it as a library in your Node.js applications. This is useful for building custom development tools, testing frameworks, and deployment pipelines.
Installation
Core Functions
startWorker()
Starts a local development server for a Worker.
import { startWorker } from "wrangler" ;
const worker = await startWorker ({
name: "my-worker" ,
entrypoint: "./src/index.ts" ,
compatibilityDate: "2024-01-01" ,
});
const response = await worker . fetch ( "/" );
console . log ( await response . text ());
await worker . dispose ();
options
StartDevWorkerInput
required
Configuration options for the dev server Show StartDevWorkerInput properties
The JavaScript or TypeScript entry-point of the worker. This is the main property of a Wrangler configuration file.
Path to the Wrangler configuration file
The compatibility date for the workerd runtime (e.g., “2024-01-01”)
Array of compatibility flags for the workerd runtime
Environment to use for operations and selecting .env files
Paths to .env files to load, relative to the project directory
Bindings available to the worker on the env object
{ type: "plain_text"; value: string } - Plain text variable
{ type: "json"; value: unknown } - JSON variable
{ type: "kv_namespace"; id: string } - KV namespace
{ type: "durable_object_namespace"; className: string; scriptName?: string } - Durable Object
{ type: "r2_bucket"; bucketName: string } - R2 bucket
{ type: "d1"; id: string } - D1 database
{ type: "service"; service: string; entrypoint?: string } - Service binding
{ type: "queue"; queueName: string } - Queue
Triggers that will cause the worker’s exported handlers to be called
HTTP routes (e.g., { type: "route"; pattern: "example.com/*" })
Custom domains
Options for the worker’s build step Whether to bundle the worker and its dependencies
Whether to minify the bundled worker
Replace global identifiers with constant expressions (e.g., { debug: 'true' })
Alias modules (e.g., { "@/utils": "./src/utils" })
Specifies types of modules matched by globs
Options for custom build steps Show Custom build options
Custom shell command to run before bundling
Files to watch for changes to trigger rebuilds
Options for the development preview environment
true or "minimal": Run in remote preview session
false: Run locally in workerd simulator
undefined: Run code locally, remote bindings remotely
Directory for persisting local storage (KV, DO, R2, D1, etc.)
dev.logLevel
'debug' | 'info' | 'log' | 'warn' | 'error' | 'none'
Controls which logs are displayed
Whether to restart the server on source/config file changes
Insert script tag in HTML responses to reload page on file changes
Local server configuration Inspector server configuration, or false to disable
The worker instance Promise that resolves when the worker is ready
Promise that resolves to the worker’s URL
Promise that resolves to the inspector URL
fetch
(request: Request) => Promise<Response>
Send an HTTP request to the worker
scheduled
(cron?: string) => Promise<void>
Trigger a scheduled event
queue
(queueName: string, messages: Message[]) => Promise<void>
Send messages to a queue consumer
setConfig
(config: StartDevWorkerOptions) => Promise<void>
Replace the entire worker configuration
patchConfig
(config: Partial<StartDevWorkerOptions>) => Promise<void>
Partially update the worker configuration
Stop the worker and clean up resources
Example Usage
import { startWorker } from "wrangler" ;
const worker = await startWorker ({
name: "my-api" ,
entrypoint: "./src/index.ts" ,
compatibilityDate: "2024-01-01" ,
bindings: {
DB: {
type: "d1" ,
id: "my-database" ,
},
MY_KV: {
type: "kv_namespace" ,
id: "my-kv-namespace" ,
},
},
dev: {
persist: ".wrangler/state" ,
server: {
port: 8787 ,
},
},
});
// Wait for worker to be ready
await worker . ready ;
// Make a request
const response = await worker . fetch ( "/api/users" );
console . log ( await response . json ());
// Trigger a scheduled event
await worker . scheduled ();
// Clean up
await worker . dispose ();
unstable_dev()
This API is experimental and may change in future releases.
Starts a Wrangler dev server for testing purposes.
import { unstable_dev } from "wrangler" ;
const worker = await unstable_dev ( "src/index.ts" , {
config: "wrangler.toml" ,
env: "staging" ,
local: true ,
});
const response = await worker . fetch ( "/" );
console . log ( response . status );
await worker . stop ();
Path to the worker script
Path to .toml configuration file
Enable persistence using default path (.wrangler/state)
Port the server is running on
Address the server is bound to
fetch
(input?: RequestInfo, init?: RequestInit) => Promise<Response>
Make a request to the worker
Wait until the server exits
Get proxy objects for Cloudflare platform bindings in Node.js.
import { getPlatformProxy } from "wrangler" ;
const { env , dispose } = await getPlatformProxy ({
configPath: "wrangler.toml" ,
});
// Use bindings
const value = await env . MY_KV . get ( "key" );
await dispose ();
Path to Wrangler config file. If not specified, searches from current directory upward.
persist
boolean | { path: string }
default: "true"
Whether and where to persist binding data. Defaults to .wrangler/state/v3.
Whether remote bindings should be enabled
Environment object containing Cloudflare bindings (KV, D1, R2, etc.)
cf
IncomingRequestCfProperties
Request.cf object with geolocation and other properties
Mock execution context with waitUntil() and passThroughOnException()
// Example: Use in a test framework
import { getPlatformProxy } from "wrangler" ;
import { describe , it , expect , beforeAll , afterAll } from "vitest" ;
let env , dispose ;
beforeAll ( async () => {
({ env , dispose } = await getPlatformProxy ());
});
afterAll ( async () => {
await dispose ();
});
it ( "should store and retrieve from KV" , async () => {
await env . MY_KV . put ( "test-key" , "test-value" );
const value = await env . MY_KV . get ( "test-key" );
expect ( value ). toBe ( "test-value" );
});
Configuration Utilities
unstable_readConfig()
Read and parse a Wrangler configuration file.
import { unstable_readConfig } from "wrangler" ;
const config = unstable_readConfig ({
config: "wrangler.toml" ,
env: "production" ,
});
console . log ( config . name ); // Worker name
console . log ( config . compatibility_date ); // Compatibility date
Parsed configuration object
unstable_getWorkerNameFromProject()
Get the worker name from a project directory.
import { unstable_getWorkerNameFromProject } from "wrangler" ;
const name = unstable_getWorkerNameFromProject ( "/path/to/project" );
console . log ( name ); // "my-worker"
Binding Utilities
convertConfigBindingsToStartWorkerBindings()
Convert Wrangler config bindings to the format expected by startWorker().
import {
unstable_readConfig ,
convertConfigBindingsToStartWorkerBindings
} from "wrangler" ;
const config = unstable_readConfig ({ config: "wrangler.toml" });
const bindings = convertConfigBindingsToStartWorkerBindings ( config );
Event Types
The Worker object emits events during its lifecycle.
ErrorEvent
Emitted when an error occurs.
type ErrorEvent = {
type : "error" ;
error : SerializedError ;
};
ConfigUpdateEvent
Emitted when configuration changes.
type ConfigUpdateEvent = {
type : "config-update" ;
config : StartDevWorkerOptions ;
};
BundleStartEvent / BundleCompleteEvent
Emitted during bundling.
type BundleStartEvent = {
type : "bundle-start" ;
};
type BundleCompleteEvent = {
type : "bundle-complete" ;
bundle : Bundle ;
};
ReadyEvent
Emitted when the worker is ready.
type ReadyEvent = {
type : "ready" ;
url : URL ;
inspectorUrl ?: URL ;
};
Pages API
unstable_pages.deploy()
Deploy a Pages project programmatically.
import { unstable_pages } from "wrangler" ;
const result = await unstable_pages . deploy ({
directory: "./dist" ,
projectName: "my-site" ,
accountId: "your-account-id" ,
});
console . log ( `Deployed to: ${ result . url } ` );
mTLS Certificate Management
uploadMTlsCertificate()
Upload an mTLS certificate from a buffer.
import { uploadMTlsCertificate } from "wrangler" ;
import fs from "fs" ;
const cert = fs . readFileSync ( "cert.pem" );
const key = fs . readFileSync ( "key.pem" );
const result = await uploadMTlsCertificate (
"my-cert" ,
cert ,
key ,
"account-id"
);
listMTlsCertificates()
List all mTLS certificates.
import { listMTlsCertificates } from "wrangler" ;
const certs = await listMTlsCertificates ( "account-id" );
deleteMTlsCertificate()
Delete an mTLS certificate.
import { deleteMTlsCertificate } from "wrangler" ;
await deleteMTlsCertificate ( "cert-id" , "account-id" );
Type Definitions
All types are exported from the main package:
import type {
Worker ,
StartDevWorkerInput ,
StartDevWorkerOptions ,
Binding ,
Trigger ,
GetPlatformProxyOptions ,
PlatformProxy ,
} from "wrangler" ;