The Cloudflare KV namespace remains unbound

After running wrangler dev, it appears that Worker KV is not being bound properly:

ERROR in /src/handler.ts
./src/handler.ts 16:8-17
[tsl] ERROR in /src/handler.ts(16,9)
      TS2304: Cannot find name 'generalKV'.

This is the content of handler.ts:

async function postHandler(request: Request): Promise<Response> {
  let content = JSON.stringify(await request.json());
  await generalKV.put([Date.now().toString()], JSON.stringify(content));
  return new Response(content);
}

Contents of wrangler.toml:

name = "general-assignment"
type = "javascript"
account_id = "<id>"
workers_dev = true
compatibility_date = "2021-11-01"
kv_namespaces = [ 
    { binding = "generalKV", id = "<id>", preview_id = "<id>" }
]

Some have suggested changing kv_namespaces to kv-namespaces, but this solution did not work for me. Please advise if there are any other steps I may have missed.

Answer №1

For those who discover this question through Google and are using Wrangler v2, encountering the following error:

Uncaught (in promise) ReferenceError: MY_KV is not defined

The tutorials and guides often overlook a crucial second parameter (and a third parameter). This second parameter represents the environment. To successfully utilize and connect to kv, follow these steps:

# Initialize the KV namespaces
wrangler kv:namespace create "MY_KV" &&\
wrangler kv:namespace create "MY_KV" --preview

wrangler will give an error if the preview KV namespace is missing, hence it's recommended to create both. Afterward, add an entry for kv_namespaces array and duplicate the preview_id in the default (dev) section (indicated as yyyy below).

# wrangler.toml
name = "worker"
main = "src/index.js"
compatibility_date = "2022-04-14"
account_id = "...."
workers_dev = true

routes = [
    "exmample.com/*"
]

# Duplicate preview_id to id
kv_namespaces = [
    { binding = "MY_KV", preview_id = "yyyy", id = "yyyy" }
]

# Execute `wrangler publish --env production` when ready
[env.production]
kv_namespaces = [
    { binding = "MY_KV", id = "xxxx" }
]

You can now access kv bindings like this:

# index.js
export default {
  async fetch(request, env) {
  ...
  const someKV = env.MY_KV.get("some-key");
  ...
  }

Answer №2

Have you manually established the KV namespace on Cloudflare already? I don't think it automatically generates them based on the worker binding setup (at least not yet).

Instructions for creating via Wrangler can be found here -

https://example.com/create-kv-namespace

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error in Deno pooling map server due to unhandled AggregateError

I am trying to run this TypeScript code snippet import { serve } from "https://deno.land/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="eb989f8d9cdbc5dbd9dac5db">[email protected]</a>/http/server.ts" imp ...

Transferring information from RSC to a nested child component using the Next.js application router

Currently, I am in the process of migrating a large Pages router next.js project to the App directory. However, I have encountered a common challenge for which I am struggling to find a suitable solution. Despite being accustomed to the convenience of Reac ...

What causes the immediate firing of the DOM callback in Angular 1.2.9?

Check out a live demo here View the source code on GitHub here Angular 1.2.9 brought in DOM callbacks with the introduction of $animate:before and $animate:after events triggered during animations. However, it seems that the $animate:after event is trigg ...

Inconsistencies in Executing JavaScript Methods Between Mobile Safari and Android Chrome

I have a JavaScript method that appears like this: function onAction() { getValue1(); getValue2(); getValue3(); } When I invoke onAction(), I notice a discrepancy in behavior between Mobile Safari and Android Chrome. In Safari, all three meth ...

Transforming numerical figures into written form within a specified range: A step-by-step guide

I have a unique custom range design that I have personally customized. Beneath each step of the range, there is a value displayed in a stylish green box. https://i.sstatic.net/vzeRK.png My query is regarding how I can replace the numeric values with tex ...

Is the this.props.onChange method called within the render function?

I'm having trouble grasping the concept of the assigned onChange property in this TextField component I found in the material-ui library: <TextField style = {{"padding":"10px","width":"100%"}} type = {'number'} valu ...

What could be causing the "function undefined" error in my HTML document?

Recently, I developed a small chat application that initially functioned well with all code contained in one HTML document. However, after separating the CSS, HTML, and JS into individual files, an issue arose when invoking the register_popup function from ...

Using the .ajax() function with jQuery to retrieve data and then using .find() on that data

Currently I am facing an issue while trying to extract the body tag from the result of the .ajax() call. Instead of getting the desired result, I only see undefined logged into the console... This is the section of code causing the problem: $(document).r ...

Efficiently handling jsonwebtoken errors in node and express

Here is the verification function I've created: exports.verifyToken = function(req, res, next){ var token = req.body.token; jwt.verify(token, config.sessionSecret, function(err, decoded) { if(err){ return next(err); }else{ ...

Loop through the numbers entered into a table field

<table id="Container1Details" cellspacing="15"> <tbody> <tr> <td align="right"> <input name="acidity" type="number" maxlength="4" id="acidity" min="0.112" max="0.152" step="0.001" style= ...

Updating the div#content dynamically with Jquery without the need to refresh the page

After spending countless hours on this forum, I have yet to find a solution that perfectly fits my needs, so I will pose my question. Here is the gist of what I am attempting to accomplish: When the page loads, the default page fades in and displays. Wh ...

How to retrieve an element using a dynamically generated class name in Vue.js

<v-data-table :headers="menuheaders" //this menus from api response :items="menus" item-key="usersmenu_menuid" items-per-page="1000" hide-default-footer="" class="elevation-1" > <template v-s ...

Express Concurrency: Managing Multiple Tasks Simultaneously

Looking to create an API using Express that is capable of processing requests either through multithreading or multiprocessing. For example, the following API has a 5-second sleep before responding. If I make 3 quick calls to it, the first response will ta ...

What is the best way to implement sorting in a table using react virtualized?

I've been working on implementing sorting in my project using the table sorting demo available on Github. Here is the code I'm using: import React from 'react'; import PropTypes from 'prop-types'; import { Table, Column, Sor ...

Is it possible to include additional information when creating a subscription for a customer on Stripe using Node.js

I am facing an issue with adding metadata to the customer object during the creation of a new subscription/customer using Stripe. The problem lies in the fact that the metadata is not being saved to the customer object. I have checked the logs/events in St ...

Editing the content of a div in real-time by dynamically updating the innerHTML

Looking for a way to dynamically change the innerHTML of a contentEditable div using pure JavaScript, without relying on the Rangy library. I want the change to occur on keyup without losing cursor position or focus. Here is an example setup: <div id=" ...

Exporting a function from Vue's `<script setup>` is similar to exporting from a module

I am trying to export a function from a component within the component itself and then use it in another component. My attempt looks like this: <!-- TestHeading.vue --> <template> <h1>{{ title }}</h1> </template> <scrip ...

What is the best way to reset form after submission in Next.js?

I have a contact form and I want all the form values to be cleared after submitting the form. I've tried the following code, but the values of the form remain unchanged after submission. What could be causing this issue and how can it be resolved? ...

NGRX 8 reducer now outputting an Object rather than an Array

I am facing an issue where the data returned from the reducer is an object instead of an array. Despite trying to return action.recentSearches, it doesn't seem to work as expected. The data being returned looks like this: { "loading": false, "recent ...

Interactive radio button that only registers the most recent click

Homepage.jsx const Homepage = () => { const [categories, setCategories] = useState([]) const [products, setProducts] = useState([]) const [selected, setSelected] = useState("all") const getAllCategories = async() => { try{ ...