valfz

Workers from first principles

A first Worker

Create the course project with cf init, read every generated file, write a fetch handler and run it locally with cf dev.

lesson
02 of 08
read
8 min

This lesson creates the project you will extend for the rest of the course. cf init generates eleven files, and each is explained here because later lessons edit most of them. By the end you will have replaced the generated handler with your own, run it in the Workers runtime on your machine, and updated the generated test to match.

Create the project

cf is Cloudflare’s command-line tool for account resources and for Workers projects. It is a release candidate at the time of writing, so pin the version:

pnpm dlx cf@1.0.0-rc.6 init shortlinks --package-manager pnpm
cd shortlinks
...
devDependencies:
+ @cloudflare/vite-plugin 2.0.0-rc.6
+ @cloudflare/vitest-plugin 1.10.0
+ cf 1.0.0-rc.6
+ typescript 7.0.2
+ vite <- @voidzero-dev/vite-plus-core 1.4.0
+ vite-plus 1.4.0
+ vitest 5.0.5
...

cf init created the directory, installed dependencies and generated types. The directory argument and --package-manager answer the two questions it would otherwise ask.

cf is now a development dependency of the project, so pnpm exec cf runs the pinned copy. The course writes every command that way. With npm the equivalent is npx cf. A globally installed cf also works, since inside a project it defers to the project’s copy. Wrangler is not installed: the project is configured through cloudflare.config.ts and built by the Cloudflare Vite plugin.

What was generated

.cloudflare/types/index.d.ts   generated binding and runtime types
.gitignore
cloudflare.config.ts           the Worker's configuration
package.json
pnpm-lock.yaml
pnpm-workspace.yaml            approves install scripts for esbuild and workerd
src/index.ts                   the Worker
test/index.test.ts             one test that runs inside the Workers runtime
tsconfig.json
vite.config.ts                 registers the Cloudflare Vite plugin
vitest.config.ts               registers the Cloudflare test plugin

Two tools are at work. cf does not bundle or serve anything itself. It hands dev and build to Vite+, installed as vite-plus with the binary vp, and the cloudflare() plugin in vite.config.ts makes Vite run your code in workerd during development and emit a deployable bundle at build time. The first line cf dev prints shows the handoff: it delegates to node_modules/vite-plus/bin/vp.

.cloudflare/ is the tools’ working directory. It holds generated types now, and it will hold local data and build output later. The generated .gitignore excludes it.

The scripts in package.json wrap the same commands. pnpm test runs vp test, and pnpm check runs cf workers types && vp check, which regenerates types and then checks formatting, lint rules and types.

The configuration file

cloudflare.config.ts
import { bindings, defineConfig } from "cf/config";
import * as entrypoint from "./src/index.ts" with { type: "cf-worker" };

export default defineConfig({
	worker: {
		name: "shortlinks",
		compatibilityDate: "2026-11-23",
		entrypoint,
		env: {
			WORLD: bindings.text("World"),
		},
	},
});

name is the Worker’s name in your account and part of its workers.dev hostname once deployed.

compatibilityDate pins runtime behavior. Cloudflare updates the runtime continuously, and changes that could break existing code only take effect for Workers whose compatibility date is on or after the change. Your Worker keeps the behavior of its date until you raise it on purpose. cf init writes a recent date that ships with the CLI. The compatibility dates page has the details.

entrypoint is the Worker module. The import attribute with { type: "cf-worker" } tells cf to read the module’s path without executing your code, and it lets TypeScript see the module’s exports.

env declares bindings, the values and resources your code receives at runtime. Lesson 4 replaces WORLD with real ones.

The file is TypeScript, so a misspelled field is an error before anything runs. The exercises have you trigger one. The full list of fields is in the configuration reference.

The fetch handler

cf init generated this Worker:

src/index.ts
import { env } from "cloudflare:workers";

export default {
	fetch() {
		return new Response(`Hello ${env.WORLD}!`);
	},
} satisfies ExportedHandler;

A Worker is an ES module whose default export is an object of event handlers. fetch handles HTTP requests. Other keys, such as scheduled for cron triggers, handle other kinds of events. The full signature is fetch(request, env, ctx). request is a standard Request. env is the object holding your bindings. ctx carries waitUntil(), which lesson 6 uses.

The template reads its binding through import { env } from "cloudflare:workers", which returns the same object from any module. This course takes env as the handler’s parameter and passes it down instead. A function’s dependencies are then visible in its signature, and a test can hand in a different value.

Replace the file with a handler that echoes the request line:

src/index.ts
export default {
	fetch(request): Response {
		const url = new URL(request.url);
		return new Response(`${request.method} ${url.pathname}\n`);
	},
} satisfies ExportedHandler<Env>;

satisfies ExportedHandler<Env> checks the object against the runtime’s handler types and infers the parameter types, which is why request needs no annotation. Env is the generated interface that describes your bindings. Trailing parameters you do not use can be left out, and the linter flags unused ones.

Run it

pnpm exec cf dev --port 8791

The server prints its local URL, http://localhost:8791/. Without --port it uses Vite’s default, 5173. The course pins 8791 so that the URLs in the text match your terminal. Arguments that cf dev does not recognize are forwarded to the dev server.

In a second terminal:

curl http://localhost:8791/some/path
curl -X POST http://localhost:8791/api/links
GET /some/path
POST /api/links

The handler runs inside workerd, the same runtime that serves production traffic, so Request, Response, crypto and the rest behave as they will when deployed. The exception is the startup phase described in lesson 1, which the dev server does not reproduce.

Change the response text and save. The dev server logs hmr update and the next request runs the new code. There is no restart step.

The dev server also hosts the Local Explorer at http://localhost:8791/cdn-cgi/local/explorer, a page for inspecting local data and logs. It becomes useful once the project stores something.

Keep the test passing

cf init wrote a test that asserts the greeting you have removed. Update it to describe the new behavior:

test/index.test.ts
import { SELF } from "cloudflare:test";
import { expect, it } from "vite-plus/test";

it("echoes the method and path", async () => {
	const response = await SELF.fetch("https://example.com/some/path");
	expect(response.status).toBe(200);
	expect(await response.text()).toBe("GET /some/path\n");
});
pnpm test
...
 Test Files  1 passed (1)
      Tests  1 passed (1)
...

The test also runs inside the Workers runtime. SELF.fetch() calls your Worker’s fetch handler directly, with no network involved, so the hostname in the URL is arbitrary. Lesson 8 builds a proper suite. Until then, this one test is updated whenever the behavior it checks changes, so that pnpm test and pnpm check pass at the end of every lesson:

pnpm check
...
pass: All 8 files are correctly formatted (190ms, 10 threads)
pass: Found no warnings, lint errors, or type errors in 5 files (770ms, 10 threads)

Lesson 3 replaces the echo with real routes: create a link, look it up, follow it.

Exercises

  1. Return JSON instead of text: the method, the path, and the query string as an object. For curl 'http://localhost:8791/a?x=1&y=2' a correct response is {"method":"GET","path":"/a","query":{"x":"1","y":"2"}} with the header content-type: application/json. Restore the echo handler afterwards, since the test depends on it.
  2. Add a second test that sends a POST to /x and expects the body POST /x\n. pnpm test should report two passed tests.
  3. Break the configuration on purpose: rename compatibilityDate to compatibilityDat and run pnpm check. The command should stop in cf workers types with Invalid cloudflare.config.ts and name the unrecognized key. Undo the change.

keyboard

h
home
w c a
writing, courses, about
n p
next and previous lesson
j k
scroll down and up
g G
top and bottom of the page
t
switch light and dark
?
this help

shortcuts are