How to Get Value from Deno KV: Simple Guide
To get a value from
Deno KV, use the asynchronous kv.get(key) method, where key is the identifier for the stored data. This returns a promise that resolves to an object containing the value under the value property if the key exists.Syntax
The basic syntax to get a value from Deno KV is:
kv.get(key): Asynchronously fetches the value stored atkey.key: Can be a string or an array of strings/numbers to represent nested keys.- The method returns a promise resolving to an object with a
valueproperty holding the stored data ornullif not found.
typescript
const kv = await Deno.openKv(); const result = await kv.get("myKey"); console.log(result.value);
Output
value stored at 'myKey' or null if not found
Example
This example shows how to store a value and then retrieve it from Deno KV.
typescript
const kv = await Deno.openKv(); // Store a value await kv.set("username", "alice"); // Get the value const result = await kv.get("username"); if (result.value !== null) { console.log("Value found:", result.value); } else { console.log("Key not found."); } await kv.close();
Output
Value found: alice
Common Pitfalls
Common mistakes when getting values from Deno KV include:
- Not awaiting the
kv.get()call, which returns a promise. - Assuming the result is the value directly instead of an object with a
valueproperty. - Not handling the case when the key does not exist, which returns
{ value: null }.
Always check if result.value is null before using it.
typescript
/* Wrong way: */ const result = kv.get("missingKey"); // forgot await console.log(result.value); // Error: result is a Promise /* Right way: */ const resultCorrect = await kv.get("missingKey"); if (resultCorrect.value === null) { console.log("Key not found."); } else { console.log(resultCorrect.value); }
Output
Key not found.
Quick Reference
| Method | Description | Return Value |
|---|---|---|
| kv.get(key) | Fetches the value for the given key | Promise resolving to { value: storedValue | null } |
| kv.set(key, value) | Stores a value at the given key | Promise |
| key | String or array representing the key path | Used to identify stored data |
Key Takeaways
Use await with kv.get(key) to retrieve the stored value asynchronously.
The result of kv.get is an object with a value property, not the value directly.
Check if result.value is null to handle missing keys safely.
Keys can be strings or arrays for nested data in Deno KV.
Always close the KV store with kv.close() when done.