KV foundations

Create and bind a namespace

Connect a named Worker binding to a KV namespace and keep local and production data targets explicit.

A KV namespace is the container that holds your keys. It lives in your Cloudflare account and has an ID. A binding is the name your Worker uses to reach it, like env.CONFIG.

Two different things. The namespace is the storage. The binding is the wire from your code to that storage, and you define it in wrangler.jsonc.

Create the namespace

Create separate local and production names deliberately:

npx wrangler kv namespace create FLAGS
npx wrangler kv key put --binding FLAGS checkout_enabled true --remote
npx wrangler kv key get --binding FLAGS checkout_enabled --remote

Inspect the generated namespace ID before adding it to configuration. Never use a production namespace as disposable local state. Delete the practice key when the exercise ends, but keep the namespace if another environment binding depends on it.

The first command prints the configuration you need:

🌀 Creating namespace with title "my-worker-FLAGS"
✨ Success!
Add the following to your configuration file in your kv_namespaces array:
{
  "kv_namespaces": [
    { "binding": "FLAGS", "id": "e29b263ab50e42ce9b637fa8370175e8" }
  ]
}

Paste that into wrangler.jsonc. The --binding FLAGS flag on the put and get commands reads the namespace ID from that file, so add the binding before running them.

Local and remote are different stores

wrangler dev uses local state by default. Every put your Worker makes during development lands in a file on your machine, not in Cloudflare. That’s a good default, because you can’t break production by accident.

The --remote flag is how you say “I mean the real one”. Without it, wrangler kv key put writes to the local store, and you’ll wonder why the dashboard shows nothing.

Verify the separation yourself. Write a key locally, then look for it remotely:

npx wrangler kv key put --binding FLAGS test_key hello
npx wrangler kv key get --binding FLAGS test_key --remote
# Value not found

That “not found” is the proof you want. Local writes stay local.

Keep the types in sync

Run npx wrangler types after adding or renaming a binding. It regenerates the Env type, so env.FLAGS autocompletes and a typo like env.FLAG fails at compile time instead of at runtime with Cannot read properties of undefined.

Try this: create a practice namespace, add the FLAGS binding, run wrangler types, and confirm a local write does not appear when you read with --remote.

Lesson completed