npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@4players/kv

v0.17.0

Published

A Deno KV client library for Node.js and Bun: KV Connect servers, local SQLite and in-memory databases.

Readme

@4players/kv

A Deno KV client library for Node.js and Bun.

  • Access self-hosted denokv servers (or any endpoint implementing the open KV Connect protocol) on Node 18+ and Bun.
  • Create local KV databases backed by SQLite, using native NAPI code shipped with the package - compatible with databases created by Deno itself.
  • Create ephemeral in-memory KV instances backed by SQLite memory files or by a lightweight JS-only implementation for testing.
  • Architecture-specific native code for the SQLite backend (see below); the only JS dependency is msgpackr, for MessagePack values.
  • Simply call the exported openKv function (equiv to Deno.openKv) with a url or local path to get started!

Quick start - Node 18+ and Bun

Install the npm package 👉 npm install @4players/kv

Remote KV Database

import { openKv } from "@4players/kv";

// connect to a denokv server
const kv = await openKv("http://localhost:4512/");
// access token for auth is the value of environment variable DENO_KV_ACCESS_TOKEN by default

// do anything using the KV api: https://deno.land/api?s=Deno.Kv&unstable
const result = await kv.set(["from-client"], "hello!");
console.log(result);

// close the database connection
kv.close();

// to provide an explicit access token, pass it as an additional option
const kv2 = await openKv("http://localhost:4512/", {
  accessToken: mySecretAccessToken,
});

Local KV Database

import { openKv } from "@4players/kv";

// create a local KV database instance backed by SQLite
const kv = await openKv("kv.db");

// do anything using the KV api: https://deno.land/api?s=Deno.Kv&unstable
const result = await kv.set(["from-client"], "hello!");
console.log(result);

// close the database connection
kv.close();

In-Memory KV Database (no native code)

import { openKv } from "@4players/kv";

// create an ephemeral KV instance for testing
const kv = await openKv("");

// do anything using the KV api: https://deno.land/api?s=Deno.Kv&unstable
const result = await kv.set(["from-client"], "hello!");
console.log(result);

// close the database connection
kv.close();

Examples use ESM syntax, but this package supports CJS require-based usage as well

Local KV Databases

Local disk-based databases are backed by SQLite, and are compatible with databases created with Deno itself:

  • leverages shared Rust code from denoland/denokv with a small shim compiled for Node's native interface via the NAPI-RS framework
  • the native code for all supported platforms ships with the package, and the one for the current platform is loaded at runtime

The following platforms are supported, on Node 18+ and Bun:

  • darwin-arm64
  • darwin-x64
  • linux-arm64-gnu
  • linux-x64-gnu
  • win32-arm64-msvc
  • win32-x64-msvc

The Linux binaries need glibc 2.17 or newer. On musl-based systems such as Alpine, use the remote or in-memory implementation.

Credits


API

This package exports a single convenience function openKv, taking an optional string path, with optional opts. Depending on the path provided, one of three different implementations are used:

  • if path is omitted or blank, an ephemeral in-memory db implementation is used, useful for testing
  • if path is an http or https url, the remote client implementation is used to connect to Deno Deploy or self-hosted denokv instances
  • otherwise the path is passed to the native sqlite implementation - can specify local paths or :memory: for SQLite's in-memory mode

You can override the implementation used via the implementation option:

const kv = await openKv("https://example.com/not-really-remote", {
  implementation: "in-memory",
});

Pass the debug option to console.log additional debugging info:

const kv = await openKv("http://localhost:4512/", {
  debug: true,
});

Supported features

| Feature | sqlite | in-memory | remote (KV Connect) | | --------------------------------------------- | ------ | --------- | ------------------- | | get / getMany / set / delete / list | ✅ | ✅ | ✅ | | atomic() (checks, sum / min / max) | ✅ | ✅ | ✅ | | Key expiration (expireIn) | ✅ | ✅ | ✅ | | watch | ✅ | ✅ | ✅ | | enqueue / listenQueue | ✅ | ✅ | ❌ |

Queue operations are not part of the KV Connect protocol, so they are only available with a local (sqlite or in-memory) database.

Backend-specific options

Each implementation supports different additional options, via the second parameter to openKv:

Remote backend

export interface RemoteServiceOptions {
  /** Access token used to authenticate to the remote service */
  readonly accessToken: string;

  /** Wrap unsupported V8 payloads to instances of UnknownV8 instead of failing.
   *
   * Only applicable when using the default serializer. */
  readonly wrapUnknownValues?: boolean;

  /** Enable some console logging */
  readonly debug?: boolean;

  /** Custom serializer to use when serializing v8-encoded KV values.
   *
   * Defaults to this package's V8-compatible serializer, on any runtime. */
  readonly encodeV8?: EncodeV8;

  /** Custom deserializer to use when deserializing v8-encoded KV values.
   *
   * Defaults to this package's V8-compatible deserializer, on any runtime. */
  readonly decodeV8?: DecodeV8;

  /** Custom fetcher to use for the underlying http calls.
   *
   * Defaults to the `transport`.
   */
  readonly fetcher?: Fetcher;

  /** How requests reach the server. `"http2"`: a pool of HTTP/2 sessions
   * (h2c without TLS) that multiplexes requests and opens further
   * connections as the server's stream limit requires. `"fetch"`: the
   * global `fetch`, which speaks HTTP/1.1 only on Bun, and on Node without
   * TLS, so every concurrent request there takes a connection of its own,
   * and a watch holds one for as long as it runs. `"auto"` (default) is
   * `"http2"` for a server that answers over it, and `"fetch"` for one that
   * does not. The pool is closed with the database. For other pool
   * settings pass a `fetcher` from `makeHttp2Fetcher` instead. */
  readonly transport?: "auto" | "fetch" | "http2";

  /** Max number of times to attempt to retry certain fetch errors (like 5xx) */
  readonly maxRetries?: number;

  /** Limit to specific KV Connect protocol versions */
  readonly supportedVersions?: KvConnectProtocolVersion[];

  /** How values other than `Uint8Array` and `KvU64` are written: `"v8"`
   * (default, readable by Deno's built-in KV) or `"msgpack"`. Both are
   * always read. */
  readonly valueEncoding?: ValueEncoding;
}

Native SQLite backend

export interface NapiBasedServiceOptions {
  /** Enable some console logging */
  readonly debug?: boolean;

  /** Underlying native napi interface */
  readonly napi?: NapiInterface;

  /** Custom serializer to use when serializing v8-encoded KV values.
   *
   * Defaults to this package's V8-compatible serializer, on any runtime. */
  readonly encodeV8?: EncodeV8;

  /** Custom deserializer to use when deserializing v8-encoded KV values.
   *
   * Defaults to this package's V8-compatible deserializer, on any runtime. */
  readonly decodeV8?: DecodeV8;

  /** The database will be opened as an in-memory database. */
  readonly inMemory?: boolean;

  /** How values other than `Uint8Array` and `KvU64` are written: `"v8"`
   * (default, readable by Deno's built-in KV) or `"msgpack"`. Both are
   * always read. */
  readonly valueEncoding?: ValueEncoding;
}

Lightweight In-Memory backend

export interface InMemoryServiceOptions {
  /** Enable some console logging */
  readonly debug?: boolean;

  /** Maximum number of attempts to deliver a failing queue message before giving up. Defaults to 10. */
  readonly maxQueueAttempts?: number;
}

Value encodings

By default, values are written in V8's serialization format, which Deno's built-in KV reads and writes. With valueEncoding: "msgpack" (remote and sqlite backends), values are written as MessagePack instead (VE_MSGPACK, using msgpackr with records). It is not tied to a JavaScript engine, decodes several times faster than V8's format in JavaScript and is often less than half the size. Both encodings are always read, so a database can hold a mix and be converted gradually, by rewriting values.

const kv = await openKv("http://localhost:4512/", { valueEncoding: "msgpack" });

Things to know before switching:

  • Deno's built-in KV (Deno.openKv) cannot read VE_MSGPACK values, and the server must be a denokv build that knows the encoding.
  • MessagePack keeps strings, numbers (incl. NaN/Infinity), bigint, undefined, null, booleans, Date, Uint8Array, Map, arrays and plain objects. Anything else changes silently, so do not store it:
    • -0 is read back as 0, lone surrogates in strings as U+FFFD, and __proto__ keys are dropped;
    • Set, RegExp and Error come back as arrays, boxed primitives as {};
    • other typed arrays, ArrayBuffer and DataView come back as Uint8Array, with wrong or no contents;
    • repeated and circular references are not kept (circular ones cannot be written).
  • Uint8Array and KvU64 values at the top level keep their own encodings (VE_BYTES, VE_LE64) either way, so sum/min/max work as before.

HTTP/2

The remote client sends its requests over a pool of HTTP/2 sessions: without TLS as h2c with prior knowledge, which denokv serves, so nothing changes on the server. One session multiplexes many requests, and the pool opens further sessions when the server's advertised stream limit (200 for denokv, less behind many proxies) or its own cap of 100 streams per session is reached, up to 8 sessions per origin. Sessions close after a minute idle, and the pool closes with the database.

A server that does not answer over HTTP/2 (its first session fails, or stays silent for three seconds) gets its requests from the global fetch instead, which on Bun, and on Node against a plain http:// server, speaks HTTP/1.1: connections are kept alive and reused, but every request in flight needs one of its own, and a watch keeps one for as long as it runs. That is the transport: "auto" default; "http2" and "fetch" force one or the other:

const kv = await openKv("http://localhost:4512", {
  accessToken,
  transport: "fetch",
});

For other pool settings, or to share a pool between databases, pass a fetcher instead; openKv then leaves it open:

import { makeHttp2Fetcher, openKv } from "@4players/kv";

const fetcher = makeHttp2Fetcher({
  maxStreamsPerSession: 50,
  maxSessions: 4,
  fallback: fetch,
});
const kv = await openKv("http://localhost:4512", { accessToken, fetcher });
// ...
kv.close();
await fetcher.close();

h2c with prior knowledge does not pass through most reverse proxies and load balancers, where the fallback applies; behind TLS, the same transport negotiates HTTP/2 with ALPN. Requires node:http2, loaded on first use.

A request is repeated on its own only when it provably was not processed: the server refused the stream, or the connection never produced the server's settings. A connection lost before the response fails the request instead, as with fetch, since the server may have processed it already and a write must not run twice. Bun reports a refused stream as a plain close, so there such a request fails too.

Other runtimes

This package is targeted for Node.js and Bun, and may work on other runtimes with the following notes:

V8 Serialization

Deno KV uses V8's serialization format to serialize values, provided natively by Deno.

On every other runtime, this package uses its own implementation of that format in plain JavaScript, so data stays readable by Deno and by any other client of the same database. Neither runtime's built-in v8 module can be used for this: Node's writes typed arrays as Node-specific host objects (which Deno cannot read) and cannot read the newest format version written by Deno, and Bun's uses JavaScriptCore's format.

Supported value types: primitives (incl. bigint), plain objects, arrays, Date, RegExp, Map, Set, Error, boxed primitives, ArrayBuffer, typed arrays, DataView, and repeated or circular references. Like structuredClone, class instances are stored as plain objects; functions, symbols, proxies and the built-ins V8 refuses to clone (weak references, promises, iterators, Intl objects, …) throw. As in V8, the type of a value follows its internal state, not its prototype. Without Node's util.types (provided by Node, Bun and Deno), proxies cannot be detected, and built-ins are told apart by their prototype.

You can still provide your own encodeV8 and decodeV8 as the second parameter to openKv:

import { makeV8Serializer, openKv } from "@4players/kv";

const { encodeV8, decodeV8 } = makeV8Serializer(); // the default

const kv = await openKv("kv.db", { encodeV8, decodeV8 });

V8 serialization is only necessary for SQLite and remote databases, the in-memory implementation used when calling openKv() or openKv('') uses in-process values and structuredClone instead.