Write Data to Cloudflare Workers KV Store with BINDING.put

Share this video with your friends

Send Tweet
Published 4 months ago
Updated 3 weeks ago

Now that we have our database setup, we need to be able to write data to that database. Firstly, we need to understand the binding concept. Secondly, we are going to use .put() to write that data to our database. Remember that .put() is an async function so we need to await it for it to work in the way that we want it to.

Instructor: [0:00] Now that the KV namespace is defined in our wrangler.toml, let's start understanding how to use KV inside of our application.

[0:06] The first thing you need to understand about KV namespaces is the binding concept. This is effectively a constant that can be used in our code to refer to this KV namespace. In this example, I've called it MY_FIRST_KV. Here in my code, if I want to use that, I can say MY_FIRST_KV, and that refers to my KV namespace.

[0:32] The PUT function takes two arguments. The first is a key, which is going to be how we refer to this piece of data in our KV namespace later on. For instance, I'll say "test-key". This is always a string. Then, the value.

[0:49] The value here can be a couple different things. Generally, the easiest way to get into using KV is to just use strings. For instance, I could say "test-key," which is a value, but if I wanted to get more complicated and store more complex pieces of data, I could do things like JSON.stringify() something in here. For instance, an object that is test-key, or anything else that can be stringified in here, numbers, arrays, etc.

[1:14] For now, I'm going to use plain strings. I'll say "test-key" as my key, and my value is another string, which is "value." When this code runs, it's going to go to the KV namespace. It's going to put this value here as the value for test-key. This is an asynchronous function.

[1:34] In order to wait for this to complete, I'm going to add await at the beginning of this call. Any time that this handle request function is called, it's going to wait for this MY_FIRST_KV namespace to put this value string here as the value for test-key.