Confused about namespace binding in queue worker


I’ve set up a Worker to consume a Queue and write some data to a KV. I’ve configured the KV in the wrangler.toml file -

name = "worker-name"
main = "src/index.ts"
compatibility_date = "2023-05-09"
usage_model = "bundled"

kv_namespaces = [
{ binding = "SESSIONS_KV", id = "YYYYYYYYYY" }
queues.consumers = [
  { queue = "production-queue-name" }

[env.staging] = true
kv_namespaces = [
{ binding = "SESSIONS_KV", id = "XXXXXXXX" }
queues.consumers = [
  { queue = "staging-queue-name" }

When I publish my worker to an environment
wrangler publish --env=staging
I can see that the namespace is available to the worker

Your worker has access to the following bindings:
- KV Namespaces:

But when I attempt to use the namespace I get an error message -
✘ [ERROR] ReferenceError: SESSIONS_KV is not defined

Any idea what I’m doing wrong? I’m pretty stumped at this stage.

If you’re using modules syntax (export default {}), bindings are accessible on the env object passed in the fetch handler, rather than in the global scope.

export default {
    async fetch(request, env) {
        const result = await env.KV.get('key')
        return new Response(result)

Thanks for the quick reply. That fixed the problem.

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.