# KV server API

## Public imports

| Import | Use |
| --- | --- |
| `kv` from `vite-hub/kv` | Read and write the default store or a named store. |
| `disposeKVStores` from `vite-hub/kv` | Close all cached stores in a shutdown hook. |
| `getKVStoreDriver` from `vite-hub/kv` | Name the configured driver that a store uses in this server process. Driver selection occurs at build time; Rate Limit reads it at boot without opening a store connection. App tests return `fs-lite`. |
| `hubKV` from `@vite-hub/kv/vite` | Register KV in the Vite config. |
| `kvStorageDriver` from `@vite-hub/kv/vite` | The unstorage driver over a KV store, for a module that takes a driver name. |
| `resolveKVViteConfig` from `@vite-hub/kv/vite` | Resolve the KV config by hand. |

`vite-hub/kv` also exports all driver, store, module, and storage types.

## Use it at runtime

Import `kv` in server code to save and read values.

```ts [server/api/settings.put.ts]
import { defineEventHandler, readBody } from 'h3'
import { kv } from 'vite-hub/kv'

export default defineEventHandler(async (event) => {
  const [error] = await kv.set('settings', await readBody(event))
  if (error) throw error
  return { ok: true }
})
```

```ts [server/api/settings.get.ts]
import { defineEventHandler } from 'h3'
import { kv } from 'vite-hub/kv'

export default defineEventHandler(async () => {
  const [error, settings] = await kv.get('settings')
  if (error) throw error
  return { settings }
})
```

When your config has more than one store, select one by name.

```ts [server/tenant-preferences.ts]
import { kv } from 'vite-hub/kv'

const preferences = kv.store('tenant-preferences')

export async function savePreferences(tenantId: string, value: unknown) {
  const [error] = await preferences.set(tenantId, value)
  if (error) throw error
}
```

### Read and write many keys

`kv.getMany(keys)` reads many keys in one call. Its value has one item per key, in the order of `keys`, with `null` for a missing key. `kv.setMany(entries)` writes an array of `{ key, value }` entries:

```ts [server/api/profiles.get.ts] fragment
const [writeError] = await kv.setMany([
  { key: 'profile:ada', value: { name: 'Ada' } },
  { key: 'profile:linus', value: { name: 'Linus' } },
], { ttl: '1h' })
if (writeError) throw writeError

const [readError, profiles] = await kv.getMany<{ name: string }>(['profile:ada', 'profile:grace', 'profile:linus'])
if (readError) throw readError
// [{ name: 'Ada' }, null, { name: 'Linus' }]
```

The options work as in `get()` and `set()` and apply to every key. In `setMany()`, the last entry of a key wins, and a `value` of `undefined` deletes the key, as `set()` does. `setMany()` is not atomic: when it fails, some entries can be written. Use `setIfAbsent()` or a Database transaction when all writes must succeed together.

| Driver | `getMany()` | `setMany()` |
| --- | --- | --- |
| `redis` | `MGET`, 1000 keys per command. | One pipeline. |
| `database` | One `SELECT` per 200 keys. | One `INSERT ... ON CONFLICT` per 200 entries. |
| `upstash` | One `MGET`. | One request per entry, 16 at a time. |
| `cloudflare` | One bulk `get()` per 100 keys. | One `put()` per entry, 16 at a time. It checks every entry against the [Workers KV limits](https://vitehub.dev/docs/kv/limits-and-errors#limits) before it writes any. |
| `deno-kv`, `fs-lite` | One read per key, 16 at a time. | One write per key, 16 at a time. |

### Read-only handles

Pass `{ mode: 'read' }` to `kv.store()` for code that only reads. The handle has `get()`, `getMany()`, `has()`, and `list()`. Write methods (`set()`, `setMany()`, `setIfAbsent()`, `delete()`, `deleteIfEquals()`, `clear()`, `increment()`, `getAndDelete()`, `lock()`) are type errors and absent at runtime. The default store is `kv.store('default', { mode: 'read' })`.

```ts [server/api/flags.get.ts]
import { defineEventHandler } from 'h3'
import { kv } from 'vite-hub/kv'

const flags = kv.store('default', { mode: 'read' })

export default defineEventHandler(async () => {
  const [error, value] = await flags.get('flags')
  if (error) throw error
  // flags.set() is a type error.
  return value
})
```

`mode` defaults to `'write'`. Another value throws [`KV_INVALID_STORE_MODE`](https://vitehub.dev/docs/kv/limits-and-errors#kv_invalid_store_mode).

> **Warning**

The mode limits this API, not the host. The Cloudflare KV binding, the Upstash token, and `fs-lite` files keep full access, and code can still import the full `kv`. It is not a security boundary. Use it to show intent and keep writes out of read-only code.

The `redis`, `database`, and `upstash` drivers provide atomic single-use reads and counters:

```ts [server/verification.ts] fragment
const [consumeError, token] = await kv.getAndDelete('verification:token')
if (consumeError) throw consumeError

const [incrementError, attempts] = await kv.increment('rate-limit:user', 60)
if (incrementError) throw incrementError
```

Use `setIfAbsent()` for single-use tokens, such as upload tickets, invite codes, and nonces. It writes only when the key is empty, in one atomic step. It returns `true` to the one call that wrote:

```ts [server/api/uploads/[ticket].put.ts] fragment
const [claimError, claimed] = await kv.setIfAbsent(`uploads:${ticket}`, 1, { ttl: '10m' })
if (claimError) throw claimError
if (!claimed) throw new HTTPError({ status: 409, message: 'Ticket already used' })
```

`setIfAbsent()` needs a value: `undefined` returns `KV_INVALID_VALUE`, because it cannot mean "remove" as in `set()`. Do not use `kv.get()` then `kv.set()`: two requests can both see a missing key and both write.

| Driver | `setIfAbsent()` |
| --- | --- |
| `redis` | Atomic. One `SET NX` command, with `PX` when you pass `ttl`. |
| `database` | Atomic. One `INSERT ... ON CONFLICT` statement that also replaces an expired key. Expiry uses the clock of the Database. |
| `upstash` | Atomic. One `SET NX` command, with `EX` when you pass `ttl`. |
| `deno-kv` | Atomic. One commit that checks the key is missing. Deno KV deletes expired keys some time after the TTL, so a key can stay longer than `ttl`. |
| `fs-lite` | Atomic on one disk, also across processes. It writes a temporary file and links it into place, so other calls see the whole value or none. A key with `ttl` expires on time, and a later call can claim it. |
| `cloudflare` | Returns `KV_UNSUPPORTED_OPERATION`. Workers KV is eventually consistent, so two requests can both see a missing key. Use D1 with `INSERT ... ON CONFLICT DO NOTHING`, or a Durable Object. |

`increment()` applies the TTL only when it creates the counter. Redis and Upstash round it up to whole seconds. A stored value that is not an integer, or that is already `Number.MAX_SAFE_INTEGER`, returns `KV_OPERATION_FAILED` and does not change. Deno KV accepts a new relative expiry on each write, so matching that fixed window would require a hidden deadline and cleanup. Deno KV, Cloudflare KV, and local `fs-lite` stores therefore return `KV_UNSUPPORTED_OPERATION` for both methods.

`deleteIfEquals(key, expected)` deletes the key only when it holds `expected`, in one atomic step, and returns `true` when this call deleted it. Use it to free a token that only its owner may free. For a lock, use [`kv.lock()`](https://vitehub.dev/docs/kv/server-api#locks), which does this for you:

```ts [server/jobs/report.ts] fragment
const owner = crypto.randomUUID()
const [claimError, claimed] = await kv.setIfAbsent('jobs:report', owner, { ttl: 60 })
if (claimError) throw claimError
if (claimed) {
  // ... run the job ...
  const [releaseError] = await kv.deleteIfEquals('jobs:report', owner)
  if (releaseError) throw releaseError
}
```

KV compares the stored text with `expected` serialized as `set()` stores it, so objects with the same fields in another order are not equal. The `redis`, `database`, and `upstash` drivers support it. Other drivers return `KV_UNSUPPORTED_OPERATION`. The type `KVDriversWith<'deleteIfEquals'>` lists the drivers that support an operation. Use the [Rate Limit primitive](https://vitehub.dev/docs/rate-limit) when provider-managed request budgets fit the application.

## Locks

`kv.lock(key, { ttl })` gives a lock that one runner holds at a time, across all server processes that share the store. Use it for a cron job or a sync that must not run twice at once. `run()` takes the lock, calls your function, and releases the lock, also when the function throws:

```ts [server/tasks/daily-report.ts] fragment
const [error, result] = await kv.lock('cron:daily-report', { ttl: '1m' }).run(async () => {
  return await sendDailyReport()
})
if (error) throw error
if (!result.acquired) return // Another runner holds the lock.
console.log(result.value)
```

- `ttl` is required: a duration such as `'1m'`, or a number of seconds. The lock expires after `ttl`, so a crashed runner never keeps it. Pick a value longer than the work.
- `wait` is optional, in seconds. Without it, `run()` returns `{ acquired: false }` at once when the lock is held. With it, `run()` polls with backoff until the lock is free or `wait` ends.
- An error from your function is thrown again after the release. A failed release returns `KV_OPERATION_FAILED`, after your function ran. The lock then expires after `ttl`.

Each lock writes a random owner token with `setIfAbsent()`, and the release frees it with `deleteIfEquals()`. A runner whose lock expired cannot delete the lock of the next runner.

KV does not renew a lock. There is no compare-and-set that changes only the TTL, so a runner cannot extend a lock. When the work runs longer than `ttl`, another runner can take the lock while the first one still runs.

When you must hold the lock across code that does not fit in one function, use `acquire()`. Call `release()` in `finally`:

```ts [server/sync.ts] fragment
const [error, lock] = await kv.lock('sync:github', { ttl: 30, wait: 5 }).acquire()
if (error) throw error
if (!lock.acquired) return
try {
  await syncGitHub()
}
finally {
  // `true`: deleted. `false`: the lock had expired, so another runner can hold it now.
  const [releaseError, released] = await lock.release()
  if (releaseError || !released) console.warn('sync:github lock expired before the release')
}
```

| Driver | `lock()` |
| --- | --- |
| `redis`, `upstash` | Atomic. `SET NX` with a TTL, and a script that deletes the key only when it holds the owner token. Upstash rounds `ttl` up to whole seconds. |
| `database` | Atomic. One `INSERT ... ON CONFLICT` statement, and one `DELETE` that checks the owner token. Expiry uses the clock of the Database. |
| `deno-kv`, `fs-lite`, `cloudflare` | Returns `KV_UNSUPPORTED_OPERATION`, and does not call your function. These drivers have no `deleteIfEquals()`. App tests use `fs-lite`, so they return this code too. |

The type `KVDriversWith<'deleteIfEquals'>` lists the drivers that support `lock()`. For work that runs longer than you can predict, use a lease, which its holder can renew. See [Locks and leases](https://vitehub.dev/docs/guides/run-one-at-a-time).

## Runtime helper

`kv` implements `KVStorage`.

| Method | Description |
| --- | --- |
| `kv.get<T>(key, { type? })` | Reads a value or returns `null`. Pass `type` to convert it, see [Typed reads](https://vitehub.dev/docs/kv/server-api#typed-reads). |
| `kv.getMany<T>(keys, { type? })` | Reads many keys in one call. Returns one value or `null` per key, in the order of `keys`. See [Read and write many keys](https://vitehub.dev/docs/kv/server-api#read-and-write-many-keys). |
| `kv.getAndDelete<T>(key, { type? })` | Atomically returns and deletes a value on `redis`, `database`, and Upstash. `{ type: 'text' }` returns the stored text. |
| `kv.set<T>(key, value, { ttl? })` | Writes a value. With `ttl`, a duration such as `'1h'` or a number of seconds, every driver expires the value after that time. Without `ttl`, the value stays until you delete or replace it. Other options return `KV_INVALID_OPTION`. |
| `kv.setMany<T>(entries, { ttl? })` | Writes an array of `{ key, value }` entries, with the options of `kv.set()`. Not atomic. |
| `kv.setIfAbsent<T>(key, value, { ttl? })` | Writes only when the key is empty, in one step. Returns `true` when this call wrote. Not on Cloudflare KV. |
| `kv.has(key)` | Checks whether a key exists. |
| `kv.increment(key, ttl)` | Atomically increments a counter on `redis`, `database`, and Upstash. |
| `kv.delete(key)` | Deletes one key. |
| `kv.deleteIfEquals<T>(key, expected)` | Atomically deletes the key when it holds `expected`. Returns `true` when this call deleted it. On `redis`, `database`, and Upstash. |
| `kv.list({ prefix?, limit?, cursor? })` | Lists the keys that start with `prefix`, as text: `'user'` matches `users:alice`, and `'users:'` matches only the keys below `users`. Without `limit`, it returns every key and no cursor. With `limit`, it reads one page; pass the returned `cursor` to read the next page. On Cloudflare KV, each binding request returns at most 1,000 keys, so a bounded `limit` above 1,000 returns at most 1,000 keys per page; pass the returned `cursor` when present to read the rest. |
| `kv.clear({ prefix? })` | Deletes the keys that start with `prefix`, with the same text match as `list()`. `kv.clear({ prefix: 'users:' })` deletes `users:alice` but not `users-old:alice`. Without `prefix`, it deletes every key of the store. The store deletes in batches: one statement on `database`, 1000 keys per command on Redis, one command on Upstash. Cloudflare KV deletes one key per call. |
| `kv.store(name, options?)` | Selects a named KV Store. `{ mode: 'read' }` returns a [read-only handle](https://vitehub.dev/docs/kv/server-api#read-only-handles). |

Every async method returns `[error, value]`, so you need no `try/catch`. `error.code` is typed per method, and `why`, `fix`, and `docs` explain it. Provider failures are `KV_OPERATION_FAILED`, with the provider error in `cause`. Configuration errors, such as an unknown store, throw. Read [Limits and errors](https://vitehub.dev/docs/kv/limits-and-errors) for each code.

Keys are strings such as `users:alice` or `users/alice`. Both `/` and `:` separate segments. A key needs at least one segment and no `.` or `..` segment, so `''`, `':'`, and `'a/../b'` return `KV_OPERATION_FAILED`. On Cloudflare KV, a key above 512 UTF-8 bytes returns `KV_KEY_TOO_LONG` ([Limits](https://vitehub.dev/docs/kv/limits-and-errors#limits)).

## Typed reads

`kv.get()` parses a stored string as JSON, so the string `'123'` reads back as the number `123`, and `'true'` as `true`. Pass `type` to get a fixed form:

```ts [server/invite.ts] fragment
const [error, code] = await kv.get('invite:alice', { type: 'text' })
// code is the string '123456', not the number 123456
```

| `type` | Returns |
| --- | --- |
| `'text'` | The stored text as a `string`. Objects and arrays come back as JSON text. |
| `'json'` | The parsed JSON value, as without `type`. |
| `'bytes'` | A `Uint8Array`. |
| `'blob'` | A `Blob`. |
| `'stream'` | A `ReadableStream<Uint8Array>`. |

The return type follows `type`: `kv.get(key, { type: 'text' })` is `string | null`. A missing key is `null` for every `type`. `kv.getAndDelete()` accepts `{ type: 'text' }`. The Upstash client parses JSON first, so on Upstash `'text'` returns the JSON text of the value.

## Use KV from useStorage and Nuxt modules

ViteHub mounts each KV store in Nitro storage. The default store is the mount `kv`, and a named store is `kv-<name>`, for example `kv-sessions`. Store names escape `%`, `:`, `/`, `\\`, and `?` as percent-encoded characters; an empty name uses `%` (for example, `a/b` mounts at `kv-a%2Fb`). The mount and `kv` read and write the same keys, and `ttl` works as in `kv.set()`.

```ts [server/api/visits.get.ts] fragment
import { useStorage } from 'nitro/storage'

export default async () => {
  const storage = useStorage('kv')
  const visits = (await storage.getItem<number>('visits')) ?? 0
  await storage.setItem('visits', visits + 1, { ttl: 3600 })
  return { visits }
}
```

`clear()` on a mount clears only its store. A mount with the same name in `nitro.kv` (or `nitro.storage` in Nuxt) wins.

Nuxt modules that store data in a Nitro mount can use KV this way. For example, set nuxt-og-image's `runtimeCacheStorage` to `'kv'`. For a module that takes an unstorage driver name, such as nuxt-security's `rateLimiter.driver`, pass `kvStorageDriver`:

```ts [nuxt.config.ts] fragment
import { kvStorageDriver } from '@vite-hub/kv/vite'

export default defineNuxtConfig({
  modules: ['vite-hub/nuxt', 'nuxt-og-image', 'nuxt-security'],
  vitehub: { kv: true },
  ogImage: { runtimeCacheStorage: 'kv' },
  security: {
    rateLimiter: { driver: { name: kvStorageDriver, options: { base: 'rate-limit' } } },
  },
})
```

The driver options are `store`, a store name (default: the default store), and `base`, a key prefix.

## Application teardown

After the app stops taking new work, call `disposeKVStores()` in your shutdown hook. It closes cached stores, including Redis connections, open filesystem iterators, and Upstash overflow pages. When a store can use Redis, ViteHub registers it on Nitro's `close` hook for you, so the process can exit after a stop signal.

- Calls at the same time share one cleanup promise.
- Cleanup failures reject with an `AggregateError`.
- Later operations create new stores, so restart in-process listings without an old cursor.

In Nitro, register the hook in a server plugin:

```ts [server/plugins/kv-cleanup.ts] fragment
import { definePlugin } from 'nitro'
import { disposeKVStores } from 'vite-hub/kv'

export default definePlugin((nitroApp) => {
  nitroApp.hooks.hook('close', disposeKVStores)
})
```

<!-- vitehub-docs:section-links -->
## In this section

- [Overview](https://vitehub.dev/raw/docs/kv.md)
- [Get started](https://vitehub.dev/raw/docs/kv/get-started.md)
- [Configure](https://vitehub.dev/raw/docs/kv/configure.md)
- [Server API](https://vitehub.dev/raw/docs/kv/server-api.md) (this page)
- [Agent capability](https://vitehub.dev/raw/docs/kv/agent-capability.md)
- [Hosts](https://vitehub.dev/raw/docs/kv/hosts.md)
- [Limits and errors](https://vitehub.dev/raw/docs/kv/limits-and-errors.md)

Next: [Agent capability](https://vitehub.dev/raw/docs/kv/agent-capability.md)

All pages: [llms.txt](https://vitehub.dev/llms.txt)
