Bindings · Exercise 03
Swap resources
Run the same Worker code against a local simulation, the real KV namespace, and a second deployment with its own namespace.
Paste this into your agent
Copied! Now paste it into your agent. No agent yet? Here's how to get one.
Swap resources
Your Worker’s code never names the KV namespace it uses. It only knows env.NOTES. That means the same code can run against a local simulation, against the real namespace from your laptop, or as a second deployment with data of its own, and you’ll do all three without changing a line of it.
What you’ll build
- Your Worker in local dev, first against a simulated namespace, then against the real one with a remote binding
- A staging copy of the same Worker, deployed with its own namespace, side by side with the original
Writing to one won’t touch the other, and your agent checks that it doesn’t.
Prerequisites
- You’ve completed Call another Worker and still have that Worker on disk.
Where a binding points
Your code always says env.NOTES. What that points at depends on how you run it:
| How you run it | env.NOTES points at |
|---|---|
cf dev |
A local simulation on your machine |
cf dev, with remote on |
The real namespace in your account |
cf deploy |
The real namespace |
cf deploy --mode staging |
A second namespace, just for staging |
A remote binding is one setting on the binding. It needs the namespace’s ID:
cloudflare.config.tsNOTES: bindings.kv({ id: "<namespace id>", dev: { remote: true } }),
And since cloudflare.config.ts is TypeScript, it can take a function of the mode. Give staging its own Worker name, and it gets its own namespace:
cloudflare.config.tsexport default defineConfig(({ mode }) => ({
worker: {
name: mode === "staging" ? "my-worker-staging" : "my-worker",
// entrypoint, compatibilityDate, ...
env: {
NOTES: bindings.kv(),
},
},
}));
Why it matters
-
Your code can only reach a resource through a binding, so it can’t be hard-coded to production data. Any deployment of the same code can point somewhere else. In testing this is called dependency injection, and with bindings you get it without trying.
-
It works inside one Worker too. Say you combine two Workers into one, and both called their KV binding
KV. If each handler takesenvas a parameter, a router can give each one its own:export default { async fetch(request, env, ctx) { const { hostname } = new URL(request.url); if (hostname === "api.example.com") { return apiWorker.fetch(request, { KV: env.API_KV }, ctx); } return assetsWorker.fetch(request, { KV: env.ASSETS_KV }, ctx); }, }; -
There are two ways to get
env. Thecf inittemplate imports it (import { env } from "cloudflare:workers"), which is handy deep inside your code. Taking it as a parameter,fetch(request, env, ctx), is what makes the router above possible, and it’s what the docs recommend for testing.