workerd Runtime
Cloudflare's `workerd` is an open-source JavaScript/WebAssembly server runtime, built on the same core technology that powers Cloudflare Workers. It provides a local execution environment for developing and testing serverless applications that replicate the Cloudflare Workers platform. The current stable version, `v1.20260421.1`, follows a `v1.YYYYMMDD.X` daily release cadence, reflecting continuous integration and frequent updates with features and bug fixes. Key differentiators include its high compatibility with the Cloudflare Workers ecosystem, enabling seamless local development and deployment, and its foundation on the proven, high-performance Cloudflare infrastructure. Unlike traditional Node.js runtimes, `workerd` is designed for a secure, isolated, and highly concurrent serverless model, with built-in support for web standards like `fetch` and `Durable Objects`.
Common errors
-
Error: workerd.capnp:1:0: Parse error: Expected 'using' or 'const' after top-level statement.
cause The Cap'n Proto configuration file (`.capnp`) has a syntax error or is malformed, preventing `workerd` from parsing its configuration.fixVerify the syntax of your `workerd.capnp` file. Ensure `using` and `const` statements are correctly formed and that there are no misplaced characters or incorrect indentation. -
Error: Bundle 'my-worker-bundle' not found. This bundle must be defined in the bundles list.
cause The worker configuration within `workerd.capnp` refers to a bundle name that is not defined in the `bundles` list, or the path to the worker script embedded in the bundle is incorrect.fixCheck that the `name` field in your `bundles` array matches the `serviceWorkerScript` reference in your `worker` definition within `workerd.capnp`. Also, ensure the `content = embed "worker.js"` path correctly points to your worker script. -
Error: Service 'main' failed to start: Error: worker initialization failed: TypeError: fetch is not a function
cause This error typically indicates that the worker script contains invalid JavaScript syntax, a runtime error, or attempts to access APIs not available in the `workerd` environment or within the worker's current scope.fixReview your `worker.js` (or `worker.ts`) file for syntax errors or logical issues. Ensure all used APIs (like `fetch`) are correctly called within the Worker environment's context (e.g., within the `fetch` handler) and are supported by `workerd` or enabled by `compatibilityFlags`.
Warnings
- breaking The `ByobBuffer` API has undergone a renaming of its `minBytes` property to `minElements`. Code interacting with `ByobBuffer` for BYOB (Bring-Your-Own-Buffer) streams will need to update to use the new property name.
- deprecated APIs for Durable Object replication, `ensureReplicas()` and `disableReplicas()`, have been deprecated. They are replaced by a new, more flexible `configureReadReplication()` API.
- gotcha `workerd` uses Cap'n Proto (`.capnp` files) for its configuration. This is a powerful, schema-driven serialization format but can be unfamiliar to developers primarily working with JSON or YAML. Incorrect syntax or schema violations in `.capnp` files will prevent `workerd` from starting.
- gotcha The `workerd` package follows a rapid, daily release cadence (e.g., `v1.YYYYMMDD.X`). While this ensures quick bug fixes and feature rollouts, it means local installations can become outdated very quickly, and specific behaviors or APIs might evolve rapidly between minor daily versions. This necessitates frequent updates and awareness of changelogs.
Install
-
npm install workerd -
yarn add workerd -
pnpm add workerd
Imports
- (Global types for Workers environment)
/// <reference types="workerd" />
- workerd.unsafe
import { unsafe } from 'workerd';import { workerd } from 'workerd'; const { unsafe } = workerd; - workerd
import { workerd } from 'workerd';import type { workerd } from 'workerd';
Quickstart
/*
1. Create your worker script: worker.js
Save this content to a file named `worker.js` in your project directory.
*/
export default {
async fetch(request) {
const url = new URL(request.url);
if (url.pathname === '/greet') {
const name = url.searchParams.get('name') || 'World';
return new Response(`Hello, ${name} from workerd!`, {
headers: { 'Content-Type': 'text/plain' },
status: 200
});
}
return new Response('Not Found. Try visiting /greet?name=Alice', { status: 404 });
}
};
/*
2. Create your workerd configuration file: workerd.capnp
This file tells the `workerd` runtime how to load and serve your worker.
Save this content to a file named `workerd.capnp` in the same directory.
*/
// using Workerd = /capnp/workerd.capnp;
//
// const config :Workerd.Config = (
// services = [
// (name = "main", worker = .worker),
// ],
// bundles = [
// (name = "my-worker-bundle", content = embed "worker.js"), // Reference your `worker.js` file
// ],
// sockets = [
// (name = "http", address = "0.0.0.0:8080", service = "main"), // workerd listens on port 8080
// ]
// );
//
// const worker :Workerd.Worker = (
// serviceWorkerScript = .myWorkerBundle,
// compatibilityDate = "2023-01-01", // Required by Cloudflare Workers for consistent behavior
// compatibilityFlags = ["nodejs_compat"], // Example: Enable Node.js compatibility features
// );
/*
3. Install workerd and run your worker
First, ensure you have Node.js and npm/npx installed.
Then, in your terminal, navigate to your project directory and run:
npm install workerd
npx workerd serve workerd.capnp
After running, open your web browser and visit:
- http://localhost:8080/greet (Expected: "Hello, World from workerd!")
- http://localhost:8080/greet?name=Alice (Expected: "Hello, Alice from workerd!")
*/