How to Set Value in Deno KV: Simple Guide with Examples
To set a value in
Deno KV, use the kv.set() method with a key array and the value you want to store. For example, await kv.set(["myKey"], "myValue") saves the value under the key myKey.Syntax
The kv.set() method stores a value in Deno KV. It takes two main parts:
- Key: An array of strings or numbers that uniquely identifies the entry.
- Value: Any JSON-serializable data you want to save.
You must await the kv.set() call because it is asynchronous.
typescript
await kv.set(["key1", "key2"], "value")
Example
This example shows how to open a Deno KV store, set a value, and then confirm it was saved by retrieving it.
typescript
import { openKv } from "https://deno.land/x/kv/mod.ts"; const kv = await openKv(); // Set a value with key ["user", "123"] await kv.set(["user", "123"], { name: "Alice", age: 30 }); // Get the value back const result = await kv.get(["user", "123"]); console.log(result.value);
Output
{"name":"Alice","age":30}
Common Pitfalls
Some common mistakes when setting values in Deno KV include:
- Not using an array for the key. The key must always be an array, even if it has one element.
- Forgetting to
awaitthekv.set()call, which can cause unexpected behavior. - Trying to store non-serializable values like functions or symbols, which will cause errors.
typescript
/* Wrong: key is a string, not an array */ // await kv.set("user123", "value"); // โ /* Right: key is an array */ await kv.set(["user123"], "value"); // โ
Quick Reference
Remember these tips when setting values in Deno KV:
- Use
await kv.set(keyArray, value). - Key must be an array of strings or numbers.
- Value must be JSON-serializable.
- Always handle asynchronous calls properly.
Key Takeaways
Always use an array as the key when calling
kv.set().Await the
kv.set() method because it is asynchronous.Store only JSON-serializable values to avoid errors.
Use
kv.get() to verify your value was saved correctly.Deno KV keys can be multi-part arrays for better organization.