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 givenkey.await kv.set(key, value): Stores thevalueunder the givenkey.await kv.delete(key): Removes the value stored atkey.
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.setorkv.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
| Method | Description | Example |
|---|---|---|
| get | Retrieve value by key | await kv.get(["user", "123"]); |
| set | Store value by key | await kv.set(["user", "123"], { name: "Alice" }); |
| delete | Remove value by key | await 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.