cloudflare-workers-sdk
A comprehensive toolkit for developing, testing, and deploying serverless applications on Cloudflare's global edge network. The SDK includes command-line tools, local development simulators, build plu
Cloudflare Workers SDK
A comprehensive toolkit for developing, testing, and deploying serverless applications on Cloudflare's global edge network. The SDK includes command-line tools, local development simulators, build plugins, and testing integrations to help you build reliable Workers applications with modern JavaScript frameworks.
Quick References
| File | Purpose |
|---|---|
packages/wrangler/src/index.ts | Main Wrangler CLI entry point |
packages/miniflare/src/index.ts | Miniflare simulator main API |
packages/vite-plugin-cloudflare/src/index.ts | Vite plugin exports |
README.md | Project overview and getting started |
packages/wrangler/README.md | Wrangler CLI documentation |
Packages
| Package | npm name | Description |
|---|---|---|
packages/wrangler | wrangler | CLI tool for building and deploying Cloudflare Workers |
packages/create-cloudflare | create-cloudflare | Project scaffolding CLI (C3) for new applications |
packages/miniflare | miniflare | Local development simulator powered by workerd |
packages/vite-plugin-cloudflare | @cloudflare/vite-plugin | Vite plugin for Workers runtime integration |
packages/vitest-pool-workers | @cloudflare/vitest-pool-workers | Vitest testing integration for Workers |
packages/kv-asset-handler | @cloudflare/kv-asset-handler | KV-based static asset handling for Workers Sites |
packages/workers-utils | @cloudflare/workers-utils | Utility functions for common Worker operations |
When to Use
- Developing serverless applications that run at the edge with sub-millisecond latency
- Building APIs, web applications, or static sites that need global distribution
- Testing Workers locally with production-like runtime behavior
- Integrating Workers into modern build pipelines (Vite, Vitest)
- Deploying applications with zero configuration complexity
- Creating multi-worker architectures with service bindings and queues
- Implementing edge caching, KV storage, R2 object storage, and D1 databases
Installation
# Install Wrangler CLI
npm install -g wrangler
# Or create a new project with create-cloudflare
npm create cloudflare@latest my-app
# Install packages programmatically
npm install wrangler @cloudflare/vite-plugin
npm install -D miniflare @cloudflare/vitest-pool-workers
Best Practices
- Always use a configuration file - Define your Worker settings in
wrangler.json,wrangler.jsonc, orwrangler.tomlfor reproducible deployments - Test locally before deploying - Use
wrangler devorminiflareto verify functionality locally - Use environment-specific configs - Leverage the
envsections in your configuration to separate development, staging, and production settings - Maintain compatibility dates - Set
compatibility_dateto control which runtime features are available - Secure your secrets - Never commit secrets to version control; use
wrangler secret putor environment variables - Leverage bindings correctly - Use type-safe bindings for KV, R2, D1, Durable Objects, and services to access resources in your Worker
Common Patterns
Creating a new Worker project:
npx create cloudflare@latest my-app
cd my-app
npx wrangler dev
Local development with Wrangler:
# Start local development server
npx wrangler dev
# Deploy to production
npx wrangler deploy
# Deploy to a specific environment
npx wrangler deploy --env production
Using Wrangler programmatically in Node.js:
import { Miniflare } from "miniflare";
const mf = new Miniflare({
script: `
export default {
async fetch(request) {
return new Response("Hello from Workers!");
}
}
`,
});
const response = await mf.dispatchFetch("http://localhost/");
console.log(await response.text());
Vite integration for modern frameworks:
// vite.config.ts
import { defineConfig } from "vite";
import { cloudflare } from "@cloudflare/vite-plugin";
export default defineConfig({
plugins: [cloudflare()],
});
KV asset handling for static sites:
import { getAssetFromKV } from "@cloudflare/kv-asset-handler";
import manifestJSON from "__STATIC_CONTENT_MANIFEST";
const assetManifest = JSON.parse(manifestJSON);
export default {
async fetch(request, env, ctx) {
try {
return await getAssetFromKV(
{ request, waitUntil: (p) => ctx.waitUntil(p) },
{
ASSET_NAMESPACE: env.__STATIC_CONTENT,
ASSET_MANIFEST: assetManifest,
}
);
} catch (e) {
return new Response("Not found", { status: 404 });
}
},
};
Testing Workers with Vitest:
// vitest.config.ts
import { defineWorkersConfig } from "@cloudflare/vitest-pool-workers";
export default defineWorkersConfig({
workers: [
{
name: "worker",
serviceBindings: {
external: { external: { url: "https://example.com" } },
},
},
],
test: {
poolOptions: {
workers: {
useWebWorkers: false,
},
},
},
});
Configuring bindings in wrangler.json:
{
"$schema": "node_modules/wrangler/config-schema.json",
"name": "my-worker",
"main": "./src/index.ts",
"compatibility_date": "2024-01-01",
"vars": {
"API_KEY": "your-api-key"
},
"kv_namespaces": [
{
"binding": "YOUR_KV_NAMESPACE",
"id": "your-kv-id"
}
],
"r2_buckets": [
{
"binding": "YOUR_R2_BUCKET",
"bucket_name": "your-bucket-name"
}
],
"d1_databases": [
{
"binding": "DB",
"database_name": "your-database-name"
}
]
}
Miniflare for advanced testing scenarios:
import { Miniflare } from "miniflare";
const mf = new Miniflare({
modules: true,
script: "./src/index.js",
kvNamespaces: ["TEST_NAMESPACE"],
r2Buckets: ["TEST_BUCKET"],
kvPersist: true, // Persist KV data to disk
r2Persist: true, // Persist R2 data to disk
});
// Get KV namespace to manipulate in tests
const kv = await mf.getKVNamespace("TEST_NAMESPACE");
await kv.put("key", "value");
API Quick Reference
| Export | Type | Description |
|---|---|---|
wrangler (CLI) | Command | Deploy, develop, and manage Workers from the command line |
create-cloudflare | CLI | Scaffold new Cloudflare projects with templates |
Miniflare | Class | Local Workers simulator for testing and development |
getAssetFromKV | Function | Retrieve static assets from Workers KV |
serveSinglePageApp | Function | Route all requests to index.html for SPAs |
cloudflare() | Function | Vite plugin for Workers runtime integration |
defineWorkersConfig | Function | Configure Vitest test pool for Workers |
readConfig() | Function | Load and validate Wrangler configuration files |
mapRequestToAsset | Function | Map request URLs to KV asset keys |
Key Wrangler Commands
| Command | Purpose |
|---|---|
wrangler dev | Start local development server with live reload |
wrangler deploy | Deploy Worker to Cloudflare's network |
wrangler pages dev <dir> | Serve static assets locally with Functions |
wrangler secret put <key> | securely store environment variables |
wrangler tail | Stream real-time logs from deployed Worker |
wrangler init [name] | Initialize a new Worker project |
Configuration Core Options
| Option | Type | Description |
|---|---|---|
name | string | Unique identifier for your Worker |
main | string | Path to Worker entry point |
compatibility_date | string | Runtime feature compatibility (e.g., "2024-01-01") |
vars | object | Environment variables for your Worker |
env | object | Environment-specific configurations |
routes | string[] | URL patterns for routing requests |