Skip to content
Latchkey

Cloudflare Workers "binding is not defined" in CI

The Worker references a binding (KV namespace, R2 bucket, D1 database, or var) that is not declared in wrangler.toml, so it is undefined at runtime. The deploy may succeed but the Worker errors when the binding is used.

What this error means

After deploy, the Worker throws "ReferenceError: MY_KV is not defined" or "env.MY_BUCKET is undefined" when handling a request.

Workers
Uncaught ReferenceError: MY_KV is not defined
  at fetch (worker.js:12:5)

Common causes

The binding is missing from wrangler.toml

The code uses env.MY_KV, but no matching kv_namespaces (or other binding) entry exists in the config, so it is undefined.

A binding defined in the wrong environment

The binding is declared under one [env.x] block but the deploy targets a different environment, so it is absent there.

How to fix it

Declare the binding in wrangler.toml

  1. Match each env.X reference in code to a binding entry.
  2. Add the kv_namespaces, r2_buckets, d1_databases, or vars entry.
  3. Redeploy so the binding is injected.
wrangler.toml
# wrangler.toml
kv_namespaces = [
  { binding = "MY_KV", id = "abc123..." }
]

Define the binding for the target environment

If you deploy with --env production, declare the binding under [env.production] as well, not only at the top level.

How to prevent it

  • Keep every env.X reference backed by a wrangler.toml binding.
  • Declare bindings per environment you deploy to.
  • Access bindings via the env argument, not globals.

Related guides

Tired of flaky CI? Latchkey auto-heals failed jobs and retries them for you. Start free →