A Worker Handles Requests on Cloudflare's Network
A two-person team runs a bookmarking tool. Its /api/notes endpoint stores the latest note and rejects writes without a token. Today it runs on one small server in Virginia, so a reader in Singapore waits for a round trip. The first move toward the edge is one small program, not a cluster.
A Worker is that program: a JavaScript or TypeScript module that Cloudflare runs on its network in response to an HTTP request. Cloudflare terminates TLS, matches a route, and invokes your exported fetch handler inside a V8 isolate — a lightweight context the platform may reuse between requests. Keep request state in the request, not in a module-level variable. Cloudflare handles placement and scaling; you upload a version.
Wrangler is the CLI that builds and uploads those versions and reads your project configuration. The configuration file, wrangler.jsonc in a new project, declares the Worker's name, entry point, compatibility date, bindings, and routing. C3 scaffolds a project and installs Wrangler locally.
A binding is a capability the platform injects into your handler as a property of env. A KV namespace, a D1 database, and a secret — a binding for encrypted text — are all bindings. You do not construct them from a URL and an API key in code. You declare a name in configuration, and the runtime hands your code an object scoped to the resource that name points at. A secret is write-only from the operator's side: after upload, neither Wrangler nor the dashboard shows the value again, though your code can still read it as a string.
Think of a coffee chain. The recipe is your code, and Cloudflare places it in every branch. A binding is a pre-installed connection to a supplier that the branch already has; you do not tape a supplier password to the recipe. A secret is a sealed envelope in the till: the barista can open it while serving a customer, but head office cannot read it back.
Those definitions split responsibility three ways. Code decides what to do with a request. Configuration decides which capabilities exist and which hostnames reach the Worker. The platform decides where execution happens.
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
subgraph Outside["Outside Cloudflare"]
U[Browser request
https://notes.example.com/api/notes]
end
subgraph CF["Cloudflare network boundary"]
E[Edge
TLS termination and route match]
W[Worker isolate
fetch request, env, ctx]
B[(Binding: env.NOTES
KV namespace)]
S[[Secret: env.API_TOKEN
write-only to operators]]
end
O[Origin server]
U -->|HTTPS| E
E -->|route matches| W
W -->|read and write| B
W -->|read at runtime| S
W -->|fetch on a miss| O
E -.->|no route match| O
classDef primary fill:#132440,color:#ffffff,stroke:#0b172b;
classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a;
classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f;
classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420;
classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f;
class E,S,O primary;
class U,W secondary;
Figure 1 follows one request: the browser reaches the edge over HTTPS, the route selects this Worker, and the handler uses its KV and secret bindings. The origin appears only when the Worker calls fetch() or no route matches. Reaching the edge does not imply reaching your code.
Figure 2 shows the same path as layers. The dashed container is a boundary, not a network hop: the browser talks to the edge, the edge invokes the isolate, and the isolate reaches bindings through the runtime. On the platform the isolate is the unit of isolation; locally it is not a hardened sandbox.
C3, Wrangler, and the Local Development Loop
Three tools appear in the first hour and blur together. C3 creates the project. Wrangler runs it, types it, and deploys it. The configuration file is the contract both of them read.
Start with C3:
npm create cloudflare@latest -- notes-api
Choose Hello World example, then Worker only, then TypeScript. Decline the immediate deploy so you can inspect the files. C3 produces a small layout:
wrangler.jsonc— name,main,compatibility_date, bindings, routes, observability.src/index.ts— the exportedfetchhandler.package.jsonandtsconfig.json— scripts, a local Wrangler dependency, and TypeScript settings.worker-configuration.d.ts— generated bywrangler types; runtime types plus anEnvshape..dev.vars— local-only secrets that you create and gitignore.test/— an optional Vitest setup.
Wrangler supports JSONC and TOML; JSONC support arrived in Wrangler 3.91.0, and Cloudflare recommends it for new projects. The format is cosmetic; the content is the source of truth for what the next deploy creates.
compatibility_date selects runtime behaviors and defaults, so identical source can behave differently across dates. Move it forward deliberately, then test.
| Stage | What it decides, and what breaks if you skip it |
|---|---|
C3 (create-cloudflare) | Creates the layout and installs a project-local Wrangler. Hand-rolled projects usually forget worker-configuration.d.ts and fight the type checker. |
wrangler.jsonc | Declares name, entry point, compatibility date, bindings, and routes. A binding name that differs from the code produces undefined at request time. |
wrangler dev | Runs the handler in local workerd with simulated bindings on localhost:8787. Skipping it hides missing-secret and empty-KV paths until production. |
wrangler deploy | Bundles, uploads a version, and attaches routes and domains. Deploying from the wrong worktree or --env serves stale code under a fresh timestamp. |
wrangler rollback | Re-points traffic to an earlier version by creating a new deployment. It does not restore a deleted namespace, fix a secret, or undo DNS. |
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
A[C3 scaffold
wrangler.jsonc + src/index.ts] --> B[npx wrangler dev]
B --> C{Local workerd
bindings simulated}
C -->|binding name absent| D[env.NOTES is undefined
TypeError on first request]
C -->|secret absent from .dev.vars| E[env.API_TOKEN is undefined
handler returns 500]
C -->|request path OK| F[Test on localhost:8787]
F --> G[npx wrangler deploy]
G --> H{Version and route}
H -->|route or domain matches| I[Live traffic]
H -->|deployed from stale tree| J[Fresh version, old code]
J --> K[wrangler deployments list
compare returned version id]
K --> L[wrangler rollback VERSION_ID
or redeploy the right commit]
classDef primary fill:#132440,color:#ffffff,stroke:#0b172b;
classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a;
classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f;
classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420;
classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f;
class A,B,C,F,G,H,I,J,K,L secondary;
class D,E danger;
Figure 3 makes the failure branches explicit. A local run can fail before any network call, and a successful deploy can still serve the wrong artifact. Both are configuration-and-artifact problems, not mysterious platform behavior.
The panels split the work. The TypeScript panel is the handler; the Bash panel is the loop around it. These are the commands that check the artifact before it reaches traffic:
Local is simulated, not isolated
Local development runs a workerd process through Miniflare: bindings point at local simulations, so a KV namespace that is full in production is empty locally until you write to it. A remote: true binding connects one resource to the real thing while your code still runs locally. Miniflare is not a hardened sandbox; only run trusted code locally.
Bindings Grant Access to Resources
A binding is an object, not a URL. env.NOTES is an object the runtime constructs from the version's configuration; its methods map to the KV namespace whose ID you put in the config. You choose the name; the ID is the resource.
Names are not resources. Rename the binding without renaming the code, and the property becomes undefined. Point it at a different ID, and the same code reads different data with no type error at all.
Typed is not verified
wrangler types generates an Env interface from your configuration, and TypeScript checks every property you touch against it. The check is real, but it happens before deployment and is erased from the upload. Types prove internal consistency, not that the deployed version has the binding you expect.
Least privilege is per version. A binding is also a boundary: a Worker sees the resources configured for its version, not every namespace in the account. But a binding to a production namespace is production data, so environment-specific IDs matter more than environment-specific names. Staging and production can share one KV namespace if both configs contain the same id.
Routing is configuration too. Configuration decides which hostnames invoke this version.
| Target | What it is | What it needs |
|---|---|---|
workers.dev | The default when no route is configured. | Nothing beyond a deploy; the fastest way to verify one. |
| Route | Maps a pattern to a Worker in front of an existing origin. | A proxied DNS record. Without one, requests fail with ERR_NAME_NOT_RESOLVED and never reach the Worker. |
| Custom Domain | Sets custom_domain: true and makes the Worker the origin. | An active zone. Cloudflare creates the DNS record and certificate; it cannot attach to a hostname with an existing CNAME or a zone you do not own. See Custom Domains. |
Verify with what a user sees. A request to the route should return your JSON and the version ID; confirm the route or domain in the dashboard's Domains & Routes view. Cleanup is configuration work too: remove the routes entry and redeploy to detach it, or delete the Worker and its namespace, as the lab's cleanup step shows.
Missing secret, not an error
A missing secret does not throw. env.API_TOKEN is undefined, so a template literal becomes the literal string Bearer undefined, and a comparison against it can authenticate a request that sends exactly that header. Check for presence first, and declare required names in configuration so deploy fails before that version reaches traffic.
Secrets, Configuration, and Deployment Targets
A secret is a binding with a different operational contract. After upload, the value is encrypted and cannot be read back through Wrangler, the dashboard, or the API. wrangler secret list returns names, not values. Your handler still reads a plain string from env, so the code sees no difference between a secret and an ordinary environment variable.
"Write-only" is about operators, not your program. It stops a support engineer or a compromised dashboard session from copying the token. It does not stop your code from logging the token or returning it. Treat every console.log(env) as a potential leak.
The local and deployed paths are deliberately separate.
| Where the value lives | Source | Behavior |
|---|---|---|
| Local | .dev.vars or .env | Choose one; if both exist, .dev.vars wins. Add .dev.vars* and .env* to .gitignore before the first commit. |
| Deployed | wrangler secret put API_TOKEN | Prompts for the value and creates a new version, deploying it immediately. Rotation is a deployment event. |
| Deploy time | Optional secrets.required | Lists names that must exist, so wrangler deploy and wrangler versions upload fail clearly instead of shipping a version that returns 500s. Also drives type generation. |
A deployment target is a tuple, not a URL: a Worker name, a version, bindings, secrets, and routes. wrangler deploy uses the top-level configuration; the staging variant uses an env.staging block, which needs its own name and binding IDs. Secrets are non-inheritable, so a top-level secret is not automatically present on staging.
New deployment, old code. A composite scenario, not a measured incident: a team fixes a bug and deploys from a worktree two commits behind. The deploy succeeds, the health check returns 200, and the bug remains. The deployment is new and the code is old, but the timestamp looks right, which is why they trust it. The handler's version field is the discriminator, so they redeploy from the correct commit rather than rolling back, which would go further into the past.
Some failures deploy cleanly. A missing binding fails on the first request with a TypeError reading get of undefined. A wrong secret name can produce a 401 from an upstream API, and a stale route can leave an old Worker serving a hostname while the new version sits healthy on workers.dev.
Rollback restores a version, not the outside world
wrangler rollback re-points traffic by creating a new deployment: with no version ID it selects the version before the latest; with an ID it selects that version. You can roll back only to the 100 most recently published versions, and not when a binding's resource was deleted or modified between the two. It cannot restore a namespace, fix a secret, or undo DNS.
A token in vars is already leaked
A token pasted into vars is plaintext in the configuration file, visible in the dashboard, and readable by anyone with repository access. Deleting the commit does not un-leak it. Rotate first, assume the value is compromised, move it to wrangler secret put, then clean the config and history.
Figure 4 contrasts the two paths. The deploy arrow carries code and configuration but not .dev.vars. The leak branch is separate and entirely avoidable: vars is for non-sensitive values, and the config file is exactly the thing that travels with every deploy and every clone.
Build a Small JSON Endpoint With One Binding
This exercise builds a read/write JSON endpoint backed by one KV namespace and one secret, using only resources available on the Workers Free plan.
Build a Small JSON Endpoint With One Binding
Status: design-only — not executed for this draft. The commands follow current documentation, but no measurement was taken. Expected observations are predictions from the handler's control flow, not recorded results.
Prerequisites. A Cloudflare account, a supported Node.js release, npm, a terminal, and npx wrangler whoami showing the intended account. No paid plan is required. Use a unique name such as notes-lab-<initials> and a disposable token, never a real production credential.
Inputs. One KV namespace with binding NOTES; one secret named API_TOKEN; the handler from the widget; a local .dev.vars.
- Create the project with C3, choosing Hello World, Worker only, TypeScript, and no immediate deploy.
- Run
npx wrangler kv namespace create NOTES. Copy the printed ID into thekv_namespacesentry inwrangler.jsonc; keep the binding name exactlyNOTES. - Add
version_metadatawith bindingCF_VERSION_METADATA, so the response can prove which version answered. - Replace
src/index.tswith the widget handler. Runnpx wrangler typessoKVNamespace,WorkerVersionMetadata, andEnvresolve. - Create
.dev.varscontainingAPI_TOKEN="lab-token-change-me", and add.dev.vars*and.env*to.gitignore. - Run
npx wrangler dev, then work through the checks in the table. - Deploy with
npx wrangler deployand note theworkers.devURL. Runnpx wrangler secret put API_TOKEN, paste the lab token, then repeat the deployed checks. - Compare the newest version ID from
npx wrangler deployments listwith theversionreturned byGET. - Optional custom domain. In a zone you control, add
"routes": [{ "pattern": "notes-lab.example.com", "custom_domain": true }], deploy, and request the hostname. Then remove the entry and redeploy.
| Check | Expected observation | What it proves |
|---|---|---|
GET /api/notes before any write | 200 with {"note":null,"version":"..."} | Route, handler, KV binding, version metadata |
POST with the lab token | 201 and a note object | Secret present; auth path works |
POST with a wrong token | 401 | Comparison runs after the presence check |
Config binding renamed to NOTES_DB, code unchanged, after restart | 500; logs show a TypeError reading get of undefined | The binding name, not the resource ID, resolves env |
.dev.vars key renamed to API_TOKEN_TYPO, after restart | 500 server_misconfigured | Presence check runs before the comparison |
Deployed POST before the secret is set | 500 server_misconfigured | Local secrets are not uploaded |
Deployed POST after the secret is set | 201 | secret put deploys a new version |
npx wrangler secret list | API_TOKEN and no value | The value is write-only |
Deployment list vs response version | The same ID | No stale worktree |
Cost dimensions. On the Free plan, Workers includes 100,000 requests per day with 10 ms of CPU time per invocation. KV includes 100,000 reads, 1,000 writes, and 1,000 deletes per day, with 1 GB stored. A few dozen curl calls are far below those allowances, but limits reset daily at 00:00 UTC. Confirm current pricing before relying on it.
Cleanup. Run npx wrangler delete for the Worker and its routes, npx wrangler kv namespace delete --namespace-id <id> for the namespace, and delete .dev.vars plus .wrangler/state locally. Confirm any custom domain is detached.
The failure checks are the point. Neither produces a build error, and neither is caught by TypeScript. Both are caught by running the request path and reading the response and logs.
Verify Local and Deployed Behavior Without Exposing Secrets
Verification date: 2026-11-04. Basis: official Cloudflare documentation reviewed on that date, plus the handler's control flow. Execution status: design-only. No Wrangler command was run, so treat these as documented expectations, not hosted validation. Record npx wrangler --version, the Node.js version, the compatibility_date, and the account plan.
Pass evidence. A correct run shows:
GET /api/notesreturns200,content-type: application/json; charset=utf-8, anullnote before the first write, and a non-emptyversion.POSTwithout a token returns401; with the correct token it returns201and a note object.- Unknown paths return
404; unsupported methods return405. wrangler deployments listmatches the response'sversion.wrangler secret listshowsAPI_TOKENand no value.- A custom domain or route resolves to the same version as
workers.dev.
Fail signatures. These are diagnostic:
TypeError: Cannot read properties of undefined (reading 'get')meansenv.NOTESis absent. Check the binding name and redeploy.500 server_misconfiguredmeansenv.API_TOKENis absent. Check the secret name and environment.- Local
201but deployed401means the deployed secret differs, or the code reads another name. - A new deployment timestamp with an old
versionmeans a stale worktree or the wrong--env. ERR_NAME_NOT_RESOLVEDmeans a route without a proxied DNS record, so the request never reaches the Worker.
Self-check. Answer before reading the explanations.
- Why can
wrangler deploysucceed with a missing binding? Deploy uploads code and configuration; it does not execute every request path.env.NOTESis resolved at request time, and theEnvcheck was erased at build time. - What differs between
.dev.varsand the deployed secret?.dev.varsis local plaintext read bywrangler devand never uploaded. The deployed secret is encrypted, attached to a version, and readable by the Worker. The code sees the same string in both cases, which is why a name mismatch is easy to miss. - What does rollback not fix? It does not restore a deleted namespace, correct a secret, repair DNS, or detach a route changed outside the version. It re-points traffic to an earlier version, subject to the 100-version and binding-integrity limits.
- Why is
varswrong for a token?varsis plaintext in a file that is committed, cloned, and deployed. Secrets are encrypted and not readable back through Wrangler or the dashboard.
Unresolved limitations. The exercise was not executed, so no latency, error rate, or cost measurement is claimed. Local KV simulation does not reproduce global replication: KV is eventually consistent, and changes may take up to 60 seconds or more to appear elsewhere. Custom Domains depend on zone status and entitlements. Secret rotation deserves a separate test because wrangler secret put creates and deploys a version. Plan limits and prices change; verify them at writing time.
Authoritative references.
- Cloudflare Workers
- Get started with the CLI
- Wrangler configuration
- Wrangler commands
- Secrets
- Local development
- Rollbacks
- Custom Domains
- Routes
- Version metadata binding
- Workers pricing
- KV pricing
- Workers best practices
Next in the Series
In Write for the Workers Runtime, we'll explore Understand Web APIs, compatibility dates, and execution limits.