Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 37 ยท Deno KV and Data

Deno KV Basics

Store data with Deno KV, the built-in key-value database. Learn hierarchical keys, get, set, delete, versionstamps, listing by prefix and range, pagination, expiry and secondary indexes.

Most apps need to remember something: a counter, a user profile, a shortened URL, a to-do list. Normally that means choosing, installing and hosting a database before you can store the first row. Deno KV removes that step. It is a key-value database built into the runtime: await Deno.openKv() and you can read and write, with ACID transactions, on your laptop (backed by a local SQLite file) and in production on Deno Deploy (backed by a globally replicated store).

This lesson covers the data model and the everyday operations. The next one, Atomic Operations, Queues and Watch, covers transactions and the real-time features.

Deno KV exists only inside Deno, so Deno.openKv code is shown read-only. The runnable examples use MiniKv, a small in-memory stand-in written in Node that has the same method names and result shapes (get, set, delete, list, getMany, atomic) for the features taught here. Where the examples call openKv(), in real Deno you call Deno.openKv(). Depending on your Deno version, KV may still be behind the --unstable-kv flag (or "unstable": ["kv"] in deno.json); if Deno says the API is unstable, add it.

Open a database

TypeScript
const kv = await Deno.openKv();               // default local file, or Deploy's database
const scratch = await Deno.openKv(":memory:"); // throwaway, great for tests
const file = await Deno.openKv("./data.db");   // a file you choose

Locally Deno stores the default database in a per-project location on disk, so data survives restarts. Opening needs file permissions for a path you choose (--allow-read and --allow-write). You can also connect to a hosted database over the network with a URL and an access token in DENO_KV_ACCESS_TOKEN.

Keys are arrays

Instead of one flat string, a key is an array of parts. This gives you folders for free:

TypeScript
["users", 42]                 // user 42
["users", 42, "settings"]     // user 42's settings
["posts", "2026", "hello"]
["counter", "visits"]

A key part can be a string, number, bigint, boolean or Uint8Array. Keys are sorted in a fixed order: first by the first part, then the second, and so on. Within one position, types sort as bytes, then strings, then numbers, then bigints, then booleans. That sorting makes prefix and range queries fast, so design keys so that things you list together share a prefix.

Limits worth remembering: a key may be at most 2 KiB when serialized, and a value at most 64 KiB. Store small records, and keep big files in an object store.

set, get and delete

TypeScript
const kv = await Deno.openKv();

await kv.set(["users", 1], { name: "Ada", role: "admin" });

const entry = await kv.get<{ name: string; role: string }>(["users", 1]);
console.log(entry.key);          // ["users", 1]
console.log(entry.value);        // { name: "Ada", role: "admin" }
console.log(entry.versionstamp); // "00000000000000020000" (opaque string)

const missing = await kv.get(["users", 99]);
console.log(missing.value);      // null
console.log(missing.versionstamp); // null

await kv.delete(["users", 1]);

Values can be anything the structured clone algorithm supports: plain objects, arrays, strings, numbers, booleans, Date, Map, Set, typed arrays and bigint. Functions and class instances lose their prototypes. get never throws for a missing key; check entry.value === null (or the versionstamp).

The versionstamp is an opaque, increasing string that changes on every write to that key. Its main use is optimistic concurrency, which the next lesson covers.

The runnable version below uses MiniKv:

Node.js set, get and delete (MiniKv stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Listing: prefix, range, limit, reverse

kv.list returns an async iterable of entries in key order. The most common selector is a prefix:

TypeScript
for await (const entry of kv.list<User>({ prefix: ["users"] })) {
  console.log(entry.key, entry.value);
}

// collect into an array
const users = [];
for await (const e of kv.list<User>({ prefix: ["users"] }, { limit: 10 })) {
  users.push(e.value);
}
Selector or option Meaning
{ prefix: ["users"] } every key that begins with the parts users
{ prefix: ["posts", "2026"], start: [...] } a prefix, starting at a given key
{ start: ["a"], end: ["c"] } a range: start inclusive, end exclusive
{ limit: 20 } at most 20 entries per call
{ reverse: true } newest or last key first
{ cursor } continue from where a previous listing stopped

A prefix matches ["users", 1], ["users", 2, "settings"] and every other key below it. To get only direct children of a "folder", check entry.key.length yourself.

Pagination with a cursor

The iterator exposes iterator.cursor, an opaque string for the next page:

TypeScript
async function page(cursor?: string) {
  const iter = kv.list({ prefix: ["posts"] }, { limit: 10, cursor });
  const items = [];
  for await (const e of iter) items.push(e.value);
  return { items, next: items.length === 10 ? iter.cursor : null };
}

Send next to the client and pass it back for the following page. Do not parse or build cursors yourself.

Expiry

Give an entry a lifetime and KV deletes it for you, perfect for sessions, caches and one-time codes:

TypeScript
await kv.set(["sessions", token], { userId: 7 }, { expireIn: 60 * 60 * 1000 }); // 1 hour

expireIn is in milliseconds. After it elapses the key behaves as if it never existed.

Secondary indexes

KV looks things up by key only. To find a user by email as well as by id, write two entries: the record, and an index entry that points to it.

Node.js Prefix listing, expiry and an email index (MiniKv stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The email index is created in one atomic step so you can never end up with a user but no index (or a taken email). Atomic operations are the subject of the next lesson.

Good key design

  • Put the broad thing first: ["users", id], ["posts", userId, postId].
  • Use zero-padded or numeric parts when you want chronological order: ["events", Date.now(), id]. Numbers sort numerically; strings sort alphabetically, so "10" comes before "9".
  • To list newest first, use reverse: true.
  • Never put secrets or user-controlled huge strings into keys.
  • Write the index entries together with the record, in one atomic commit.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What kind of value is a Deno KV key?

    Keys are arrays of strings, numbers, bigints, booleans or Uint8Arrays. The array form lets you list by prefix.
  2. 2. What does kv.get return for a key that does not exist?

    get always returns an entry object; for a missing key both value and versionstamp are null.
  3. 3. How do you list all entries under ["users"]?

    list takes a selector. A prefix selector returns every key that begins with those parts, in key order.
  4. 4. What unit does expireIn use?

    expireIn is a number of milliseconds, so one hour is 60 * 60 * 1000.
  5. 5. Why write an index entry such as ["users_by_email", email]?

    There are no queries by value. A secondary index is a second key that points to the primary record.

Summary

  • Deno.openKv() opens a built-in database: a local file in development, a replicated service on Deploy.
  • Keys are arrays; values are structured-cloneable and limited to 64 KiB.
  • get returns { key, value, versionstamp }, with nulls for a missing key; set, delete and getMany cover the basics.
  • list supports prefix, range, limit, reverse and cursor pagination; expireIn removes entries automatically.
  • Secondary indexes are extra keys you write together with the record.

Next: Atomic Operations, Queues and Watch