0
0
DenoHow-ToBeginner ยท 4 min read

How to Use Deno.openKv for Key-Value Storage

Use Deno.openKv() to open a key-value store in Deno. It returns a Kv instance that lets you store, retrieve, and delete data using simple key arrays. Always use await to open the store and perform async operations.
๐Ÿ“

Syntax

The basic syntax to open a key-value store is using await Deno.openKv(). This returns a Kv object to interact with the store.

  • Deno.openKv(): Opens or creates a persistent key-value store.
  • kv.get(key): Retrieves a value by key.
  • kv.set(key, value): Stores a value with the given key.
  • kv.delete(key): Removes a key-value pair.

Keys are arrays of strings or numbers to allow hierarchical storage.

typescript
const kv = await Deno.openKv();

// Example key and value
const key = ["user", "123"];
await kv.set(key, { name: "Alice", age: 30 });
const result = await kv.get(key);
console.log(result.value);
Output
{ name: "Alice", age: 30 }
๐Ÿ’ป

Example

This example shows how to open the key-value store, add a user object, retrieve it, and delete it.

typescript
async function demoOpenKv() {
  const kv = await Deno.openKv();

  const userKey = ["user", "001"];
  const userData = { name: "Bob", age: 25 };

  // Store data
  await kv.set(userKey, userData);
  console.log("User saved.");

  // Retrieve data
  const getResult = await kv.get(userKey);
  console.log("Retrieved user:", getResult.value);

  // Delete data
  await kv.delete(userKey);
  console.log("User deleted.");

  // Confirm deletion
  const checkDeleted = await kv.get(userKey);
  console.log("After deletion:", checkDeleted.value);
}

demoOpenKv();
Output
User saved. Retrieved user: { name: "Bob", age: 25 } User deleted. After deletion: undefined
โš ๏ธ

Common Pitfalls

  • Forgetting to await Deno.openKv() causes errors because it returns a promise.
  • Using a simple string as a key instead of an array can cause unexpected behavior; keys must be arrays.
  • Not handling the case when kv.get() returns undefined if the key does not exist.
  • Not closing the Kv store (optional but recommended) can lead to resource leaks.
typescript
async function wrongUsage() {
  // Wrong: not awaiting openKv
  // const kv = Deno.openKv(); // This is a Promise, not Kv instance

  // Correct:
  const kv = await Deno.openKv();

  // Wrong: using string key
  // await kv.set("user001", { name: "Eve" }); // Key must be array

  // Correct:
  await kv.set(["user", "001"], { name: "Eve" });

  // Handle missing key
  const result = await kv.get(["user", "nonexistent"]);
  if (result.value === undefined) {
    console.log("Key not found.");
  }
}

wrongUsage();
Output
Key not found.
๐Ÿ“Š

Quick Reference

MethodDescriptionUsage Example
Deno.openKv()Opens or creates a key-value storeconst kv = await Deno.openKv();
kv.get(key)Gets value by key (array)const res = await kv.get(["user", "123"]);
kv.set(key, value)Sets value for keyawait kv.set(["user", "123"], {name: "Alice"});
kv.delete(key)Deletes key-value pairawait kv.delete(["user", "123"]);
kv.close()Closes the store (optional)await kv.close();
โœ…

Key Takeaways

Always use await when calling Deno.openKv() to get the Kv instance.
Keys must be arrays of strings or numbers to organize data hierarchically.
Check for undefined when retrieving keys that might not exist.
Use kv.set(), kv.get(), and kv.delete() to manage data in the store.
Optionally close the Kv store with kv.close() to free resources.