0
0
DenoHow-ToBeginner ยท 3 min read

How to Use KV in Deno Deploy: Simple Guide with Examples

In Deno Deploy, use the built-in kv API to store and retrieve key-value pairs asynchronously. Access it via await kv.get(key) and await kv.set(key, value) inside your request handler to persist data across requests.
๐Ÿ“

Syntax

The kv API in Deno Deploy provides simple methods to store and retrieve data by keys.

  • await kv.get(key): Retrieves the value for the given key.
  • await kv.set(key, value): Stores the value under the given key.
  • await kv.delete(key): Removes the value stored at key.

Keys can be strings or arrays of strings for namespaces. Values can be any JSON-serializable data.

typescript
const value = await kv.get("myKey");
await kv.set("myKey", "myValue");
await kv.delete("myKey");
๐Ÿ’ป

Example

This example shows a simple Deno Deploy handler that increments a counter stored in KV on each request and returns the current count.

typescript
import { serve } from "https://deno.land/std@0.203.0/http/server.ts";

serve(async (req) => {
  // Get current count or default to 0
  const countEntry = await kv.get(["counter"]);
  const count = (countEntry.value ?? 0) + 1;

  // Store updated count
  await kv.set(["counter"], count);

  return new Response(`Visitor count: ${count}`, {
    headers: { "content-type": "text/plain" },
  });
});
Output
Visitor count: 1 (then increments on each request)
โš ๏ธ

Common Pitfalls

Common mistakes when using kv in Deno Deploy include:

  • Not awaiting kv.set or kv.get, causing unexpected behavior.
  • Using non-serializable values (like functions or DOM objects) which cause errors.
  • Using simple strings as keys without namespaces, which can cause key collisions.
  • Assuming immediate consistency; KV operations are eventually consistent in some cases.
typescript
/* Wrong: Missing await causes bugs */
kv.set("key", "value"); // Don't forget await

/* Right: Always await async KV calls */
await kv.set("key", "value");
๐Ÿ“Š

Quick Reference

MethodDescriptionExample
getRetrieve value by keyawait kv.get(["user", "123"]);
setStore value by keyawait kv.set(["user", "123"], { name: "Alice" });
deleteRemove value by keyawait kv.delete(["user", "123"]);
โœ…

Key Takeaways

Use await with kv methods to handle asynchronous storage correctly.
Keys can be arrays for better organization and to avoid collisions.
Values must be JSON-serializable to store in KV.
KV storage persists data across requests in Deno Deploy.
Avoid using non-serializable data and always handle possible null returns from kv.get.