workerd: "binding is not defined" for KV namespace in local dev
Fixes the KV ReferenceError that appears only in wrangler dev. This skill shows how to add the preview namespace ID to the kv_namespaces binding in wrangler.toml and restart dev so env.MY_KV is defined locally. Use it when KV works after deploy but throws 'binding is not defined' in local development.
Fix "binding is not defined" for KV namespace in local dev
TL;DR
Local dev binds the preview KV namespace, so your [[kv_namespaces]] entry needs a valid preview_id. Run wrangler kv namespace list, put the real preview namespace ID in the binding config, and fully restart wrangler dev. Without a preview_id there is nothing to attach locally, so env.MY_KV stays undefined.
Verbatim error
workerd: "binding is not defined" for KV namespace in local devSteps
- Run
npx wrangler kv namespace list. Expected: a JSON list with anidandtitlefor each namespace in your account. - In wrangler.toml, find your
[[kv_namespaces]]entry and set bothid(production) andpreview_id(preview) to real namespace IDs from that list. Expected: both fields present, no placeholder values. - Stop
wrangler devcompletely and start it again (a full restart, not hot reload). Expected: dev boots with no binding errors. - In the handler, reference
env.MY_KVexactly matching thebindingname in wrangler.toml. Expected: no ReferenceError when the code runs. - Smoke-test:
await env.MY_KV.put("ping", "1")thenawait env.MY_KV.get("ping"). Expected: the round-trip returns "1" locally.
Use this when
- "binding is not defined" appears only in
wrangler dev, never after deploy - KV works in production but
env.MY_KVis undefined locally - You recently added the KV binding and never set a
preview_id
Not for this skill when
- The binding is invalid in production too (the production
idis wrong or stale) - The namespace was deleted (recreate it and update both IDs)
- D1 or R2 bindings are missing (same shape of problem, different wrangler commands)
Variant phrasings
- kv namespace undefined wrangler dev
- env KV binding not found local
- miniflare kv binding missing
- ReferenceError: MY_KV is not defined workers dev
Why it happens
wrangler dev attaches preview resources, not production ones. A binding entry with only an id has nothing to bind locally, so the runtime leaves env.MY_KV undefined and throws a ReferenceError the moment your code touches it.
Edge cases
- A
preview_idpointing at a deleted namespace produces a different error at dev boot; re-list and fix it. - Local KV data does not persist across restarts unless you pass a persist directory to
wrangler dev. - Binding names are case-sensitive;
env.my_kvandenv.MY_KVare different bindings.
Provenance
Resolved from the public thread: https://vectle.com/posts/pstxTKCmsRgiuDvlVyBCfMFQ
Maintainer review
No maintainer verification is recorded for this version.
This records the version a maintainer checked. It does not assert that the version is the latest upstream release.