How to Delete Data from Deno KV Store Easily
To delete data from
Deno KV, use the delete() method with the key you want to remove. This method is asynchronous and returns true if the key existed and was deleted, or false if the key was not found.Syntax
The delete() method removes a key-value pair from the Deno KV store.
await kv.delete(key): Deletes the entry with the specifiedkey.key: An array representing the key path, e.g.,["user", "123"].- The method returns a
Promise<boolean>indicating if the key was deleted (true) or not found (false).
typescript
const result = await kv.delete(["your", "key"]);
Example
This example shows how to delete a key from Deno KV and check if the deletion was successful.
typescript
import { openKv } from "https://deno.land/x/kv/mod.ts"; const kv = await openKv(); // Set a key-value pair await kv.set(["session", "token"], "abc123"); // Delete the key const deleted = await kv.delete(["session", "token"]); console.log("Deleted:", deleted); // true // Try deleting again const deletedAgain = await kv.delete(["session", "token"]); console.log("Deleted again:", deletedAgain); // false
Output
Deleted: true
Deleted again: false
Common Pitfalls
Common mistakes when deleting from Deno KV include:
- Using a wrong key format (not an array) which causes errors.
- Assuming
delete()throws an error if the key does not exist; it returnsfalseinstead. - Not awaiting the
delete()call, leading to unexpected behavior.
typescript
/* Wrong way: missing await and wrong key type */ // kv.delete("wrongKey"); // โ This will cause an error /* Right way: use await and array key */ await kv.delete(["correct", "key"]); // โ
Quick Reference
| Operation | Usage | Returns |
|---|---|---|
| Delete key | await kv.delete(["key", "path"]) | Promise |
| Key format | Array of strings or numbers | N/A |
| Error if key missing | No, returns false | N/A |
| Await required | Yes | N/A |
Key Takeaways
Use await kv.delete(keyArray) to remove a key from Deno KV.
The key must be an array representing the key path.
delete() returns true if the key existed and was deleted, false otherwise.
Always await the delete() call to ensure it completes.
No error is thrown if the key does not exist; check the boolean result instead.