KV binding is not defined

I have my binding set up in wrangler.toml, and set through the interface against my project for publish.

kv_namespaces = [
    { title = "KV_FROM_TEST_WORKER", binding = "KV_FROM_TEST_WORKER", id = "<id>", preview_id = "<preview_id>" }
]

(I tried both with and without title included)

and in my src/index.js

export default {
    async fetch(request) {
        let response;
        if (request.method === 'POST') {
            const body = await request.json()
            console.log(JSON.stringify(body))
            return await generate(body);
        } else {
            console.log("GOT");
            const added = await KV_FROM_TEST_WORKER.get("foo");
            const response = new Response(JSON.stringify({'success': true, "data": added}), { "status": 200 });
            return response;
            return new Response("GOT");
        }
    },
};

However, running both locally and on the web, both error with the following error when making a GET request

Uncaught (in promise) ReferenceError: KV_FROM_TEST_WORKER is not defined

Would anyone be able to help with what I am missing in my set up to enable this?

It looks like you’re using the newer module worker format, which will expose KV bindings and env vars etc. in env rather than as globals.

Add env as the second argument to your exported fetch function like async fetch(request, env), and you should then be able to access env. KV_FROM_TEST_WORKER, etc.

The docs for this aren’t amazing yet, but here’s some more info: https://developers.cloudflare.com/workers/learning/migrating-to-module-workers/

4 Likes

Thanks cherryjimbo, that has solved the issue.

2 Likes