# Keyv Simple key-value storage with support for multiple backends Source Index: https://keyv.org/llms.txt ## Documentation ### Getting Started URL: https://keyv.org/docs/ Description: Install Keyv, store a value in seconds, and learn who uses it and what it can do. # Getting Started Keyv is a small, Promise-based key-value store. Use it as an in-memory TTL cache or point it at Redis, SQLite, Postgres, MongoDB, and other backends through storage adapters. The application API stays the same when you change the store. ```js import Keyv from "keyv"; const keyv = new Keyv(); await keyv.set("user:1", { name: "Ada" }, 60_000); await keyv.get("user:1"); // { name: 'Ada' } ``` Keys are strings. Values can be any JSON-serializable type, plus `Buffer` and `BigInt` with the built-in serializer. ## Quick Start Install the core package. By default everything lives in memory. ```bash npm install keyv ``` ```js import Keyv from "keyv"; const keyv = new Keyv(); await keyv.set("foo", "bar"); await keyv.get("foo"); // 'bar' await keyv.has("foo"); // true await keyv.delete("foo"); // true ``` Add a storage adapter when you want the data to survive process restarts: ```bash npm install @keyv/redis ``` ```js import Keyv from "keyv"; import KeyvRedis from "@keyv/redis"; const keyv = new Keyv(new KeyvRedis("redis://localhost:6379")); keyv.on("error", (error) => console.error("Keyv error", error)); await keyv.set("session:abc", { userId: 42 }, 3_600_000); ``` You can also pass options as the first argument, or pass the adapter plus options: ```js const keyv = new Keyv({ store: new KeyvRedis("redis://localhost:6379"), namespace: "cache", ttl: 60_000, }); ``` See [Options](/docs/options/) for the full constructor surface, and [Storage Adapters](/docs/storage-adapters/overview/) for every official backend. ## Who Uses Keyv Keyv is the storage layer behind several widely used caching stacks in the Node.js ecosystem: | Project | How it uses Keyv | | --- | --- | | [Cacheable](https://cacheable.org) | Layered L1/L2 caching built on Keyv stores | | [cache-manager](https://www.npmjs.com/package/cache-manager) | Multi-store cache abstraction for services | | [NestJS](https://docs.nestjs.com/techniques/caching) | Caching via `@nestjs/cache-manager` | | **got / cacheable-request** | RFC-compliant HTTP response caching | Thousands of npm packages depend on Keyv directly or through those libraries. If you are embedding Keyv inside your own module, expose a `cache` / `store` option and set a [namespace](/docs/namespaces/) so `.clear()` cannot wipe unrelated data. ## Features ### Storage adapters Official adapters wrap Redis, Valkey, MongoDB, SQLite, PostgreSQL, MySQL, Etcd, Memcache, DynamoDB, and Cloudflare KV. Pass any of them as `store`. See [Storage Adapters](/docs/storage-adapters/overview/). **Built-in adapters** ship in the `keyv` package: - **`KeyvMemoryAdapter`** — the default. Wraps `Map`, [`quick-lru`](https://github.com/sindresorhus/quick-lru), [`lru.min`](https://github.com/wellwelwel/lru.min), or any Map-like object. Adds namespacing, TTL, and batch methods. See [Using Map and LRU](/docs/using-map-and-lru/). - **`KeyvBridgeAdapter`** — wraps legacy async adapters and async Map-like stores so they work with the v6 contract. See [Legacy Storage Adapters](/docs/legacy-storage-adapters/). You can also bring [your own adapter](/docs/storage-adapters/overview/#build-your-own) or use a [third-party adapter](/docs/storage-adapters/third-party/). ### Serialization The built-in `KeyvJsonSerializer` is on by default. It round-trips JSON types plus `Buffer` and `BigInt`. Official alternatives: - [`@keyv/serialize-superjson`](/docs/serialization/superjson/) — `Date`, `Map`, `Set`, `RegExp`, `URL`, `Error` - [`@keyv/serialize-msgpackr`](/docs/serialization/msgpackr/) — compact binary MessagePack Disable serialization for in-memory objects with `{ serialization: false }`. Compression and encryption require a serializer. See [Encode and Decode](/docs/encode-and-decode/). ### Sanitization Enable `{ sanitize: { keys: true, namespace: true } }` to strip SQL comments, Mongo operators, path traversal, and control characters from keys and namespaces. Harmless characters such as quotes pass through. See [Sanitization](/docs/sanitization/). ### Encryption Pass a `KeyvEncryptionAdapter` (`encrypt` / `decrypt`) via the `encryption` option. Official packages: - [`@keyv/encrypt-node`](/docs/encryption/encrypt-node/) — Node.js `crypto` (AES-GCM, AES-CCM, ChaCha20-Poly1305) - [`@keyv/encrypt-web`](/docs/encryption/encrypt-web/) — Web Crypto API for browsers, Workers, and Deno Encryption runs on the serialized (and optionally compressed) string. See [Encode and Decode](/docs/encode-and-decode/). ### Everything else - **TTL** — default on the instance, override per `set()` - **Namespaces** — isolate keys that share a backend - **Hooks** — `before:*` / `after:*` on every operation - **Events, stats, and telemetry** — `error` events, `stat:hit` / `stat:miss`, and optional `eventLogger` - **Runtimes** — Node.js, Bun, and browsers ## Type-safe Usage Pass a generic on the instance, or on individual `get` / `set` calls: ```ts const numbers = new Keyv(); await numbers.set("count", 3); const value = await numbers.get("count"); // number | undefined const keyv = new Keyv(); await keyv.set("name", "Ada"); const name = await keyv.get("name"); ``` ## Next Steps - [Options](/docs/options/) and [Properties](/docs/properties/) - [Methods](/docs/methods/) - [Storage Adapters](/docs/storage-adapters/overview/) - [v5 → v6 Migration](/docs/migration/v5-to-v6/) if you are upgrading - Archived [v5 documentation](/v5/) ### Options URL: https://keyv.org/docs/options/ Description: Constructor options for Keyv — store, namespace, TTL, serialization, compression, encryption, stats, and more. # Options Create a Keyv instance with `new Keyv(store?, options?)` or `new Keyv(options)`. ```js import Keyv from "keyv"; import KeyvRedis from "@keyv/redis"; const keyv = new Keyv(new KeyvRedis("redis://localhost:6379"), { namespace: "cache", ttl: 60_000, }); ``` The first argument can be a storage adapter **or** an options object. Extra fields you pass are not forwarded into the adapter — configure the adapter itself, then pass the instance as `store`. ## `store` Type: `KeyvStorageAdapter | Map | Map-like` Default: in-memory `Map` wrapped by `KeyvMemoryAdapter` The storage backend. Official adapters, a `Map`, an LRU, or any object Keyv can detect. See [Storage Adapters](/docs/storage-adapters/overview/) and [Using Map and LRU](/docs/using-map-and-lru/). ```js const keyv = new Keyv({ store: new Map() }); ``` If the value is not a usable store, Keyv emits an `error` and falls back to `KeyvMemoryAdapter` with a `Map`. ## `namespace` Type: `string` Default: `undefined` Namespace for this instance. Keyv assigns it on the storage adapter so keys from different instances can share a backend. When omitted, Keyv keeps the namespace set on the adapter, if any. See [Namespaces](/docs/namespaces/). ## `ttl` Type: `number` (milliseconds) Default: `undefined` (no expiry) Default time-to-live for `set()`. A per-call `ttl` overrides this. `0` and negative values are treated as no TTL. ## `serialization` Type: `KeyvSerializationAdapter | false` Default: `KeyvJsonSerializer` (built-in) Object with `stringify` and `parse`. Set to `false` to store raw objects (in-memory only; compression is skipped, and with an encryption adapter set, writes fail with an error). See [Encode and Decode](/docs/encode-and-decode/). ```js import { superJsonSerializer } from "@keyv/serialize-superjson"; const keyv = new Keyv({ serialization: superJsonSerializer }); ``` ## `compression` Type: `KeyvCompressionAdapter` Default: `undefined` Adapter with `compress` and `decompress`. Requires serialization (the default is enough). See [Compression](/docs/compression/overview/). ```js import KeyvGzip from "@keyv/compress-gzip"; const keyv = new Keyv({ compression: new KeyvGzip() }); ``` ## `encryption` Type: `KeyvEncryptionAdapter` Default: `undefined` Adapter with `encrypt` and `decrypt`. Runs after serialize (and optional compress). With `serialization: false`, writes fail with an error instead of storing values unencrypted. See [Encryption](/docs/encryption/overview/). ```js import KeyvEncryptNode from "@keyv/encrypt-node"; const keyv = new Keyv({ encryption: new KeyvEncryptNode({ key: process.env.KEYV_SECRET }), }); ``` ## `sanitize` Type: `KeyvSanitizeOptions` Default: disabled Strip dangerous patterns from keys and namespaces. Set `keys` and `namespace` to `true` to enable every category on both targets. See [Sanitization](/docs/sanitization/). ```js const keyv = new Keyv({ sanitize: { keys: { sql: true, mongo: false }, namespace: true }, }); ``` ## `stats` Type: `boolean` Default: `false` Subscribe `KeyvStats` to telemetry events (`stat:hit`, `stat:miss`, `stat:set`, `stat:delete`, `stat:error`). See [Statistics](/docs/statistics/). ```js const keyv = new Keyv({ stats: true }); ``` ## `checkExpired` Type: `boolean` Default: `true` When `true`, Keyv also checks the absolute `expires` in the stored envelope on `get` / `getMany` / `has` / `hasMany`, and deletes expired rows it finds. That keeps reads millisecond-precise on backends whose native TTL is coarse (Memcached seconds) or lazily swept (DynamoDB, Mongo TTL indexes). Set `false` to trust the adapter alone and skip the extra decode on reads. ```js const keyv = new Keyv({ checkExpired: false }); ``` ## Constructor overloads ```ts new Keyv(); new Keyv(options); new Keyv(store); new Keyv(store, options); ``` `store` is detected by looking for a `.get` method. Anything else is treated as `options`. ### Properties URL: https://keyv.org/docs/properties/ Description: Instance properties on Keyv — store, namespace, TTL, serialization, compression, encryption, stats, sanitize, and more. # Properties Every constructor option is also a live property. Changing a property updates the running instance (and, for `namespace`, the storage adapter). ## `.store` Type: `KeyvStorageAdapter` Default: `KeyvMemoryAdapter` wrapping a `Map` Get or replace the storage adapter. Setting it resolves Map-like and legacy stores, forwards `'error'` events, and applies Keyv's namespace. When Keyv has no namespace, the new adapter keeps its own. ```js import KeyvSqlite from "@keyv/sqlite"; const keyv = new Keyv(); keyv.store = new KeyvSqlite("sqlite://./cache.sqlite"); ``` ## `.namespace` Type: `string | undefined` Default: `undefined` When set, Keyv sanitizes it (if sanitization is on) and writes it to `store.namespace`. Setting `undefined` stops namespacing. When Keyv has no namespace of its own, this returns the adapter's. See [Namespaces](/docs/namespaces/). ```js const keyv = new Keyv({ namespace: "users" }); console.log(keyv.namespace); // 'users' keyv.namespace = undefined; ``` ## `.ttl` Type: `number | undefined` Default: `undefined` Default TTL in milliseconds. `0` and negative values become `undefined` (never expires). Override per call with `set(key, value, ttl)`. ```js const keyv = new Keyv({ ttl: 5000 }); keyv.ttl = undefined; ``` ## `.serialization` Type: `KeyvSerializationAdapter | undefined` `false` in the constructor becomes `undefined` on the property (serialization off). See [Encode and Decode](/docs/encode-and-decode/). ```js const keyv = new Keyv(); keyv.serialization; // KeyvJsonSerializer keyv.serialization = false; // disable ``` ## `.compression` Type: `KeyvCompressionAdapter | undefined` Default: `undefined` ```js import KeyvGzip from "@keyv/compress-gzip"; const keyv = new Keyv(); keyv.compression = new KeyvGzip(); ``` ## `.encryption` Type: `KeyvEncryptionAdapter | undefined` Default: `undefined` ```js keyv.encryption = { encrypt: async (data) => Buffer.from(data).toString("base64"), decrypt: async (data) => Buffer.from(data, "base64").toString("utf8"), }; ``` ## `.checkExpired` Type: `boolean` Default: `true` Read-only after construction. Configured only via the `checkExpired` option. See [Options](/docs/options/#checkexpired). ```js const keyv = new Keyv(); keyv.checkExpired; // true const trusting = new Keyv({ checkExpired: false }); trusting.checkExpired; // false ``` ## `.stats` Type: `KeyvStats` Always present. Tracking is off until you pass `{ stats: true }` or set `keyv.stats.enabled = true`. See [Statistics](/docs/statistics/). ```js const keyv = new Keyv({ stats: true }); keyv.stats.hits; keyv.stats.reset(); ``` ## `.sanitize` Type: `KeyvSanitize` Always present. Disabled until you pass the `sanitize` option. Update it with `updateOptions()` or replace the adapter. See [Sanitization](/docs/sanitization/). ```js import { KeyvSanitize } from "keyv"; keyv.sanitize.updateOptions({ keys: true, namespace: true }); keyv.sanitize = new KeyvSanitize({ keys: true, namespace: false }); ``` ## Inherited from Hookified Keyv extends [Hookified](https://hookified.org), so these are also available: | Property | Purpose | | --- | --- | | `hooks` | `Map` of registered hook handlers | | `eventLogger` | Optional Pino/Winston-style logger; see [Logging & Telemetry](/docs/logging-and-telemetry/) | | `throwOnHookError` | Throw when a hook throws (default `false`) | | `throwOnEmptyListeners` | Throw on `'error'` with no listeners (default `true`) | ### Methods URL: https://keyv.org/docs/methods/ Description: Keyv methods — set, get, delete, has, batch APIs, raw access, iterator, disconnect, encode, and decode. # Methods Keys are always strings. Values can be any type the serializer can handle. Every mutating and reading method is async. ## `.set(key, value, [ttl])` Set a value. Optional `ttl` is relative milliseconds and overrides the instance default. Returns `true` on success, `false` if the key is empty after sanitization, the value is a `symbol`, or the store throws. ```js await keyv.set("foo", "bar"); await keyv.set("foo", "expires", 1000); ``` > [!WARNING] > `symbol` values cannot be serialized. Keyv emits `'error'` with `"symbol cannot be serialized"` and returns `false`. See [Events and Errors](/docs/events-and-errors/). ## `.setMany(entries)` Set many values. Each entry is a `KeyvEntry`: `{ key, value, ttl? }`. Returns `boolean[]`. ```js await keyv.setMany([ { key: "a", value: 1, ttl: 1000 }, { key: "b", value: 2 }, ]); ``` ## `.get(key)` Returns the value, or `undefined` if missing or expired. Passing an array of keys delegates to `.getMany()`. ```js await keyv.get("foo"); // 'bar' | undefined await keyv.get(["a", "b"]); // same as getMany ``` ## `.getMany(keys)` Returns `(Value | undefined)[]` in the same order as `keys`. ```js await keyv.getMany(["a", "missing"]); // [1, undefined] ``` ## `.getRaw(key)` / `.getManyRaw(keys)` Return the stored envelope `{ value, expires? }` instead of unwrapping `.value`. Use this when you need the expiry timestamp or round-trip through `.setRaw()`. ```js await keyv.set("foo", "bar", 60_000); const raw = await keyv.getRaw("foo"); // { value: 'bar', expires: 1710000000000 } ``` ## `.setRaw(key, value)` / `.setManyRaw(entries)` Write a `KeyvValue` envelope yourself. The envelope is still encoded (serialize → compress → encrypt). Derive TTL from `value.expires` (absolute Unix ms). ```js await keyv.setRaw("foo", { value: "bar", expires: Date.now() + 60_000 }); await keyv.setManyRaw([ { key: "a", value: { value: 1 } }, { key: "b", value: { value: 2, expires: Date.now() + 1000 } }, ]); ``` Round-trip: ```js const raw = await keyv.getRaw("foo"); if (raw) { raw.value = "updated"; await keyv.setRaw("foo", raw); } ``` ## `.delete(key)` Delete one key, or pass an array to `.deleteMany()`. Returns `true` if the key existed. ```js await keyv.delete("foo"); ``` ## `.deleteMany(keys)` Returns `boolean[]` — one result per key. ```js await keyv.deleteMany(["a", "b"]); // [true, false] ``` ## `.has(key)` / `.hasMany(keys)` Existence checks. Expired keys count as missing when `checkExpired` is on (default). ```js await keyv.has("foo"); // true await keyv.hasMany(["foo", "missing"]); // [true, false] ``` ## `.clear()` Delete every key in the **current namespace**. Emits `'clear'`. If the store can't limit the delete to the namespace (a `Map`-like store without `keys()`, or an older async store without `iterator()` that doesn't manage its own namespace), nothing is deleted and Keyv emits `'error'`. ```js await keyv.clear(); ``` ## `.disconnect()` Ask the adapter to close connections. Emits `'disconnect'`. Safe to call when the store has no `disconnect()`. ```js await keyv.disconnect(); ``` ## `.iterator()` Async generator of `[key, value]` pairs. Decodes values, skips (and deletes) expired entries when `checkExpired` is on. Yields nothing if the store has no `iterator()`. ```js for await (const [key, value] of keyv.iterator()) { console.log(key, value); } ``` ## `.encode(data)` / `.decode(data)` Public pipeline helpers. `encode` runs serialize → compress → encrypt. `decode` runs the reverse. See [Encode and Decode](/docs/encode-and-decode/). ```js const packed = await keyv.encode({ value: "bar", expires: Date.now() + 1000 }); const envelope = await keyv.decode(packed); ``` ### Events and Errors URL: https://keyv.org/docs/events-and-errors/ Description: Error events, when errors throw, telemetry events, and symbols. # Events and Errors Keyv extends [Hookified](https://hookified.org), which is an `EventEmitter`-compatible event bus. Import the event names from `KeyvEvents` so you do not depend on string literals. ```js import Keyv, { KeyvEvents } from "keyv"; const keyv = new Keyv(); keyv.on(KeyvEvents.ERROR, (error) => { console.error("Keyv error", error); }); ``` ## Event names (`KeyvEvents`) `KeyvEvents` is a **string enum** (`KeyvEvents.ERROR === "error"`). Import the names so you do not depend on magic strings. | Name | Value | When | | --- | --- | --- | | `ERROR` | `'error'` | Store failure, encode/decode failure, invalid store, unserializable value | | `INFO` | `'info'` | Informational messages (available for your own emits and logger routing) | | `WARN` | `'warn'` | Warnings, including Hookified deprecation warnings | | `STAT_HIT` | `'stat:hit'` | Successful `get` / `getRaw` read, including batch variants | | `STAT_MISS` | `'stat:miss'` | Missing or expired `get` / `getRaw` read, including batch variants | | `STAT_SET` | `'stat:set'` | Successful set | | `STAT_DELETE` | `'stat:delete'` | Delete attempted | | `STAT_ERROR` | `'stat:error'` | Operation failed | `clear` and `disconnect` are also emitted (as those method names) when those methods begin, before the corresponding hooks and adapter operation run. ```js keyv.on("clear", () => console.log("namespace cleared")); keyv.on("disconnect", () => console.log("disconnected")); ``` Telemetry payloads are `KeyvTelemetryEvent` objects: ```ts type KeyvTelemetryEvent = { event: string; // 'hit' | 'miss' | 'set' | 'delete' | 'error' key?: string; namespace?: string; timestamp: number; }; ``` See [Logging & Telemetry](/docs/logging-and-telemetry/) and [Statistics](/docs/statistics/). ## Symbols cannot be serialized `JSON.stringify` cannot represent `symbol`. If you `set` a symbol, Keyv emits `'error'` with the string `"symbol cannot be serialized"` and records `stat:error`. With a listener attached, `set` then returns `false`. With none, it rejects. ```js import Keyv, { KeyvEvents } from "keyv"; const keyv = new Keyv(); keyv.on(KeyvEvents.ERROR, (error) => { console.error(error); // 'symbol cannot be serialized' }); const ok = await keyv.set("id", Symbol("id")); console.log(ok); // false ``` The same check runs inside `setMany`. Prefer strings, numbers, or objects as values. ## Error forwarding from the store When you assign a store, Keyv subscribes to the adapter's `'error'` event and re-emits it on the Keyv instance. Connection failures from Redis, Postgres, and others surface as `keyv.on('error', ...)`. An adapter can emit these outside any Keyv call, for example when a Redis connection drops. With no listener attached, such an error is thrown with no call to catch it, which can crash the process, so attach a listener whenever your adapter connects to a server. If the provided store is not a Map-like, async Map, or storage adapter, Keyv emits: ``` Could not use the provided storage adapter, falling back to KeyvMemoryAdapter with Map ``` With a listener attached, Keyv then continues with an in-memory Map. With none, the error is thrown, so passing an unusable store to the constructor throws. Encode/decode failures also emit `'error'` (for example a corrupt compressed payload). With a listener attached, `decode` returns `undefined` after emitting. ## When errors throw Keyv follows the Node.js `EventEmitter` rule. When an operation fails, Keyv emits `'error'`, and whether the operation also throws depends on whether a listener is attached: - **With a listener**, the listener receives the error and the operation returns a fallback value. - **With no listener**, the operation rejects with the error. ```js const keyv = new Keyv(store); // any storage adapter // No listener: a failed call rejects. await keyv.get("key"); // throws if the store fails keyv.on("error", (error) => console.error(error)); await keyv.get("key"); // undefined if the store fails, and the listener receives the error ``` These are the fallback values a failed call returns when a listener is attached: | Method | Returns | | --- | --- | | `get`, `getRaw` | `undefined` | | `getMany`, `getManyRaw` | an array of `undefined` | | `set`, `setRaw`, `delete`, `has` | `false` | | `setMany`, `setManyRaw`, `deleteMany`, `hasMany` | an array of `false` | | `clear`, `disconnect` | `undefined` | | `iterator` | ends the iteration | A failed read looks the same as a missing key, so use the `'error'` events when you need to tell them apart. It emits `stat:error`, not `stat:miss`. To discard errors without logging them, register a no-op listener: ```js keyv.on("error", () => {}); ``` Keyv v5's `throwOnErrors` and `emitErrors` options were removed in v6. See the [v5 to v6 migration guide](/docs/migration/v5-to-v6/#error-handling-changed-and-throwonerrors-was-removed). ## Adapter-level throw options Some adapters have their own flags that control whether the adapter itself rejects or emits `'error'` and returns a fallback value, for example `@keyv/redis` `throwOnConnectError` and `throwOnErrors`. An adapter should do one or the other for a given failure, not both, so Keyv reports the failure once. When the adapter rejects, Keyv handles the failure like any other: it emits `'error'`, then returns a fallback value if a listener is attached or rejects if none is. ### Hooks URL: https://keyv.org/docs/hooks/ Description: before/after hooks for get, set, delete, has, clear, disconnect, and raw APIs. Includes deprecated PRE_/POST_ aliases. # Hooks Every Keyv operation fires a `before:*` hook, then the store call, then an `after:*` hook. Hooks can observe or mutate the payload (for example prefixing keys on `BEFORE_SET`). Register handlers with `onHook()` or `addHook()` from [Hookified](https://hookified.org). Import names from `KeyvHooks`. ```js import Keyv, { KeyvHooks } from "keyv"; const keyv = new Keyv(); keyv.onHook(KeyvHooks.BEFORE_SET, (data) => { console.log(`Setting ${data.key}`); }); ``` `addHook(event, handler)` is the same registration API used in the test suite. ## Hook names (`KeyvHooks`) | Before | After | Operation | | --- | --- | --- | | `BEFORE_SET` (`before:set`) | `AFTER_SET` (`after:set`) | `set` | | `BEFORE_SET_MANY` (`before:setMany`) | `AFTER_SET_MANY` (`after:setMany`) | `setMany` | | `BEFORE_SET_RAW` (`before:setRaw`) | `AFTER_SET_RAW` (`after:setRaw`) | `setRaw` | | `BEFORE_SET_MANY_RAW` (`before:setManyRaw`) | `AFTER_SET_MANY_RAW` (`after:setManyRaw`) | `setManyRaw` | | `BEFORE_GET` (`before:get`) | `AFTER_GET` (`after:get`) | `get` | | `BEFORE_GET_MANY` (`before:getMany`) | `AFTER_GET_MANY` (`after:getMany`) | `getMany` | | `BEFORE_GET_RAW` (`before:getRaw`) | `AFTER_GET_RAW` (`after:getRaw`) | `getRaw` | | `BEFORE_GET_MANY_RAW` (`before:getManyRaw`) | `AFTER_GET_MANY_RAW` (`after:getManyRaw`) | `getManyRaw` | | `BEFORE_DELETE` (`before:delete`) | `AFTER_DELETE` (`after:delete`) | `delete` | | `BEFORE_DELETE_MANY` (`before:deleteMany`) | `AFTER_DELETE_MANY` (`after:deleteMany`) | `deleteMany` | | `BEFORE_HAS` (`before:has`) | `AFTER_HAS` (`after:has`) | `has` | | `BEFORE_HAS_MANY` (`before:hasMany`) | `AFTER_HAS_MANY` (`after:hasMany`) | `hasMany` | | `BEFORE_CLEAR` (`before:clear`) | `AFTER_CLEAR` (`after:clear`) | `clear` | | `BEFORE_DISCONNECT` (`before:disconnect`) | `AFTER_DISCONNECT` (`after:disconnect`) | `disconnect` | ## Mutating `BEFORE_SET` The object passed to `BEFORE_SET` is `{ key, value, ttl }`. Mutations are used for the write. ```js keyv.onHook(KeyvHooks.BEFORE_SET, (data) => { data.key = `prefix-${data.key}`; data.value = { wrapped: data.value }; }); ``` ## Hits and misses `AFTER_GET` and `AFTER_GET_RAW` run on both hits and misses. A miss (missing or expired) passes `undefined` as the value. ```js keyv.onHook(KeyvHooks.AFTER_GET, (data) => { if (data.value === undefined) { console.log("miss", data.key); } else { console.log("hit", data.key, data.value); } }); ``` ## Delete hooks `delete()` accepts a single key or an array (which delegates to `deleteMany`). `BEFORE_DELETE` / `AFTER_DELETE` therefore see either a string or an array. Prefer `BEFORE_DELETE_MANY` / `AFTER_DELETE_MANY` for batch deletes. Keyv still fires the single-key delete hooks from `deleteMany` for backward compatibility. ## Deprecated `PRE_*` / `POST_*` names The v5 names (`PRE_SET` → `"preSet"`, `POST_GET` → `"postGet"`, …) still fire if anything is subscribed to them. Keyv emits deprecation warnings. Use `BEFORE_*` / `AFTER_*` going forward. ```js // works, but deprecated keyv.addHook(KeyvHooks.PRE_SET, () => {}); ``` ## Hook errors `throwOnHookError` defaults to `false`. A throwing hook emits `'error'` instead of failing the Keyv call. Set `keyv.throwOnHookError = true` if a hook failure should fail the operation. ### Namespaces URL: https://keyv.org/docs/namespaces/ Description: Isolate keys that share a backend. Namespace lives on the storage adapter in v6. # Namespaces A namespace isolates one Keyv instance's keys from another when they share a backend. Clearing `users` does not touch `cache`. ```js import Keyv from "keyv"; import KeyvRedis from "@keyv/redis"; const redis = "redis://localhost:6379"; const users = new Keyv(new KeyvRedis(redis), { namespace: "users" }); const cache = new Keyv(new KeyvRedis(redis), { namespace: "cache" }); await users.set("foo", "users"); await cache.set("foo", "cache"); await users.get("foo"); // 'users' await cache.get("foo"); // 'cache' await users.clear(); await users.get("foo"); // undefined await cache.get("foo"); // 'cache' ``` ## How it works in v6 Keyv core does **not** prefix keys itself. It sets `store.namespace`. Official adapters apply that namespace with their own prefixing (Redis `namespace::key`, SQL `WHERE namespace = …`, and so on). You can set the namespace on Keyv or on the adapter: - A namespace passed to Keyv wins. Keyv writes it to the adapter, replacing any namespace the adapter had. - When Keyv has no namespace, it keeps the adapter's and `keyv.namespace` returns it. ```js const store = new KeyvRedis(redis, { namespace: "users" }); const users = new Keyv(store); users.namespace; // 'users' ``` That is why `useKeyPrefix` / `keyPrefix` from v5 are gone. See the [v5 → v6 Migration](/docs/migration/v5-to-v6/) guide. Set or clear the namespace later via the property: ```js keyv.namespace = "tenant-42"; keyv.namespace = undefined; // no isolation ``` If [sanitization](/docs/sanitization/) is enabled, the namespace is cleaned on construct and on the setter. A namespace that Keyv keeps from the adapter is cleaned too. A namespace that cleaning leaves empty becomes `keyv-sanitized`, so the instance still has a namespace of its own. ## Memory and Map stores `KeyvMemoryAdapter` (the default `Map` / LRU wrapper) prefixes keys as `namespace::key` (customizable `namespaceSeparator`). A namespaced `clear()` removes only those keys, which it finds with the underlying store's `keys()` (a standard `Map` has one). A minimal Map-like object without `keys()` can't tell namespaces apart, so a namespaced `clear()` throws instead of wiping the **entire** store. ## Bridge / legacy adapters `KeyvBridgeAdapter` does one of two things: - If the wrapped store already has a `namespace` property (a full adapter), the bridge **propagates** namespace and does not prefix again. When the bridge has no namespace of its own, it keeps the one the store was configured with. - Otherwise it prefixes keys itself so one shared async store can host multiple namespaces. A namespaced `clear()` finds those keys with the store's `iterator()`. A store without one can't tell namespaces apart, so `clear()` throws instead of wiping every namespace. See [Legacy Storage Adapters](/docs/legacy-storage-adapters/). ## Namespaces that share a prefix Most adapters store a key as ``: the memory adapter, the bridge adapter when it prefixes keys itself, Redis, Valkey, Etcd, DynamoDB, Cloudflare KV, and Memcache. The separator is `::` by default, and each of these adapters takes a `namespaceSeparator` option to change it. ```js const store = new KeyvRedis(redis, { namespace: "users", namespaceSeparator: "/" }); await store.set("foo", "bar"); // stored as users/foo ``` A namespace that extends another with the separator isn't kept apart from it: - Clearing or iterating `users` also reaches the entries of `users::archive`, because these adapters find a namespace's entries by its prefix. Memcache is the exception: it clears each namespace on its own and has no iterator. - The two can build the same stored key. `archive::x` in `users` and `x` in `users::archive` are one entry, so writing either replaces the other. Keep the separator out of namespace names when namespaces have to stay apart. With the default `::`, names that contain a single `:`, such as `users:archive`, stay apart from `users`. Valkey's `useSets: true` doesn't change this: it builds keys the same way, and its `iterator()` still finds entries by prefix. SQLite, PostgreSQL, MySQL, and MongoDB keep the namespace in its own column or field, so their namespaces never overlap. A bridge around an adapter that handles its own namespace leaves the keys to that adapter, so it behaves like the adapter it wraps. ## Embedding Keyv in a library Always set a namespace when you wrap Keyv inside another module so callers can `.clear()` without destroying unrelated app data. ```js class AwesomeModule { constructor(opts) { this.cache = new Keyv({ store: typeof opts.cache === "string" ? undefined : opts.cache, namespace: "awesome-module", }); } } ``` ### Encode and Decode URL: https://keyv.org/docs/encode-and-decode/ Description: Serialization, compression, and encryption pipeline. Built-in JSON serializer, SuperJSON, MessagePack, and custom adapters. # Encode and Decode Keyv stores an envelope `{ value, expires? }`, not the raw value. `encode()` turns that envelope into what the adapter persists. `decode()` turns the adapter's bytes back into the envelope. ## Pipeline **On set:** serialize → compress (optional) → encrypt (optional) → store **On get:** store → decrypt (optional) → decompress (optional) → parse → value Compression and encryption operate on the **serialized string**. They only run when a serializer is configured. The built-in `KeyvJsonSerializer` is on by default, so this works out of the box. If you set `serialization: false`, values go to the store as-is and compression is skipped. With an encryption adapter set, writes fail with an error instead, so nothing is stored unencrypted. ```js const packed = await keyv.encode({ value: { n: 1 }, expires: Date.now() + 1000 }); const envelope = await keyv.decode(packed); // { value: { n: 1 }, expires: ... } ``` `decode` returns `undefined` for `null` / `undefined` input, or if decrypt/decompress/parse throws (the error is emitted as `'error'`). ## Built-in JSON serializer `KeyvJsonSerializer` is the default. It uses `JSON.stringify` / `JSON.parse` with extra tags: - `Buffer` / `Uint8Array` → `:base64:...` - `BigInt` → `:bigint:...` - Strings that already start with `:` are escaped so they round-trip In browsers without `Buffer`, it uses `btoa` / `atob`. ```js import Keyv, { KeyvJsonSerializer, jsonSerializer } from "keyv"; const keyv = new Keyv(); // already using KeyvJsonSerializer keyv.serialization = jsonSerializer; // shared instance ``` ## Official serializers | Package | Extra types | | --- | --- | | built-in `KeyvJsonSerializer` | JSON + `Buffer` + `BigInt` | | [`@keyv/serialize-superjson`](/docs/serialization/superjson/) | `Date`, `Map`, `Set`, `RegExp`, `URL`, `Error`, `undefined` | | [`@keyv/serialize-msgpackr`](/docs/serialization/msgpackr/) | `Date`, `Map`, `Set`, `RegExp`, `Error`, `NaN`, `Infinity` (binary) | ```js import { superJsonSerializer } from "@keyv/serialize-superjson"; import { msgpackrSerializer } from "@keyv/serialize-msgpackr"; const withDates = new Keyv({ serialization: superJsonSerializer }); const compact = new Keyv({ serialization: msgpackrSerializer }); ``` ## Custom serializer ```ts interface KeyvSerializationAdapter { stringify: (object: unknown) => string | Promise; parse: (data: string) => T | Promise; } ``` ```js const serializer = { stringify: (value) => JSON.stringify(value), parse: (data) => JSON.parse(data), }; const keyv = new Keyv({ serialization: serializer }); ``` ## Disabling serialization Useful for an in-memory `Map` of objects when you do not need a string payload: ```js const keyv = new Keyv({ store: new Map(), serialization: false }); ``` Do not disable serialization if you use compression, encryption, or a backend that only stores strings. ## Compression and encryption ```js import KeyvGzip from "@keyv/compress-gzip"; import KeyvEncryptNode from "@keyv/encrypt-node"; const keyv = new Keyv({ compression: new KeyvGzip(), encryption: new KeyvEncryptNode({ key: process.env.KEYV_SECRET }), }); ``` See [Compression](/docs/compression/overview/) and [Encryption](/docs/encryption/overview/). ## `decodeWithExpire` Internal helper used by `get` / `has` when `checkExpired` is on. It decodes each row and deletes keys whose `expires` is in the past. You can call it if you are reading raw adapter rows yourself. ### Sanitization URL: https://keyv.org/docs/sanitization/ Description: Strip SQL, Mongo, path-traversal, and control-character patterns from keys and namespaces. # Sanitization Sanitization is **off** by default. When enabled, Keyv strips dangerous *patterns* from keys and namespaces before they reach the store. Harmless characters such as quotes, slashes, and dollar signs in the middle of a string pass through. Results are cached in an LRU (10,000 entries) so repeated keys are cheap. ## Enable it ```js const keyv = new Keyv({ sanitize: { keys: true, namespace: true }, }); await keyv.set("test; DROP TABLE", "value"); // stored as "test DROP TABLE" await keyv.set("user's-data", "value"); // unchanged ``` Omitting `sanitize`, or setting both targets to `false`, leaves keys and namespaces untouched. ## Pattern categories | Category | Patterns stripped | Purpose | | --- | --- | --- | | `sql` | `;` `--` `/*` | SQL injection fragments | | `mongo` | leading `$`, `{$` sequences | MongoDB operator injection | | `escape` | `\0` `\r` `\n` | Null bytes and CRLF | | `path` | `../` `..\` | Path traversal | Stripping repeats until nothing matches, so the characters left around a removed pattern can't form a new one. For example, `..././etc` becomes `etc`, not `../etc`, and `$$where` becomes `where`. ## Targets | Target | Default when enabled | Applies to | | --- | --- | --- | | `keys` | all categories | Every key-accepting method | | `namespace` | `true` | Constructor and `namespace` setter | Methods that sanitize keys: `get`, `set`, `delete`, `has`, `getMany`, `setMany`, `deleteMany`, `hasMany`, `getRaw`, `getManyRaw`, `setRaw`, `setManyRaw`. Empty keys after sanitization cause `set` / `delete` / `has` / `get` to no-op (`false` / `undefined`). The batch methods skip them the same way: an empty key never reaches the store, and its position in the result holds `undefined` or `false`. A namespace that is empty after sanitization, such as `$$` or `;`, becomes `keyv-sanitized`. An empty namespace would turn namespacing off, mixing the instance's keys with unrelated ones and letting `clear()` remove them. ## Granular control ```js const keyv = new Keyv({ sanitize: { keys: { sql: true, mongo: false }, namespace: { path: true, sql: false }, }, }); ``` Disable namespace sanitization only: ```js const keyv = new Keyv({ sanitize: { keys: true, namespace: false }, }); ``` ## Change at runtime ```js import { KeyvSanitize } from "keyv"; keyv.sanitize.updateOptions({ keys: true, namespace: true }); keyv.sanitize.updateOptions({ keys: { sql: true, mongo: false } }); keyv.sanitize = new KeyvSanitize({ keys: true, namespace: true }); ``` `keyv.sanitize.enabled` is `true` when any category is on for keys or namespace. Sanitization is not a substitute for parameterized queries or adapter-level escaping. It is a Defense-in-Depth filter for untrusted key material. See [SECURITY.md](https://github.com/jaredwray/keyv/blob/main/SECURITY.md) in the repository. ### Using Map and LRU URL: https://keyv.org/docs/using-map-and-lru/ Description: Use Map, quick-lru, lru.min, or BigMap as the Keyv store. How KeyvMemoryAdapter wraps them. # Using Map and LRU Any object that looks like a `Map` — `get`, `set`, `delete`, `clear`, `has` as **synchronous** methods — is wrapped in `KeyvMemoryAdapter`. That is the default when you call `new Keyv()` with no store. ```js import Keyv from "keyv"; const keyv = new Keyv(); // KeyvMemoryAdapter(new Map()) await keyv.set("foo", "bar"); ``` ## Pass a `Map` yourself ```js const store = new Map(); const keyv = new Keyv({ store }); ``` You rarely need `new KeyvMemoryAdapter(...)` yourself. Keyv does it when it detects `store: "mapLike"`. Set `namespace` on the **Keyv** options or on the adapter. When both are set, Keyv's wins. ```js import Keyv, { KeyvMemoryAdapter } from "keyv"; const keyv = new Keyv({ store: new KeyvMemoryAdapter(new Map()), namespace: "cache", }); ``` ## LRU caches [`quick-lru`](https://github.com/sindresorhus/quick-lru) and [`lru.min`](https://github.com/wellwelwel/lru.min) implement the Map API. Use them to bound memory. ```js import Keyv from "keyv"; import QuickLRU from "quick-lru"; const lru = new QuickLRU({ maxSize: 1000 }); const keyv = new Keyv({ store: lru }); ``` When the underlying store's `set` accepts a TTL argument, the memory adapter also passes a **relative** duration derived from the absolute `expires`, so the LRU can evict on its own as well as via Keyv's expiry check. ## What `KeyvMemoryAdapter` adds - **Namespace prefixing** — `namespace` + `namespaceSeparator` (default `::`). Namespaced `clear()` deletes only that prefix, using the store's `keys()`. Without `keys()` it throws rather than wipe the whole store. - **TTL** — keeps `{ value, expires }` beside the payload so `get` / `has` / `iterator` can evict lazily without decoding. - **Batch + iterator** — `getMany`, `setMany`, `hasMany`, `deleteMany`, and `iterator()` when the store has `entries()`. - **v6 contract** — `capabilities.expires === true`, so Keyv passes absolute `expires` directly. This wrapper is separate from the `{ value, expires }` envelope Keyv core serializes. Custom serializers still see `expires` inside the payload. ## Scaling past Map limits JavaScript `Map` is practical up to about **16.7 million** entries. [`@keyv/bigmap`](/docs/storage-adapters/bigmap/) distributes keys across many inner Maps. ```js import { createKeyv } from "@keyv/bigmap"; const keyv = createKeyv(); await keyv.set("user:1", { name: "Ada" }, 60_000); ``` ## Async Map-like stores If `get` / `set` / `delete` / `clear` are **async**, Keyv uses `KeyvBridgeAdapter` instead of the memory adapter. The bridge converts absolute `expires` back to a relative `ttl` for `set(key, value, ttl)`. A Promise-wrapped `Map` that ignores that third argument will not evict by itself — enable `checkExpired` (default) so reads still filter expired rows. See [Legacy Storage Adapters](/docs/legacy-storage-adapters/). ### Statistics URL: https://keyv.org/docs/statistics/ Description: Enable KeyvStats for hits, misses, sets, deletes, errors, and per-key LRU frequency maps. # Statistics `KeyvStats` listens to [telemetry events](/docs/logging-and-telemetry/) and counts them. Tracking is **off** until you turn it on. ```js const keyv = new Keyv({ stats: true }); await keyv.set("foo", "bar"); await keyv.get("foo"); await keyv.get("missing"); await keyv.delete("foo"); console.log(keyv.stats.hits); // 1 console.log(keyv.stats.misses); // 1 console.log(keyv.stats.sets); // 1 console.log(keyv.stats.deletes); // 1 ``` ## Counters | Property | Meaning | | --- | --- | | `hits` | Successful retrievals | | `misses` | Missing or expired keys | | `sets` | Successful sets | | `deletes` | Deletes | | `errors` | Failed operations | ## Per-key LRU maps Each event type has a `Map` capped at `maxEntries` (default **1000**). Keys are `namespace::key` when a namespace is set, otherwise just `key`. | Map | Event | | --- | --- | | `hitKeys` | `stat:hit` | | `missKeys` | `stat:miss` | | `setKeys` | `stat:set` | | `deleteKeys` | `stat:delete` | | `errorKeys` | `stat:error` | ```js console.log(keyv.stats.hitKeys.get("foo")); // 1 console.log(keyv.stats.missKeys.get("missing")); // 1 ``` When a map is full, the oldest key is evicted (LRU via insert order). ## Enable, disable, reset ```js const keyv = new Keyv({ stats: false }); keyv.stats.enabled = true; // subscribe keyv.stats.enabled = false; // unsubscribe keyv.stats.reset(); // counters and maps back to empty keyv.stats.maxEntries = 500; ``` Disabling unsubscribes listeners but keeps the last emitter around so re-enabling works. ## Standalone `KeyvStats` You can point stats at any Hookified/EventEmitter that emits `stat:*` events: ```js import { KeyvStats } from "keyv"; const stats = new KeyvStats({ enabled: true, maxEntries: 500, emitter: keyv }); ``` If `enabled` is `false` but `emitter` is passed, the emitter is stored and used when you later set `enabled = true`. ### Logging & Telemetry URL: https://keyv.org/docs/logging-and-telemetry/ Description: stat:* telemetry events, eventLogger (Pino/Winston), and how stats subscribe to the same events. # Logging & Telemetry Keyv emits structured telemetry for reads, writes, deletes, and operation errors, and can pipe events through Hookified's `eventLogger` (Pino, Winston, or any logger with `info` / `warn` / `error` / …). ## Telemetry events Emitted as `KeyvEvents` (see [Events and Errors](/docs/events-and-errors/)): | Event | Payload | | --- | --- | | `stat:hit` | `{ event: 'hit', key, namespace, timestamp }` | | `stat:miss` | `{ event: 'miss', key, namespace, timestamp }` | | `stat:set` | `{ event: 'set', key, namespace, timestamp }` | | `stat:delete` | `{ event: 'delete', key, namespace, timestamp }` | | `stat:error` | `{ event: 'error', key, namespace, timestamp }` | Batch read, write, and delete methods emit **one event per key**. Successful `has()` and `hasMany()` probes do not emit `stat:hit` or `stat:miss`; failures still emit `stat:error`. A read that fails emits `stat:error` and no `stat:miss`. ```js import Keyv, { KeyvEvents } from "keyv"; const keyv = new Keyv(); keyv.on(KeyvEvents.STAT_HIT, (event) => { console.log("hit", event.key, event.namespace, event.timestamp); }); ``` `KeyvStats` is a ready-made subscriber for these events. See [Statistics](/docs/statistics/). ## `eventLogger` Keyv extends Hookified, so you can attach a logger. Hookified maps event names to log levels: | Emitted name | Logger method | | --- | --- | | `error` | `error()` | | `warn` | `warn()` | | `debug` | `debug()` | | `trace` | `trace()` | | `fatal` | `fatal()` | | anything else (including `stat:hit`) | `info()` | ```js import pino from "pino"; const keyv = new Keyv(); keyv.eventLogger = pino({ level: "info" }); keyv.on("error", () => {}); // keep empty-listener throws from firing await keyv.set("foo", "bar"); ``` The constructor does not take `eventLogger`; set the property after `new Keyv()`. Remove it with `keyv.eventLogger = undefined`. ## Custom metrics Subscribe to `stat:*` yourself to export Prometheus counters, OpenTelemetry spans, or logs without enabling `KeyvStats`: ```js keyv.on("stat:hit", ({ key, namespace }) => { metrics.increment("cache_hit", { key, namespace }); }); keyv.on("stat:miss", ({ key }) => { metrics.increment("cache_miss", { key }); }); ``` ## Deprecation warnings Using v5 hook names (`preSet`, …) emits `'warn'` and, if configured, `eventLogger.warn()`. Prefer `KeyvHooks.BEFORE_*` / `AFTER_*`. See [Hooks](/docs/hooks/). ### Detect Capabilities URL: https://keyv.org/docs/detect-capabilities/ Description: detectKeyv, detectKeyvStorage, compression, serialization, encryption, and keyvStorageCapability. # Detect Capabilities Keyv exports helpers that inspect an object and report which methods exist, whether they are sync or async, and whether the object is a compatible Keyv instance, store, compressor, serializer, or encryptor. ```ts import { detectKeyv, detectKeyvStorage, detectKeyvCompression, detectKeyvSerialization, detectKeyvEncryption, keyvStorageCapability, } from "keyv"; ``` Every `methods` entry is `{ exists: boolean, methodType: "sync" | "async" | "none" }`. ## `detectKeyv(obj)` Returns `{ compatible, methods, properties }`. `compatible` is `true` only when **all** Keyv methods and the `hooks` / `stats` properties are present. ```js const result = detectKeyv(new Keyv()); result.compatible; // true result.methods.get.methodType; // 'async' result.properties.hooks; // true result.properties.stats; // true const partial = detectKeyv(new Map()); partial.compatible; // false partial.methods.get.exists; // true ``` Methods checked: `get`, `set`, `delete`, `clear`, `has`, `getMany`, `setMany`, `deleteMany`, `hasMany`, `disconnect`, `getRaw`, `getManyRaw`, `setRaw`, `setManyRaw`, `iterator`. ## `detectKeyvStorage(obj)` Returns `{ compatible, store, methods, expires? }`. `store` is one of: | Value | Meaning | | --- | --- | | `"keyvStorage"` | Full async adapter (`get`, `set`, `delete`, `clear`, `has`, `setMany`, `deleteMany`, `hasMany`) | | `"mapLike"` | Sync `get`, `set`, `delete`, `has` (a `Map`) | | `"asyncMap"` | Async `get`, `set`, `delete`, `clear` | | `"none"` | Not a usable store | ```js detectKeyvStorage(new Map()); // { compatible: true, store: 'mapLike', methods: { get: { exists: true, methodType: 'sync' }, ... } } ``` Keyv uses this in `resolveStore()` to pick `KeyvMemoryAdapter` vs `KeyvBridgeAdapter`. `methodType` is `"async"` only for native `async` functions, so for a `"mapLike"` store that isn't a `Map`, `resolveStore()` also calls `has` once. If it returns a promise, the store goes to `KeyvBridgeAdapter`. ## `keyvStorageCapability(adapter)` Build the full capability object for a v6 adapter, including `expires: true`. Expose it as a `capabilities` getter so Keyv passes **absolute** `expires` instead of wrapping you in the bridge. ```ts import { keyvStorageCapability, type KeyvStorageAdapter } from "keyv"; class MyAdapter { get capabilities() { return keyvStorageCapability(this); } async set(key, value, expires) { /* expires is Unix ms */ } } ``` Declaring `expires: true` means you should enforce expiry (native TTL and/or a read-side check). Keyv still double-checks on read when `checkExpired` is `true`. Validate with `@keyv/test-suite` `storageTtlTests`. ## Compression, serialization, encryption ```js detectKeyvCompression({ compress: (d) => d, decompress: (d) => d }); // { compatible: true, methods: { compress, decompress } } detectKeyvSerialization(JSON); // { compatible: true, methods: { stringify, parse } } detectKeyvEncryption({ encrypt: (d) => d, decrypt: (d) => d }); // { compatible: true, methods: { encrypt, decrypt } } ``` `compatible` is `true` when both methods in the pair exist. Early v6 pre-release docs called these helpers `isKeyv`, `isKeyvStorage` and so on. They were renamed to `detect*` during v6 development. No published v5 release exported the `isKeyv*` names, so v5 code has nothing to rename. See the [v5 → v6 Migration](/docs/migration/v5-to-v6/) guide. ### Legacy Storage Adapters URL: https://keyv.org/docs/legacy-storage-adapters/ Description: How KeyvBridgeAdapter wraps v5 relative-TTL adapters and async Map-like stores. # Legacy Storage Adapters v6 storage adapters accept an **absolute** `expires` timestamp (Unix ms) on `set` / `setMany`. Pre-v6 adapters took a **relative** `ttl`. You do not need to rewrite those adapters: Keyv wraps them in `KeyvBridgeAdapter`. The public API is unchanged. `keyv.set(key, value, ttl)` is still relative milliseconds. ## When the bridge is used Keyv looks at the store in this order: 1. `store.capabilities.expires === true` → use the adapter as-is (v6 contract). 2. Full async adapter **without** that flag → `KeyvBridgeAdapter` (legacy relative TTL). 3. Map-like, with methods that aren't native `async` functions → `KeyvMemoryAdapter`. If the store isn't a `Map`, Keyv first calls its `has` once, and if that returns a promise the store goes to `KeyvBridgeAdapter` instead. That covers adapters compiled to an older target and methods written without `async`. 4. Async Map-like → `KeyvBridgeAdapter`. 5. Anything else → `'error'` and fall back to `KeyvMemoryAdapter(new Map())`. ```js import Keyv, { KeyvBridgeAdapter } from "keyv"; const keyv = new Keyv({ store: myLegacyAdapter }); // equivalent to: const explicit = new Keyv({ store: new KeyvBridgeAdapter(myAsyncStore), namespace: "cache", }); ``` A `namespace` on the Keyv options is applied to the adapter. Without one, Keyv keeps the namespace the adapter was configured with. ## What the bridge does - **Converts expiry** — absolute `expires` → relative `ttl` for the wrapped `set`. If the deadline is already past, it **deletes** instead of writing. - **Delegates batch methods** — `getMany`, `setMany`, `has`, `hasMany`, `deleteMany`, `iterator`, `disconnect` when present; otherwise loops over single-key methods. - **Namespaces** — if the store has a `namespace` property, the bridge assigns it and does not prefix keys (avoids double-prefixing). When the bridge has no namespace, the store keeps its own. Otherwise the bridge prefixes `namespace::key` (set the separator with `namespaceSeparator`), and a namespaced `clear()` finds those keys with the store's `iterator()`. A store without `iterator()` can't tell namespaces apart, so `clear()` throws instead of wiping every namespace. - **Forwards `'error'`** from the wrapped store onto the bridge (and then onto Keyv). ## Writing a v6 adapter instead Prefer declaring the new contract so you skip the conversion and never parse encoded values to recover TTL (that used to fail under compression, encryption, or non-JSON serializers): ```ts import { keyvStorageCapability, type KeyvStorageEntry } from "keyv"; class MyAdapter { get capabilities() { return keyvStorageCapability(this); } async set(key, value, expires) { // expires is Unix ms, or undefined } async setMany(entries: KeyvStorageEntry[]) { // each entry has absolute expires } } ``` See [Storage Adapters](/docs/storage-adapters/overview/) and [Detect Capabilities](/docs/detect-capabilities/). ## Third-party adapters Community adapters that have not declared `capabilities.expires` keep working through the bridge. You can still pass `{ store: communityAdapter }`. When you maintain an adapter, upgrading to the v6 contract is recommended. The [third-party list](/docs/storage-adapters/third-party/) has community backends and a walkthrough for implementing `KeyvStorageAdapter`. ### Browser, Node, and Bun Support URL: https://keyv.org/docs/browser-node-and-bun/ Description: Runtime support for Node.js, Bun, and browsers. Engines, Web Crypto, and what to install where. # Browser, Node, and Bun Support ## Node.js The published `engines` field is **Node.js 22.19+** (the current maintenance LTS line and newer). Official adapters follow the same floor. That is a [versioning](/docs/migration/versioning/) contract: we do not raise the Node floor on an already-released major. ```bash npm install keyv ``` Core Keyv has one runtime dependency: [hookified](https://hookified.org). The JSON serializer uses `Buffer` when present and `btoa` / `atob` otherwise. Use [`@keyv/encrypt-node`](/docs/encryption/encrypt-node/) for `crypto` ciphers in Node. ## Bun We test Keyv on [Bun](https://bun.sh/). The default target is still Node.js. If something breaks on Bun, [open an issue](https://github.com/jaredwray/keyv/issues). SQLite's optional `bun:sqlite` driver is the fastest in the [SQLite benchmarks](/docs/storage-adapters/sqlite/#benchmarks) when you are already on Bun. ## Browsers Keyv's core source does not import Node built-ins. The in-memory store, serializer, hooks, stats, sanitization, and Web Crypto encryption work in browsers (and Cloudflare Workers / Deno) after your bundler includes the package. ```js import Keyv from "keyv"; const keyv = new Keyv({ store: new Map() }); await keyv.set("foo", "bar"); ``` Use [`@keyv/encrypt-web`](/docs/encryption/encrypt-web/) for `crypto.subtle`. Use [`@keyv/cloudflare-kv`](/docs/storage-adapters/cloudflare-kv/) inside Workers (`bind` mode) or from Node via the REST API. Browser storage (localStorage, IndexedDB) is available through [community adapters](/docs/storage-adapters/third-party/) such as `keyv-browser`. > [!NOTE] > Most official *database* adapters (Redis, Postgres, Mongo, …) expect a Node-like runtime and native clients. In the browser, stick to `Map` / LRU, BigMap, or a browser/Worker-safe adapter. ## Serialization in the browser `KeyvJsonSerializer` round-trips `Uint8Array` via base64 without `Buffer`. SuperJSON and msgpackr work wherever their own packages run. ## Tests - Node: `pnpm test` in the monorepo - Bun: `.github/workflows/bun-test.yaml` - Browser: static "no Node builtin imports" checks plus happy-dom runtime tests in `core/keyv` ### Test Suite URL: https://keyv.org/docs/test-suite/ # @keyv/test-suite [keyv](https://github.com/jaredwray/keyv) > Test suite for Keyv API compliance [![build](https://github.com/jaredwray/keyv/actions/workflows/tests.yaml/badge.svg)](https://github.com/jaredwray/keyv/actions/workflows/tests.yaml) [![codecov](https://codecov.io/gh/jaredwray/keyv/branch/main/graph/badge.svg?token=bRzR3RyOXZ)](https://codecov.io/gh/jaredwray/keyv) [![npm](https://img.shields.io/npm/v/@keyv/test-suite.svg)](https://www.npmjs.com/package/@keyv/test-suite) [![npm](https://img.shields.io/npm/dm/@keyv/test-suite)](https://npmjs.com/package/@keyv/test-suite) Complete [Vitest](https://vitest.dev/) test suite to test a [Keyv](https://github.com/jaredwray/keyv) storage adapter for API compliance. ## Usage ### Install Install `vitest`, `keyv` and `@keyv/test-suite` as development dependencies. ```shell npm install --save-dev vitest keyv @keyv/test-suite ``` Then update `keyv` and `@keyv/test-suite` versions to `*` in `package.json` to ensure you're always testing against the latest version. ### Create Test File `test.js` ```js import { keyvTestSuite, storageTestSuite } from '@keyv/test-suite'; import { Keyv } from 'keyv'; import { test } from 'vitest'; import KeyvStore from './src/index.js'; const store = () => new KeyvStore(); keyvTestSuite(test, Keyv, store); storageTestSuite(test, store); ``` Where `KeyvStore` is your storage adapter. `keyvTestSuite` tests the adapter through a `Keyv` instance, and `storageTestSuite` tests it directly (see [Storage Adapter Tests](#storage-adapter-tests)). If your adapter implements `iterator()`, also import and call `keyvIteratorTests(test, Keyv, store)`. Set your test script in `package.json` to `vitest`. ```json "scripts": { "test": "vitest" } ``` ## Example for Storage Adapters Take a look at [keyv/redis](https://github.com/jaredwray/keyv/tree/main/storage/redis) for an example of an existing storage adapter using `@keyv/test-suite`. ## Storage Adapter Tests To test a storage adapter directly (without the `Keyv` wrapper), use `storageTestSuite`. It runs basic CRUD, batch, iterator, TTL, namespace, and disconnect tests against the adapter: ```js import { it } from 'vitest'; import { storageTestSuite } from '@keyv/test-suite'; import KeyvStore from './src/index.js'; const store = () => new KeyvStore(); storageTestSuite(it, store); ``` ### Storage Test Options `storageTestSuite` (and the individual `storage*Tests` functions) accept an options object as the third argument: | Option | Type | Default | Description | |--------|------|---------|-------------| | `missingValue` | `undefined \| null` | `undefined` | Value returned by `get()` for missing or expired keys | | `basic` | `boolean` | `true` | Enable basic CRUD tests (`set`/`get`/`delete`/`has`/`clear`) | | `batch` | `boolean` | `true` | Enable batch operation tests (`setMany`/`getMany`/`hasMany`/`deleteMany`) | | `iterator` | `boolean` | `true` | Enable iterator tests | | `ttl` | `boolean` | `true` | Enable TTL tests | | `ttlGranularity` | `'milliseconds' \| 'seconds'` | `'milliseconds'` | TTL granularity used by the TTL tests | | `namespace` | `boolean` | `true` | Enable namespace getter/setter test | | `disconnect` | `boolean` | `true` | Enable disconnect test | ### TTL Granularity By default the TTL tests use sub-second TTL values (300ms TTL with a 600ms expiry wait). Storage backends such as etcd (leases) and DynamoDB only support TTLs at second-level resolution, so they can't honor sub-second TTLs. For those adapters, set `ttlGranularity: 'seconds'` and the TTL tests will use second-scale values instead (1 second TTL with a 3 second expiry wait): ```js import { it } from 'vitest'; import { storageTestSuite } from '@keyv/test-suite'; import KeyvStore from './src/index.js'; const store = () => new KeyvStore(); storageTestSuite(it, store, { ttlGranularity: 'seconds' }); ``` Use `ttl: false` only when the adapter has no storage-level TTL support at all. ## Testing Compression Adapters If you're testing a compression adapter, use `compressionTestSuite` instead of `keyvTestSuite`. It checks `compress`/`decompress` round trips and that the adapter works with a `Keyv` instance. ```js import { compressionTestSuite } from '@keyv/test-suite'; import { it } from 'vitest'; import KeyvGzip from '@keyv/compress-gzip'; compressionTestSuite(it, new KeyvGzip()); ``` ## Migrating from v5 Keyv v5 adapters used `@keyv/test-suite` 2.x. To move to the v6 test suite: - There is no default export. Import `keyvTestSuite` and the other suites by name. - The first argument is Vitest's `test` (or `it`) function. Version 2.x took the whole Vitest module (`import * as test from 'vitest'`). - `keyvNamespaceTest` is now `keyvNamespaceTests`. - `keyvCompresstionTests` is now `compressionTestSuite`. - New suites: `storageTestSuite` tests an adapter directly, without `Keyv`. It runs `storageBasicTests`, `storageBatchTests`, `storageIteratorTests`, `storageTtlTests`, `storageNamespaceTests` and `storageDisconnectTests`, which are also exported. `encryptionTestSuite(test, adapter)` and `serializationTestSuite(test, adapter)` test encryption and serialization adapters. ## License [MIT © Jared Wray](LICENSE) ### Storage Adapters URL: https://keyv.org/docs/storage-adapters/overview/ Description: Official backends, native TTL, how to use an adapter, benchmarks, and writing your own. # Storage Adapters Keyv is a thin API over a store. Performance is almost entirely the backend's; Keyv adds namespacing, encoding, TTL conversion, and a consistent Promise API. ## Official adapters | Backend | Package | Native expiry | Notes | | --- | --- | --- | --- | | Memory / Map / LRU | built-in `KeyvMemoryAdapter` | Yes (lazy) | Default. See [Using Map and LRU](/docs/using-map-and-lru/) | | Redis | [@keyv/redis](/docs/storage-adapters/redis/) | Yes (`PXAT`, `PX` fallback) | Clusters, Sentinel, TLS | | Valkey | [@keyv/valkey](/docs/storage-adapters/valkey/) | Yes (`PXAT`) | Redis-compatible OSS | | MongoDB | [@keyv/mongo](/docs/storage-adapters/mongo/) | TTL index (lazy sweep) | Revalidated in Keyv | | SQLite | [@keyv/sqlite](/docs/storage-adapters/sqlite/) | `expires` column | Node, better-sqlite3, bun:sqlite | | PostgreSQL | [@keyv/postgres](/docs/storage-adapters/postgres/) | `expires` column | | | MySQL | [@keyv/mysql](/docs/storage-adapters/mysql/) | `expires` column | Interval sweeper | | Etcd | [@keyv/etcd](/docs/storage-adapters/etcd/) | Leases | | | Memcache | [@keyv/memcache](/docs/storage-adapters/memcache/) | Seconds (`exptime`) | Keyv `checkExpired` keeps ms precision | | DynamoDB | [@keyv/dynamo](/docs/storage-adapters/dynamo/) | TTL attribute (hours lag) | | | Cloudflare KV | [@keyv/cloudflare-kv](/docs/storage-adapters/cloudflare-kv/) | Client-side + 60s native min | Worker bind or REST | | BigMap | [@keyv/bigmap](/docs/storage-adapters/bigmap/) | Via Keyv | Scale past ~16.7M Map entries | Install the adapter next to `keyv` and pass an instance as `store` (or as the first constructor argument): ```js import Keyv from "keyv"; import KeyvRedis from "@keyv/redis"; const keyv = new Keyv(new KeyvRedis("redis://localhost:6379"), { namespace: "cache", }); ``` Many adapters also export `createKeyv(...)` so you can skip the two-step construct. ## How to use 1. Install `keyv` and the adapter package. 2. Construct the adapter (URI, native client, or options). 3. Pass it to `new Keyv(adapter)` or `{ store }`. 4. Listen for `'error'` on the Keyv instance. 5. Use `set` / `get` / `delete` as usual. TTL on `keyv.set` is **relative milliseconds**; Keyv converts to absolute `expires` for v6 adapters. ```js keyv.on("error", (error) => console.error(error)); await keyv.set("foo", { n: 1 }, 60_000); await keyv.get("foo"); ``` Map-like stores do not need an extra package: ```js import QuickLRU from "quick-lru"; const keyv = new Keyv({ store: new QuickLRU({ maxSize: 1000 }) }); ``` ## Benchmarks Keyv itself is not the bottleneck. Compare **drivers and runtimes**, not Keyv vs Keyv. **SQLite** (in-memory, 10k pre-generated pairs, `set` then `get`). From the [@keyv/sqlite](/docs/storage-adapters/sqlite/#benchmarks) suite — relative numbers, not a guarantee on your machine: | Driver | Summary | ops/sec | | --- | --- | --- | | bun:sqlite | fastest in that run | ~64K | | better-sqlite3 | ~32% slower | ~44K | | node:sqlite | ~33% slower | ~43K | | sqlite3 (legacy) | ~75% slower | ~16K | **BigMap vs `Map`**: native `Map` is faster below the ~16.7 million entry limit. [@keyv/bigmap](/docs/storage-adapters/bigmap/) exists to go beyond that limit by hashing across inner Maps. For Redis, Postgres, and the rest, measure your deployment (network RTT, pipeline, cluster). Use `getMany` / `setMany` when the adapter implements them natively. ## Build your own Implement `KeyvStorageAdapter`. Required: async `get`, `set`, `delete`, `clear`. Optional but recommended: `has`, `getMany`, `setMany`, `deleteMany`, `hasMany`, `iterator`, `disconnect`. v6 `set` takes **absolute** `expires` (Unix ms). Declare it: ```ts import { keyvStorageCapability, type KeyvStorageEntry } from "keyv"; class MyAdapter { get capabilities() { return keyvStorageCapability(this); } async set(key, value, expires) { /* persist value + expires */ return true; } async setMany(entries: KeyvStorageEntry[]) { /* ... */ } } ``` If you omit `capabilities.expires`, Keyv wraps you in `KeyvBridgeAdapter` and converts `expires` back to relative `ttl`. See [Legacy Storage Adapters](/docs/legacy-storage-adapters/). Test with [@keyv/test-suite](/docs/test-suite/): ```js import { keyvTestSuite, storageTestSuite } from "@keyv/test-suite"; import { Keyv } from "keyv"; import { test } from "vitest"; import MyAdapter from "./my-adapter.js"; const store = () => new MyAdapter(); keyvTestSuite(test, Keyv, store); storageTestSuite(test, store); ``` Community adapters are listed on [Third-Party Adapters](/docs/storage-adapters/third-party/). ### @keyv/redis URL: https://keyv.org/docs/storage-adapters/redis/ # @keyv/redis [keyv](https://github.com/jaredwray/keyv) > Redis storage adapter for Keyv [![build](https://github.com/jaredwray/keyv/actions/workflows/tests.yaml/badge.svg)](https://github.com/jaredwray/keyv/actions/workflows/tests.yaml) [![codecov](https://codecov.io/gh/jaredwray/keyv/branch/main/graph/badge.svg?token=bRzR3RyOXZ)](https://codecov.io/gh/jaredwray/keyv) [![npm](https://img.shields.io/npm/v/@keyv/redis.svg)](https://www.npmjs.com/package/@keyv/redis) [![npm](https://img.shields.io/npm/dm/@keyv/redis)](https://npmjs.com/package/@keyv/redis) Redis storage adapter for [Keyv](https://github.com/jaredwray/keyv). # Features * Built on top of [@redis/client](https://npmjs.com/package/@redis/client). * TTL is handled directly by Redis via absolute `PXAT` expiry, with an automatic relative `PX` fallback for servers older than 6.2 (see [Expiration and TTL](#expiration-and-ttl)). * Supports Redis Clusters. * Url connection string support or pass in your Redis Options * Easily add in your own Redis client. * Namespace support for key management. * Unlink as default delete method for performance. * Access to the Redis client for advanced use cases. * Keyv and Redis Libraries are exported for advanced use cases. * `createKeyv` function for easy creation of Keyv instances. * jsDoc comments for easy documentation. * CJS / ESM and TypeScript supported out of the box. # Table of Contents * [Usage](#usage) * [Migrating from v5 to v6](#migrating-from-v5-to-v6) * [Migrating from v4 to v5](#migrating-from-v4-to-v5) * [Using the createKeyv function](#using-the-createkeyv-function) * [Using the createKeyvNonBlocking function](#using-the-createkeyvnonblocking-function) * [Namespaces](#namespaces) * [Fixing Double Prefixing of Keys](#fixing-double-prefixing-of-keys) * [Using Generic Types](#using-generic-types) * [Performance Considerations](#performance-considerations) * [Expiration and TTL](#expiration-and-ttl) * [High Memory Usage on Redis Server](#high-memory-usage-on-redis-server) * [Gracefully Handling Errors and Timeouts](#gracefully-handling-errors-and-timeouts) * [Using Cacheable with Redis](#using-cacheable-with-redis) * [Clustering](#clustering) * [Sentinel](#sentinel) * [TLS Support](#tls-support) * [Redis Cloud](#redis-cloud) * [Keyv Redis Options](#keyv-redis-options) * [API](#api) * [Events](#events) * [Migrating from v3 to v4](#migrating-from-v3-to-v4) * [About Redis Sets and its Support in v4](#about-redis-sets-and-its-support-in-v4) * [Using with NestJS](#using-with-nestjs) * [License](#license) # Installation ```bash npm install --save keyv @keyv/redis ``` # Usage Here is a standard use case where we implement `Keyv` and `@keyv/redis`: ```js import Keyv from 'keyv'; import KeyvRedis from '@keyv/redis'; const keyv = new Keyv(new KeyvRedis('redis://user:pass@localhost:6379')); keyv.on('error', handleConnectionError); ``` Here is the same example but with the `Keyv` instance created with the `createKeyv` function: ```js import { createKeyv } from '@keyv/redis'; const keyv = createKeyv('redis://user:pass@localhost:6379'); ``` You only have to import the `@keyv/redis` library if you are using the `createKeyv` function. 🎉 Otherwise, you can import `Keyv` and `@keyv/redis` independently. Here you can pass in the Redis options directly: ```js import Keyv from 'keyv'; import KeyvRedis from '@keyv/redis'; const uri = "redis://localhost:6379"; // NOTE: please use the settings that you need to configure. Check out Keyv Redis Options section const options = { namespace: "test", namespaceSeparator: "->", clearBatchSize: 100, useUnlink: true, noNamespaceAffectsAll: true, }; const keyvRedis = new KeyvRedis(uri, options); const keyv = new Keyv(keyvRedis); ``` Or you can create a new Redis instance and pass it in with `KeyvOptions` such as setting the `store`: ```js import Keyv from 'keyv'; import KeyvRedis, { createClient } from '@keyv/redis'; const redis = createClient({ url: 'redis://user:pass@localhost:6379' }); const keyvRedis = new KeyvRedis(redis); const keyv = new Keyv({ store: keyvRedis}); ``` # Migrating from v5 to v6 `@keyv/redis` v6 tracks Keyv's shared version. The adapter already implemented the v6 storage contract (`capabilities.expires`); these are the redis-specific things to know: * **`@redis/client` is now v6.** `createClient`, `createCluster`, and `createSentinel` are still exported from this package. `createClient` takes a `RedisClientOptions` object (`{ url: 'redis://...' }`), not a URI string. * **Adapters receive absolute `expires`, not relative `ttl`.** When you call `keyv.set(key, value, 1000)`, Keyv converts that millisecond ttl to a Unix-ms deadline and passes it to the adapter. Direct adapter calls should pass `expires` (`Date.now() + ttl`), not a relative ttl. * **Keyv no longer prefixes keys.** Namespacing lives on the adapter (`namespace` + `namespaceSeparator`, default `::`). You do not need `useKeyPrefix: false` — that option was removed from Keyv. * **`keyPrefixSeparator` is now `namespaceSeparator`.** The option, getter, and setter were renamed to match the other adapters. In plain JavaScript the old option is ignored and the store uses `::`, so rename it wherever you set it. * **Keys written by v5 need matching settings.** v5's default setup, `new Keyv(new KeyvRedis(uri))`, applied its default `keyv` namespace twice, once in Keyv and once in the adapter, so `foo` was stored as `keyv::keyv:foo`. Read those keys with `new Keyv(new KeyvRedis(uri, { namespaceSeparator: '::keyv:' }), { namespace: 'keyv' })`. The [v5 to v6 migration guide](https://keyv.org/docs/migration/v5-to-v6/#the-default-keyv-namespace-was-removed) lists the settings for other v5 setups. * **`createKeyv` accepts cluster and sentinel options** the same way the `KeyvRedis` constructor does. * **A failure is reported once.** When the adapter rejects because of `throwOnConnectError` or `throwOnErrors`, it no longer also emits `error`. A failed connection rejects with the connection error as the rejection's `cause`. See [Gracefully Handling Errors and Timeouts](#gracefully-handling-errors-and-timeouts). # Migrating from v4 to v5 The major change from v4 to v5 is that we are now using v5 of the `@redis/client` library which has a new API. This means that some methods have changed but it should be a drop-in replacement for most use cases. # Keyv Redis Options You can pass in options to the `KeyvRedis` constructor. Here are the available options: ```typescript export type KeyvRedisOptions = { /** * Namespace for the current instance. */ namespace?: string; /** * Separator to use between namespace and key. */ namespaceSeparator?: string; /** * Number of keys to delete in a single batch. */ clearBatchSize?: number; /** * Enable Unlink instead of using Del for clearing keys. This is more performant but may not be supported by all Redis versions. */ useUnlink?: boolean; /** * Whether to allow clearing all keys when no namespace is set. * If set to true and no namespace is set, iterate() will return all keys. * @default false */ noNamespaceAffectsAll?: boolean; /** * Throw an error if the client is not connected when trying to connect. By default this is * `true` so a failed Redis connection throws. * @default true */ throwOnConnectError?: boolean; /** * Throw an error if any operation fails. When `false`, failures emit an `error` event * and return no-op responses (`undefined` for gets, `false` for writes/deletes). * @default false */ throwOnErrors?: boolean; /** * Timeout in milliseconds for the full connect handshake (TCP plus Redis HELLO / AUTH). * When undefined, the Redis client default is used. If set, a connection that does not * succeed within this time throws, the in-flight attempt is aborted, and leftover sockets * are not left open. When Keyv constructs the client, this is also passed as * `socket.connectTimeout` unless that option is already set. Auto-reconnect is disabled * unless you pass `socket.reconnectStrategy`. * @default undefined */ connectionTimeout?: number; }; ``` You can pass these options when creating a new `KeyvRedis` instance: ```js import Keyv from 'keyv'; import KeyvRedis from '@keyv/redis'; const keyvRedis = new KeyvRedis('redis://user:pass@localhost:6379', { namespace: 'my-namespace', namespaceSeparator: ':', clearBatchSize: 1000, useUnlink: true, noNamespaceAffectsAll: false, connectionTimeout: 200 }); const keyv = new Keyv({ store: keyvRedis }); ``` You can also set these options after the fact by using the `KeyvRedis` instance properties: ```js import {createKeyv} from '@keyv/redis'; const keyv = createKeyv('redis://user:pass@localhost:6379'); keyv.store.namespace = 'my-namespace'; ``` See [API](#api) for the full property and method list. Missing keys and swallowed errors return `undefined` (never `null`). Events are emitted through [Hookified](https://hookified.org) — see [Events](#events). # Using the `createKeyv` function The `createKeyv` function is a convenience function that creates a new `Keyv` instance with the `@keyv/redis` store. It applies `namespace` on both Keyv and the adapter so keys are prefixed once. Here is an example of how to use it: ```js import { createKeyv } from '@keyv/redis'; const keyv = createKeyv('redis://user:pass@localhost:6379'); ``` To use a namespace you can do it here and this will set Keyv up correctly to avoid the double namespace issue: ```js import { createKeyv } from '@keyv/redis'; const keyv = createKeyv('redis://user:pass@localhost:6379', {namespace: 'my-namespace'}); ``` # Using the `createKeyvNonBlocking` function The `createKeyvNonBlocking` function is a convenience function that creates a new `Keyv` instance with the `@keyv/redis` store. It does what `createKeyv` does but also turns off the adapter's `throwOnConnectError` and `throwOnErrors`, the Redis offline queue, and the reconnect strategy, so that when used as a secondary cache in libraries such as [cacheable](https://npmjs.org/package/cacheable) it does not block the primary cache. This is useful when you want to use Redis as a secondary cache and do not want to block the primary cache on connection errors or timeouts when using `nonBlocking`. Concurrent operations share the in-flight Redis connect so they are not dropped while the client is still opening. Here is an example of how to use it: ```js import { createKeyvNonBlocking } from '@keyv/redis'; const keyv = createKeyvNonBlocking('redis://user:pass@localhost:6379'); keyv.on('error', (error) => console.error('Redis error', error)); ``` As with any Keyv instance, attach an `error` listener so a failed operation returns a fallback value instead of rejecting. See [Gracefully Handling Errors and Timeouts](#gracefully-handling-errors-and-timeouts). With a URI or client options, `createKeyvNonBlocking` creates the client with the offline queue and reconnect already off. When Redis is down, an operation fails as soon as its connection attempt does and returns its fallback value, instead of waiting for Redis to come back. A refused connection fails immediately. A host that doesn't respond waits for the socket's `connectTimeout` (5 seconds by default), which the `connectionTimeout` option can shorten. node-redis fixes a client's reconnect strategy when the client is created, so a client you pass in keeps its own. Create it with `socket: { reconnectStrategy: false }` to get the same behavior. Its offline queue is still turned off: ```js import { createClient, createKeyvNonBlocking } from '@keyv/redis'; const client = createClient({ url: 'redis://localhost:6379', socket: { reconnectStrategy: false } }); const keyv = createKeyvNonBlocking(client); ``` Cluster and sentinel connections keep their own offline queue and reconnect settings. Only the throw settings change. # Namespaces By default namespacing is turned off, this is done because it causes much more memory / performance usage for Redis. Redis does **not** treat colons (`:`) or namespaces as special—there are no hierarchical keys or namespace mechanics internally. The dramatic memory savings you see when removing prefixes like `namespace:` come from one thing: **key length**. Redis stores every key as a full string in memory, wrapped in an SDS structure and allocated by jemalloc. Longer keys (e.g., `namespace:key123`) fall into larger jemalloc size classes, require more bytes for the SDS header, and cause more fragmentation. Shorter keys (e.g., `key123`) fit into much smaller slabs, pack tightly, and result in far more stable and predictable memory usage. This means the colon is not the issue—**the extra characters are.** A key that goes from ~18 bytes to ~6 bytes can use *half the memory per key* once overhead, allocator classes, and fragmentation are considered. Multiply that by hundreds of thousands or millions of keys, and memory usage becomes significantly smaller and much more stable simply because the keys are shorter. ## How to use Namespaces You can set a namespace for your keys. This is useful if you want to manage your keys in a more organized way. Here is an example of how to set a `namespace` with the `store` option: ```js import Keyv from 'keyv'; import KeyvRedis, { createClient } from '@keyv/redis'; const redis = createClient({ url: 'redis://user:pass@localhost:6379' }); const keyvRedis = new KeyvRedis(redis); const keyv = new Keyv({ store: keyvRedis, namespace: 'my-namespace' }); ``` To make this easier, you can use the `createKeyv` function which will automatically set the `namespace` option to the `KeyvRedis` instance: ```js import { createKeyv } from '@keyv/redis'; const keyv = createKeyv('redis://user:pass@localhost:6379', { namespace: 'my-namespace' }); ``` This will prefix all keys with `my-namespace::` (the default `namespaceSeparator` is `::`). You can also set the namespace after the fact: ```js keyv.namespace = 'my-namespace'; ``` `clear()` and `iterator()` only touch keys that start with the namespace and separator (`my-namespace::`). Both are matched literally, so `*`, `?`, `[`, `]` and `\` in them have no special meaning to `SCAN`: clearing `tenant*` leaves `tenant-prod` alone. Clearing `my-namespace` does also clear a namespace that extends it with the separator, such as `my-namespace::archive`, because a key can contain the separator too. Keep the separator out of namespace names if you need them kept apart. NOTE: If you plan to do many clears or deletes, it is recommended to read the [Performance Considerations](#performance-considerations) section. # Fixing Double Prefixing of Keys In v6, Keyv does not prefix keys. The Redis adapter owns namespacing, so this: ```js import Keyv from 'keyv'; import KeyvRedis from '@keyv/redis'; const keyv = new Keyv(new KeyvRedis('redis://user:pass@localhost:6379'), { namespace: 'my-namespace' }); ``` stores keys as `my-namespace::key`. `createKeyv` does the same wiring for you: ```js import { createKeyv } from '@keyv/redis'; const keyv = createKeyv('redis://user:pass@localhost:6379', { namespace: 'my-namespace' }); ``` If you are upgrading from v5, drop `useKeyPrefix` — it no longer exists. Do not also set Redis client's `keyPrefix`; use the adapter `namespace` instead so `SCAN`/`clear`/`iterator` stay in sync. ## Using Generic Types When initializing `KeyvRedis`, you can specify the type of the values you are storing and you can also specify types when calling methods: ```typescript import Keyv from 'keyv'; import KeyvRedis, { createClient } from '@keyv/redis'; type User = { id: number name: string } const redis = createClient({ url: 'redis://user:pass@localhost:6379' }); const keyvRedis = new KeyvRedis(redis); const keyv = new Keyv({ store: keyvRedis }); await keyv.set("user:1", { id: 1, name: "Alice" }) const user = await keyv.get("user:1") console.log(user.name) // 'Alice' // specify types when calling methods const user = await keyv.get("user:1") console.log(user.name) // 'Alice' ``` # Performance Considerations With namespaces being prefix based it is critical to understand some of the performance considerations we have made: * `clear()` - We use the `SCAN` command to iterate over keys. This is a non-blocking command that is more efficient than `KEYS`. In addition we are using `UNLINK` by default instead of `DEL`. Even with that if you are iterating over a large dataset it can still be slow. It is highly recommended to use the `namespace` option to limit the keys that are being cleared and if possible to not use the `clear()` method in high performance environments. If you don't set namespaces, you can enable `noNamespaceAffectsAll` to clear all keys using the `FLUSHDB` command which is faster and can be used in production environments. * `delete()` - By default we are now using `UNLINK` instead of `DEL` for deleting keys. This is a non-blocking command that is more efficient than `DEL`. If you are deleting a large number of keys it is recommended to use the `deleteMany()` method instead of `delete()`. * `clearBatchSize` - The `clearBatchSize` option is set to `1000` by default. This is because Redis has a limit of 1000 keys that can be deleted in a single batch. If no namespace is defined and noNamespaceAffectsAll is set to `true` this option will be ignored and the `FLUSHDB` command will be used instead. * `useUnlink` - This option is set to `true` by default. This is because `UNLINK` is a non-blocking command that is more efficient than `DEL`. If you are not using `UNLINK` and are doing a lot of deletes it is recommended to set this option to `true`. * `setMany`, `getMany`, `deleteMany` - These methods are more efficient than their singular counterparts. These will be used by default in the `Keyv` library such as when using `keyv.delete(string[])` it will use `deleteMany()`. If you want to see even better performance please see the [Using Cacheable with Redis](#using-cacheable-with-redis) section as it has non-blocking and in-memory primary caching that goes along well with this library and Keyv. # Expiration and TTL Keyv hands this adapter an **absolute** expiry — a Unix timestamp in milliseconds — computed once on the Keyv host. The adapter writes it to Redis with `SET ... PXAT`, the absolute-expiry option. Because the deadline is absolute, it is immune to clock skew and to any latency between Keyv computing the expiry and Redis receiving the command: a key set to expire at `T` expires at `T` no matter how long the write takes to arrive. `PXAT` was added in **Redis 6.2**. For older servers the adapter automatically falls back to the relative `PX` option (the remaining lifetime in milliseconds): * On the **first** expiring write, the adapter runs `INFO server` once, parses `redis_version`, and caches whether the server is 6.2+. Every later write reuses that cached answer, so detection costs one `INFO` round-trip per connection, not per write. * **6.2 or newer** → the write uses `PXAT: expires` (absolute). * **Older than 6.2** → the write uses `PX: max(1, expires - Date.now())` (relative, computed at write time). An expiry already in the past becomes `PX: 1` because Redis rejects `SET ... PX 0`. * If the version **cannot be determined** — for example a cluster where `INFO` isn't directly available, or a transient error reading it — the adapter assumes `PXAT` is supported, since such deployments are overwhelmingly modern. The cached result means it won't keep retrying `INFO` on every write. The same detection and fallback apply to `setMany`, including the per-hash-slot grouping used in cluster mode. No configuration is required; you always call `keyv.set(key, value, ttl)` with a relative millisecond `ttl` (or rely on the `ttl` option) and the adapter chooses the correct Redis option for your server. The relative `PX` fallback re-derives the remaining lifetime store-side, so on pre-6.2 servers a large write-to-Redis latency could in theory shorten the effective TTL by that latency. On 6.2+ (`PXAT`) there is no such window. If you need the skew-immune absolute behaviour, run Redis 6.2 or later. # High Memory Usage on Redis Server This is because we are using `UNLINK` by default instead of `DEL`. This is a non-blocking command that is more efficient than `DEL` but will slowly remove the memory allocation. If you are deleting or clearing a large number of keys you can disable this by setting the `useUnlink` option to `false`. This will use `DEL` instead of `UNLINK` and should reduce the memory usage. ```js const keyv = new Keyv(new KeyvRedis('redis://user:pass@localhost:6379', { useUnlink: false })); // Or keyv.store.useUnlink = false; ``` # Gracefully Handling Errors and Timeouts Attach an `error` listener to the Keyv instance when you use `@keyv/redis`. Keyv handles errors the way a Node.js `EventEmitter` does: when an operation fails, it emits `error`, and then - **with a listener attached**, the operation returns a fallback value, such as `undefined` from `get` or `false` from `set`; - **with no listener attached**, the operation rejects with the error. The Redis client also reports connection problems as `error` events outside any Keyv call, for example when a connection drops. Keyv forwards these to its own `error` event. With no listener attached, such an error is thrown with no call to catch it, which can crash your process. ```js import Keyv from 'keyv'; import KeyvRedis from '@keyv/redis'; const keyv = new Keyv(new KeyvRedis('redis://user:pass@localhost:6379')); keyv.on('error', (error) => { console.error('error', error); }); ``` See [Error Handling](https://github.com/jaredwray/keyv/tree/main/core/keyv#error-handling) in the Keyv README for the fallback value each method returns. The adapter has its own options that decide whether `KeyvRedis` rejects or reports a failure as an `error` event: - `throwOnConnectError` (default `true`): reject when the connection fails, with the connection error as the rejection's `cause`. When it is `false`, the adapter emits the connection error as an `error` event instead. - `throwOnErrors` (default `false`): reject when an operation fails. When it is `false`, the adapter emits `error` and returns a no-op value on `get`, `getMany`, `set`, `setMany`, `delete`, and `deleteMany` if the connection is lost. The adapter reports each failure once: when it rejects, it does not also emit `error`. Used through Keyv, a rejection from the adapter is handled by the rule above: Keyv emits `error`, then returns a fallback value if a listener is attached or rejects if none is. There is a default `Reconnect Strategy` if you pass in just a `uri` connection string we will automatically create a Redis client for you with the following reconnect strategy: ```typescript export const defaultReconnectStrategy = (attempts: number): number | Error => { // Exponential backoff base: double each time, capped at 2s. // Parentheses make it clear we do (2 ** attempts) first, then * 100 const backoff = Math.min((2 ** attempts) * 100, 2000); // Add random jitter of up to ±50ms to avoid thundering herds: const jitter = (Math.random() - 0.5) * 100; return backoff + jitter; }; ``` # Using Cacheable with Redis If you are wanting to see even better performance with Redis, you can use [Cacheable](https://npmjs.org/package/cacheable) which is a multi-layered cache library that has in-memory primary caching and non-blocking secondary caching. Here is an example of how to use it with Redis: ```js import KeyvRedis from '@keyv/redis'; import Cacheable from 'cacheable'; const secondary = new KeyvRedis('redis://user:pass@localhost:6379'); const cache = new Cacheable( { secondary } ); ``` For even higher performance you can set the `nonBlocking` option to `true`: ```js const cache = new Cacheable( { secondary, nonBlocking: true } ); ``` This will make it so that the secondary does not block the primary cache and will be very fast. 🚀 > **Note:** `cacheable` 2 depends on Keyv v5 and wraps a store like this one in its own v5 `Keyv`. A v5 `Keyv` passes a relative `ttl` where a v6 adapter expects an absolute `expires`, so entries expire at the wrong time, usually at once. Check which Keyv version your `cacheable` needs with `npm view cacheable dependencies.keyv`, and keep this setup on v5 until it supports v6. See [Libraries That Embed Keyv v5](https://keyv.org/docs/migration/v5-to-v6/#libraries-that-embed-keyv-v5). # Clustering If you are using a Redis Cluster, you can pass in the `redisOptions` directly. Here is an example of how to do that: ```js import Keyv from 'keyv'; import KeyvRedis, { createCluster } from '@keyv/redis'; const cluster = createCluster({ rootNodes: [ { url: 'redis://127.0.0.1:7000', }, { url: 'redis://127.0.0.1:7001', }, { url: 'redis://127.0.0.1:7002', }, ], }); const keyv = new Keyv({ store: new KeyvRedis(cluster) }); ``` You can learn more about the `createCluster` function in the [documentation](https://github.com/redis/node-redis/blob/master/docs/clustering.md) at https://github.com/redis/node-redis/tree/master/docs. # Sentinel If you are using Sentinel to provide high availability for your Redis instances, you can pass in the sentinel options directly to the `KeyvRedis` constructor: ```js import Keyv from 'keyv'; import KeyvRedis from '@keyv/redis'; const keyv = new Keyv({ store: new KeyvRedis({ name: 'mymaster', sentinelRootNodes: [ { host: '127.0.0.1', port: 26379 }, { host: '127.0.0.1', port: 26380 }, { host: '127.0.0.1', port: 26381 }, ], }), }); ``` For TypeScript users, the `RedisSentinelOptions` type is exported from the package: ```typescript import KeyvRedis, { type RedisSentinelOptions } from '@keyv/redis'; const sentinelOptions: RedisSentinelOptions = { name: 'mymaster', sentinelRootNodes: [ { host: '127.0.0.1', port: 26379 }, { host: '127.0.0.1', port: 26380 }, { host: '127.0.0.1', port: 26381 }, ], }; const keyvRedis = new KeyvRedis(sentinelOptions); ``` You can learn more about Sentinel configuration in the [documentation](https://github.com/redis/node-redis/blob/master/docs/sentinel.md) at https://github.com/redis/node-redis/tree/master/docs. # TLS Support Here is an example of how to use TLS using the `redisOptions`: ```js import Keyv from 'keyv'; import KeyvRedis from '@keyv/redis'; const tlsOptions = { socket: { host: 'localhost', port: 6379, tls: true, // Enable TLS connection rejectUnauthorized: false, // Ignore self-signed certificate errors (for testing) // Alternatively, provide CA, key, and cert for mutual authentication ca: fs.readFileSync('/path/to/ca-cert.pem'), cert: fs.readFileSync('/path/to/client-cert.pem'), // Optional for client auth key: fs.readFileSync('/path/to/client-key.pem'), // Optional for client auth } }; const keyv = new Keyv({ store: new KeyvRedis(tlsOptions) }); ``` # Redis Cloud You connect to Redis Cloud the same way you connect to any Redis server, with a URI or with Redis client options. `KeyvRedis` creates a client from a URI string. It passes an options object, unchanged except for `connectionTimeout` when you set it, to `createClient` from `@redis/client`. That means `url`, `username`, `password`, and every `socket` TLS option work exactly as documented for `@redis/client`. `createKeyv` accepts the same arguments. ## Endpoint and credentials The database endpoint (host and port) is on the database's **Configuration** tab in the Redis Cloud console: in the **Access** section for Essentials databases, or the **General** section for Pro databases. By default the database has a user named `default`. To see its password, use **Default user** > **Configure** for an Essentials database, or the **Security** section of the **Configuration** tab for a Pro database. If you turned on role-based access control and turned off the default user, use the username and password of a data access role instead. With TLS turned on, the URI uses the `rediss://` scheme (two `s`'s). Without `redis_ca.pem`, the URI below fails to connect when the database's certificate was issued by a Redis Cloud CA, so trust that CA as shown in [Trusting `redis_ca.pem`](#trusting-redis_capem). ```js import Keyv from 'keyv'; import KeyvRedis from '@keyv/redis'; const keyv = new Keyv(new KeyvRedis('rediss://default:password@redis-host:12345')); keyv.on('error', (error) => console.error('Redis error', error)); ``` Replace `password`, `redis-host`, and `12345` with your values. Encode a password that contains reserved URI characters, such as `@`, `:`, `/`, or `#`, with `encodeURIComponent`. A `redis://` URI connects without TLS, which a TLS-enabled database refuses. ## Turning on TLS TLS is off by default. Turn it on from the **Security** section of the database's **Configuration** tab. It is available on paid Essentials and Pro plans, but not on the Free plan. Redis Cloud recommends TLS for any database reached over its public endpoint. Once TLS is on, every connection must use it. ## Trusting `redis_ca.pem` Download the Redis Cloud CA bundle, `redis_ca.pem`, with **Download server certificate** on the database's **Configuration** tab, or from **Account Settings** > **Security**. The file holds several certificates, including Redis Cloud's own root CAs, which Node.js does not trust by default. Without the bundle, a `rediss://` URI checks the certificate only against Node.js's built-in CAs, which fails for databases whose certificates were issued by a Redis Cloud CA. Pass the whole file as `socket.ca`. Node.js loads every certificate in it. ```js import fs from 'node:fs'; import Keyv from 'keyv'; import KeyvRedis from '@keyv/redis'; const keyv = new Keyv(new KeyvRedis({ url: 'rediss://default:password@redis-host:12345', socket: { tls: true, ca: fs.readFileSync('/path/to/redis_ca.pem'), }, })); keyv.on('error', (error) => console.error('Redis error', error)); ``` You can set the host, port, and credentials as separate options instead of a `url`: ```js const keyv = new Keyv(new KeyvRedis({ username: 'default', password: 'password', socket: { host: 'redis-host', port: 12345, tls: true, ca: fs.readFileSync('/path/to/redis_ca.pem'), }, })); ``` Keep these points in mind: - Leave `rejectUnauthorized` unset so Node.js verifies the certificate. The [TLS Support](#tls-support) sample sets it to `false`, which is only suitable for a local server with a self-signed certificate. - Connect with the endpoint hostname from the console, not an IP address. The certificate check compares hostnames. - `socket.tls` must match the URI scheme, so it must be `true` with `rediss://`. Otherwise `@redis/client` throws. - A URI string gets the adapter's [`defaultReconnectStrategy`](#helpers). With an options object, `@redis/client` uses its own reconnect behavior unless you set `socket.reconnectStrategy`, for example to `defaultReconnectStrategy`, which you can import from `@keyv/redis`. ## Mutual TLS If the database requires client authentication (**Mutual TLS** in the TLS settings), add the client certificate and private key you registered there to the same `socket` options: ```js const keyv = new Keyv(new KeyvRedis({ username: 'default', password: 'password', socket: { host: 'redis-host', port: 12345, tls: true, ca: fs.readFileSync('/path/to/redis_ca.pem'), cert: fs.readFileSync('/path/to/client.crt'), key: fs.readFileSync('/path/to/client.key'), }, })); ``` Other hosted Redis services use the same pattern: a `rediss://` URI or `socket.tls: true`, plus the CA certificate the provider gives you. # API `KeyvRedis` extends [Hookified](https://hookified.org) (`on`, `once`, `emit`, hooks) and implements the Keyv storage adapter contract. Missing keys and swallowed errors return `undefined` (never `null`). ## Properties * **capabilities** - Adapter capability descriptor. `capabilities.expires` is `true` (absolute Unix-ms `expires` on `set` / `setMany`). * **client** - The Redis client, cluster, or sentinel connection. Assigning a new connection re-wires Hookified event listeners and resets PXAT detection. Type: `RedisClientConnectionType`. * **namespace** - Namespace used to prefix keys. `undefined` means no prefixing. Default: `undefined`. * **namespaceSeparator** - Separator between namespace and key. May be `""`. Default: `"::"`. * **clearBatchSize** - `SCAN` / delete batch size. Must be greater than `0` or an `error` event is emitted. Default: `1000`. * **useUnlink** - Use `UNLINK` instead of `DEL`. Default: `true`. * **noNamespaceAffectsAll** - When no namespace is set, `clear()` / `iterator()` affect all keys (including namespaced ones). Default: `false`. * **throwOnConnectError** - Throw when connect fails, with the connection error as the `cause`, instead of emitting `error`. Default: `true`. * **throwOnErrors** - Throw on operation failures instead of emitting `error` and returning a no-op. Default: `false`. * **connectionTimeout** - Timeout in milliseconds for the full connect handshake (TCP plus Redis HELLO / AUTH). `undefined` uses the Redis client default. On expiry the in-flight connect is aborted so sockets and timers are not left active. When Keyv constructs the client, this is also passed as `socket.connectTimeout` unless that option is already set. Auto-reconnect is disabled unless you pass `socket.reconnectStrategy`. ## Methods * **constructor([connect], [options])** - `connect` is a URI string, client/cluster/sentinel options (`KeyvRedisConnect`), or an existing connection. See [Keyv Redis Options](#keyv-redis-options). * **getClient()** - Return the ready client, connecting first if needed. Concurrent callers share the in-flight connect and wait until `isReady` (not only `isOpen`). On `connectionTimeout`, the hung handshake is aborted so sockets are not left open. Returns `Promise`. * **set(key, value, [expires])** - Set a key. `expires` is an absolute Unix timestamp in milliseconds. Returns `Promise`. Through Keyv, pass a relative millisecond `ttl` to `keyv.set` — Keyv converts it to `expires`. * **setMany(entries)** - Set `KeyvStorageEntry` objects (`{ key, value, expires? }`) via `MULTI/EXEC`. Returns `Promise` (per-entry success). Cluster mode groups by hash slot. * **get(key)** - Get a key. Returns the value or `undefined` if missing (Redis `null` is mapped to `undefined`). * **getMany(keys)** - Get multiple keys. Each missing entry is `undefined`. * **has(key)** - Returns `Promise`. * **hasMany(keys)** - Returns `Promise`. * **delete(key)** - Returns `Promise`. * **deleteMany(keys)** - Returns `Promise`. * **clear()** - Clear keys in the namespace. With no namespace, clears un-prefixed keys unless `noNamespaceAffectsAll` is `true` (`FLUSHDB`). * **iterator()** - Async generator of `[key, value]` pairs. Uses the instance namespace. Missing values are `undefined`. * **disconnect([force])** - Graceful `close()` (`QUIT`) when `force` is false; `destroy()` when `true`. * **createKeyPrefix(key, [namespace])** - Returns `namespace::key` (or `key` when namespace is omitted). * **getKeyWithoutPrefix(key, [namespace])** - Strips a leading namespace prefix. * **isCluster()** - `true` if the connection is a Redis cluster. * **isSentinel()** - `true` if the connection is a Redis sentinel. * **getMasterNodes()** - Cluster master node clients, or `[client]` when standalone. ## Helpers * **createKeyv([connect], [options])** - Keyv instance with this adapter. Applies `namespace` on both Keyv and the store. `connect` accepts the same `KeyvRedisConnect` types as the constructor (including cluster/sentinel). Defaults to `"redis://localhost:6379"` when `connect` is omitted. * **createKeyvNonBlocking([connect], [options])** - Same as `createKeyv`, then disables throws, the offline queue, and reconnect for secondary-cache use. A client passed in keeps its own reconnect strategy, and cluster and sentinel connections only have their throw settings changed. See [Using the `createKeyvNonBlocking` function](#using-the-createkeyvnonblocking-function). Concurrent operations wait for the shared in-flight connect instead of being dropped. * **defaultReconnectStrategy(attempts)** - Default socket reconnect delay when a URI string is passed to the constructor. Exponential backoff capped at 2s, plus up to ±50ms of jitter. Returns a delay in milliseconds. # Events `KeyvRedis` extends Hookified and re-emits these events from the Redis client onto the adapter: | Event | Payload | When | | --- | --- | --- | | `error` | `Error` (or a string for invalid `clearBatchSize`) | Client errors, and connect or operation failures that the adapter does not reject (see `throwOnConnectError` and `throwOnErrors`) | | `connect` | the Redis connection | The client connects | | `disconnect` | the Redis connection | The client disconnects | | `reconnecting` | reconnect info from `@redis/client` | The client is reconnecting | ```js import {createKeyv} from '@keyv/redis'; const keyv = createKeyv('redis://user:pass@localhost:6379'); const store = keyv.store; store.on('error', (error) => { console.error('adapter error', error); }); store.on('connect', () => { console.log('Redis connected'); }); store.once('disconnect', () => { console.log('Redis disconnected'); }); store.on('reconnecting', () => { console.log('Redis reconnecting'); }); ``` `error`, `connect`, `disconnect`, and `reconnecting` are re-emitted on the adapter. Other Redis-client-only events (for example `ready`) can still be listened on `store.client`: ```js store.client.on('ready', () => { console.log('Redis client ready'); }); ``` Client events: https://www.npmjs.com/package/redis#events # Migrating from v3 to v4 > **Note:** This section applies to versions before v6. Keyv v6 removed the `useKeyPrefix` option: TypeScript rejects it and JavaScript ignores it. In v6 the adapter owns namespacing, so leave the option out. See [Fixing Double Prefixing of Keys](#fixing-double-prefixing-of-keys). Overall the API is the same as v3 with additional options and performance improvements. Here are the main changes: * The `ioredis` library has been removed in favor of the `redis` aka `node-redis` library. If you want to use ioredis you can use `@keyv/valkey` * The `useUnlink` option has been added to use `UNLINK` instead of `DEL` and set to true by default. * The `clearBatchSize` option has been added to set the number of keys to delete in a single batch. * The `clear()` and `delete()` methods now use `UNLINK` instead of `DEL`. If you want to use `DEL` you can set the `useUnlink` option to `false`. * BREAKING: We no longer support redis sets. This is due to the fact that it caused significant performance issues and was not a good fit for the library. * BREAKING: YOUR PREVIOUS KEYS WILL NOT BE VALID. This is because of the fixe of the namespace support and how it is handled. Now, when using `keyv` with `@keyv/redis` as the storage adapter you can do the following: ```js import Keyv from 'keyv'; import KeyvRedis from '@keyv/redis'; const redis = new KeyvRedis('redis://user:pass@localhost:6379'); const keyv = new Keyv({ store: redis, namespace: 'my-namespace', useKeyPrefix: false }); ``` This will make it so the storage adapter `@keyv/redis` will handle the namespace and not the `keyv` instance. If you leave it on it will just look duplicated like `my-namespace:my-namespace:key`. # About Redis Sets and its Support in v4 We no longer support redis sets. This is due to the fact that it caused significant performance issues and was not a good fit for the library. # Using with NestJS > You can integrate `@keyv/redis` with NestJS by creating a custom `CacheModule`. This allows you to use Keyv as a cache store in your application. > **Note:** `cache-manager` 7 depends on Keyv v5. It reads expiry data with `store.get(key, { raw: true })`, which a v6 `Keyv` ignores, so `ttl()` and the refresh logic in `wrap()` stop working with a v6 store. Check which Keyv version your `cache-manager` needs with `npm view cache-manager dependencies.keyv`. See [Libraries That Embed Keyv v5](https://keyv.org/docs/migration/v5-to-v6/#libraries-that-embed-keyv-v5). ### 1. Install Dependencies ```bash npm install @keyv/redis keyv @nestjs/cache-manager cache-manager cacheable ``` ### 2. Create a Cache Module Create a file `cache.module.ts`: ```ts import { Module } from '@nestjs/common'; import { CacheModule as NestCacheModule } from '@nestjs/cache-manager'; import { createKeyv } from '@keyv/redis'; @Module({ imports: [ NestCacheModule.registerAsync({ useFactory: () => ({ stores: [createKeyv('redis://localhost:6379')], }), }), ], providers: [], exports: [], }) export class CacheModule {} ``` ### 3. Import the Cache Module in AppModule Update `app.module.ts`: ```ts import { Module } from '@nestjs/common'; import { CacheModule } from './modules/config/cache/cache.module'; @Module({ imports: [ CacheModule, // Import your custom cache module // other modules... ], }) export class AppModule {} ``` ### 4. Create the Cache Service Create a file `cache.service.ts`: ```ts import { CACHE_MANAGER } from '@nestjs/cache-manager'; import { Inject, Injectable } from '@nestjs/common'; import { Cache } from 'cache-manager'; @Injectable() export class CacheService { constructor(@Inject(CACHE_MANAGER) private cacheManager: Cache) {} async get(key: string): Promise { return this.cacheManager.get(key); } async set(key: string, value: T, ttl?: number): Promise { await this.cacheManager.set(key, value, ttl); return true; } async delete(key: string): Promise { await this.cacheManager.del(key); } } ``` ### 5. Register CacheService in CacheModule Update `cache.module.ts`: ```ts import { Module } from '@nestjs/common'; import { CacheModule as NestCacheModule } from '@nestjs/cache-manager'; import { createKeyv } from '@keyv/redis'; import { CacheService } from './services/cache.service'; @Module({ imports: [ NestCacheModule.registerAsync({ useFactory: () => ({ stores: [createKeyv('redis://localhost:6379')], }), }), ], providers: [CacheService], exports: [CacheService], }) export class CacheModule {} ``` ### 6. Import CacheModule in the Target Module (e.g. TaskModule) ```ts import { Module } from '@nestjs/common'; import { TaskService } from './task.service'; import { TaskRepository } from './repositories/task.repository'; import { CacheModule } from 'src/modules/config/cache/cache.module'; @Module({ imports: [CacheModule], providers: [TaskService, TaskRepository], }) export class TaskModule {} ``` ### 7. Using the Cache in a Service ```ts import { Injectable, NotFoundException } from '@nestjs/common'; import { TaskRepository } from '../repositories/task.repository'; import { TaskDto } from '../dto/task.dto'; import { CacheService } from 'src/modules/config/cache/services/cache.service'; @Injectable() export class TaskService { constructor( private readonly taskRepository: TaskRepository, private readonly cache: CacheService, // Inject the CacheService ) {} async findById(id: number): Promise { const cacheKey = `task:${id}`; // 1. Try to get from cache const cached = await this.cache.get(cacheKey); if (cached) { return cached; } // 2. If not found in cache, fetch from database const task = await this.taskRepository.findById(id); if (!task) { throw new NotFoundException('Task not found'); } // 3. Set in cache for future requests await this.cache.set(cacheKey, task, 300 * 1000); // 5 minutes TTL return task; } } ``` You can learn more about caching in NestJS in the [official documentation](https://docs.nestjs.com/techniques/caching#in-memory-cache). --- # License [MIT © Jared Wray](LICENSE) ### @keyv/valkey URL: https://keyv.org/docs/storage-adapters/valkey/ # @keyv/valkey [keyv](https://github.com/jaredwray/keyv) > Valkey storage adapter for Keyv [![build](https://github.com/jaredwray/keyv/actions/workflows/tests.yaml/badge.svg)](https://github.com/jaredwray/keyv/actions/workflows/tests.yaml) [![codecov](https://codecov.io/gh/jaredwray/keyv/branch/main/graph/badge.svg?token=bRzR3RyOXZ)](https://codecov.io/gh/jaredwray/keyv) [![npm](https://img.shields.io/npm/v/@keyv/valkey.svg)](https://www.npmjs.com/package/@keyv/valkey) [![npm](https://img.shields.io/npm/dm/@keyv/valkey)](https://npmjs.com/package/@keyv/valkey) [Valkey](https://valkey.io) storage adapter for [Keyv](https://github.com/jaredwray/keyv). Valkey is the open source replacement to Redis which decided to do a [dual license](https://redis.com/blog/redis-adopts-dual-source-available-licensing/) approach moving forward. Valkey is a drop-in replacement for Redis and is fully compatible with the Redis protocol. We are using the [iovalkey](https://www.npmjs.com/package/iovalkey) which is a Node.js client for Valkey based on the `ioredis` client. ## Table of Contents - [Install](#install) - [Usage](#usage) - [Using the createKeyv function](#using-the-createkeyv-function) - [Migrating to v6](#migrating-to-v6) - [Constructor Options](#constructor-options) - [Properties](#properties) - [capabilities](#capabilities) - [namespace](#namespace) - [namespaceSeparator](#namespaceseparator) - [useSets](#usesets) - [useRedisSets (deprecated)](#useredissets-deprecated) - [client](#client) - [Methods](#methods) - [.get(key)](#getkey) - [.getMany(keys)](#getmanykeys) - [.set(key, value, expires?)](#setkey-value-expires) - [.setMany(entries)](#setmanyentries) - [.delete(key)](#deletekey) - [.deleteMany(keys)](#deletemanykeys) - [.has(key)](#haskey) - [.hasMany(keys)](#hasmanykeys) - [.clear()](#clear) - [.iterator()](#iterator) - [.disconnect()](#disconnect) - [Events](#events) - [Expiration and TTL](#expiration-and-ttl) - [Clustering](#clustering) - [License](#license) ## Install ```shell npm install --save keyv @keyv/valkey ``` ## Usage This is using the helper `createKeyv` function to create a Keyv instance with the Valkey storage adapter: ```js import {createKeyv} from '@keyv/valkey'; const keyv = createKeyv('redis://localhost:6379'); keyv.on('error', handleConnectionError); await keyv.set('foo', 'bar'); console.log(await keyv.get('foo')); // 'bar' ``` If you want to specify the `KeyvValkey` class directly, you can do so: ```js import Keyv from 'keyv'; import KeyvValkey from '@keyv/valkey'; const keyv = new Keyv(new KeyvValkey('redis://user:pass@localhost:6379', { disable_resubscribing: true })); ``` Or you can manually create a storage adapter instance and pass it to Keyv: ```js import Keyv from 'keyv'; import KeyvValkey from '@keyv/valkey'; const keyvValkey = new KeyvValkey('redis://user:pass@localhost:6379'); const keyv = new Keyv({ store: keyvValkey }); ``` Or reuse a previous Redis instance: ```js import Keyv from 'keyv'; import Redis from 'iovalkey'; import KeyvValkey from '@keyv/valkey'; const redis = new Redis('redis://user:pass@localhost:6379'); const keyvValkey = new KeyvValkey(redis); const keyv = new Keyv({ store: keyvValkey }); ``` Or reuse a previous Redis cluster: ```js import Keyv from 'keyv'; import Redis from 'iovalkey'; import KeyvValkey from '@keyv/valkey'; const cluster = new Redis.Cluster([{ host: '127.0.0.1', port: 7001 }]); const keyvValkey = new KeyvValkey(cluster); const keyv = new Keyv({ store: keyvValkey }); ``` ## Using the createKeyv function `createKeyv` is a convenience factory that returns a `Keyv` instance with the Valkey adapter already wired. The namespace is taken from the adapter so it is preserved whether it was passed in the connect options object or the second argument. ```js import {createKeyv} from '@keyv/valkey'; const keyv = createKeyv('redis://localhost:6379', { namespace: 'my-app' }); console.log(keyv.namespace); // 'my-app' console.log(keyv.store.namespace); // 'my-app' ``` If no connect argument is provided, the default URI is `redis://localhost:6379`. ## Migrating to v6 ### Breaking changes #### Properties instead of opts In v6, all configuration options are exposed as top-level properties with getters and setters: ```js // v6 store.useSets; // false (default) store.useSets = true; store.namespace = 'my-namespace'; ``` #### `useRedisSets` renamed to `useSets` The `useRedisSets` option has been renamed to `useSets`. The `useRedisSets` property is still available as a deprecated getter/setter on the class but will be removed in a future version. #### `redis` property renamed to `client` The `redis` property has been renamed to `client` and is now properly typed as `Redis | Cluster` instead of `any`. Update any code that accesses the underlying iovalkey instance: ```js // v5 store.redis; // v6 store.client; ``` #### `useSets` default changed from `true` to `false` The default value of `useSets` has changed from `true` to `false` for performance reasons. When enabled, a set is maintained for each namespace to track keys, which can lead to memory leaks in high-throughput scenarios. If you depend on the previous behavior, explicitly set `useSets: true` in your options: ```js const store = new KeyvValkey('redis://localhost:6379', { useSets: true }); ``` #### `useSets` key prefix changed from `namespace:` to `sets:` When `useSets` is enabled, all keys (both data keys and the SET tracking key) now use a `sets:` prefix instead of `namespace:`. This prevents `WRONGTYPE` collisions between the SET tracking key and regular string data keys that could share the same name. - **Data keys**: `sets:::` (v5 stored the key as Keyv passed it, `:`) - **SET tracking key**: `sets:` (was `namespace:`) The `clear()` method automatically detects and cleans up legacy `namespace:`-prefixed SET keys. #### Data written by v5 v5's default setup stored `foo` as `keyv:foo`: the key Keyv had prefixed with its default `keyv` namespace. No v6 setting builds that key, so let those entries repopulate or rename them to the v6 layout. Data written with `useRedisSets: false` was stored as `namespace:keyv:keyv:foo`, which v6 reads with `useSets: false`, `namespaceSeparator: ':'`, and `new Keyv(store, { namespace: 'keyv:keyv' })`. See the [v5 to v6 migration guide](https://keyv.org/docs/migration/v5-to-v6/#the-default-keyv-namespace-was-removed) for other setups. #### Missing values are `undefined`, never `null` `get()`, `getMany()`, and `iterator()` return `undefined` for missing keys. They never return `null`. ## Constructor Options `KeyvValkey` accepts a connection URI string, an options object, or an existing iovalkey `Redis`/`Cluster` instance. The options object accepts the following properties along with any [`RedisOptions`](https://github.com/valkey-io/iovalkey#connect-to-valkey) from the `iovalkey` library: | Option | Type | Default | Description | | --- | --- | --- | --- | | `uri` | `string` | `undefined` | Valkey connection URI (`redis://` or `valkey://`) | | `useSets` | `boolean` | `false` | Whether to use sets for namespace key management | | `namespace` | `string` | `undefined` | Namespace used to prefix keys for multi-tenant isolation | | `namespaceSeparator` | `string` | `'::'` | Separator between the namespace and the key, as in `namespace:::` | ## Properties All configuration options are exposed as properties with getters and setters on the `KeyvValkey` instance. You can read or update them after construction. ### capabilities Read-only capability descriptor for the v6 storage contract. `capabilities.expires` is `true`, which means `set()` / `setMany()` accept an absolute Unix-ms `expires` timestamp. - Type: `KeyvStorageCapability` ```js const store = new KeyvValkey('redis://localhost:6379'); console.log(store.capabilities.expires); // true ``` ### namespace Get or set the namespace for the adapter. Used for key prefixing and scoping operations like `clear()`. - Type: `string | undefined` - Default: `undefined` ```js const store = new KeyvValkey('redis://localhost:6379'); store.namespace = 'my-namespace'; console.log(store.namespace); // 'my-namespace' ``` ### namespaceSeparator Get or set the separator between the namespace and the key. Data keys are `namespace:`, or `sets:` with `useSets: true`. - Type: `string` - Default: `'::'` ```js const store = new KeyvValkey('redis://localhost:6379', { namespace: 'my-namespace' }); console.log(store.namespaceSeparator); // '::' await store.set('foo', 'bar'); // stored as namespace:my-namespace::foo ``` ### useSets Get or set whether to use sets for key management. When `true`, a set is maintained for each namespace to track keys. When `false`, keys are prefixed with the namespace and pattern matching is used instead. - Type: `boolean` - Default: `false` ```js const store = new KeyvValkey('redis://localhost:6379', { useSets: true }); console.log(store.useSets); // true ``` **Note**: When `useSets` is `true`, a set is maintained for each namespace which can lead to memory leaks in high-performance scenarios. This is why the default is `false`. When `useSets` is enabled, all keys use the `sets:` prefix (e.g., `sets:myns::mykey`) to isolate them from non-useSets keys. The SET tracking key is stored at `sets:`. When `useSets` is `false`, the `clear()` function uses pattern matching (`KEYS namespace:::*`, with any glob characters in the namespace and separator escaped) to find and delete keys, which may be slower on very large databases. A namespace that merely shares a prefix (for example `users` and `users-archive`) is not affected. A namespace that extends another with the separator (for example `users::archive` under `users`) cannot be told apart by the pattern and is cleared along with it. With no namespace this matches every key in the current database. `useSets: true` doesn't keep such namespaces apart either. `clear()` removes only the keys the namespace's set tracks, but `iterator()` still matches `sets:::*`, and the two namespaces build some of the same keys: `archive::x` in `users` and `x` in `users::archive` are both `sets:users::archive::x`. Keep the separator out of namespace names that have to stay apart. ### useRedisSets (deprecated) Deprecated alias for `useSets`. Use `useSets` instead. ### client Get or set the underlying iovalkey `Redis` or `Cluster` client instance. Replacing the client re-wires Hookified event listeners on the new instance and removes them from the previous one. - Type: `Redis | Cluster` ```js import Redis from 'iovalkey'; const store = new KeyvValkey('redis://localhost:6379'); console.log(store.client); // Redis instance // Replace with a new instance store.client = new Redis('redis://localhost:6380'); ``` ## Methods ### .get(key) Returns the value for the given key. Returns `undefined` if the key does not exist. Never returns `null`. ```js const value = await store.get('foo'); ``` ### .getMany(keys) Returns an array of values for the given keys. Returns `undefined` for any key that does not exist. Never returns `null` entries. In cluster mode, keys are grouped by hash slot and fetched with per-slot `MGET`. ```js const values = await store.getMany(['foo', 'bar']); ``` ### .set(key, value, expires?) Sets a value for the given key with an optional absolute `expires` (Unix ms since epoch). The adapter writes it via `PXAT`. Through Keyv (`keyv.set(key, value, ttl)`) you still pass a relative TTL in milliseconds — Keyv converts it to `expires` for you. Returns `true` if the value was stored, or `false` if `value` is `undefined` or the write failed (the failure is also emitted as an `error` event). ```js await store.set('foo', 'bar'); await store.set('foo', 'bar', Date.now() + 5000); // expires in ~5 seconds ``` ### .setMany(entries) Sets multiple key-value pairs in a single batch operation using `MULTI/EXEC` transactions. Each entry is a `KeyvStorageEntry` object (`{ key: string, value: Value, expires?: number }`) where `expires` is an absolute Unix ms timestamp, and `Value` is inferred from the entries provided. Entries with `undefined` values are skipped. Returns a `boolean[]` with per-entry success tracking by inspecting each command's result. In cluster mode, entries are grouped by hash slot with results mapped back to the original order. ```js const results = await store.setMany([ { key: 'foo', value: 'bar' }, { key: 'baz', value: 'qux', expires: Date.now() + 5000 }, ]); // [true, true] ``` ### .delete(key) Deletes a key-value pair from the store. Returns `true` if the key existed and was deleted, `false` otherwise. ```js const deleted = await store.delete('foo'); ``` ### .deleteMany(keys) Deletes multiple key-value pairs from the store. Each key is deleted individually (cluster-safe; not a single `MULTI` batch). Returns a `boolean[]` indicating whether each key was deleted. ```js const results = await store.deleteMany(['foo', 'bar']); // [true, true] ``` ### .has(key) Returns `true` if the key exists in the store, `false` otherwise. ```js const exists = await store.has('foo'); ``` ### .hasMany(keys) Checks if multiple keys exist in the store in a single batch operation. In cluster mode, keys are grouped by hash slot. Returns an array of booleans. ```js const results = await store.hasMany(['foo', 'bar', 'baz']); // [true, true, false] ``` ### .clear() Clears all entries from the store. If a namespace is set, only entries within that namespace are cleared (`namespace:::*`, glob characters escaped), so a namespace that merely shares a prefix such as `users-archive` is left alone. A namespace that extends it with the separator, such as `users::archive`, cannot be distinguished from keys containing the separator and is cleared too, so keep the separator out of namespace names that have to stay apart; `useSets` doesn't fully separate them (see [useSets](#usesets)). If no namespace is set and `useSets` is `false`, this uses `KEYS *` and removes every key in the current database. In cluster mode every master node is searched. ```js await store.clear(); ``` ### .iterator() Returns an async iterator for iterating over all key-value pairs in the store. The iterator uses the namespace configured on the instance and the same key pattern as `clear()`, and in cluster mode it scans every master node. Missing values are yielded as `undefined`, never `null`. ```js for await (const [key, value] of store.iterator()) { console.log(key, value); } ``` ### .disconnect() Disconnects from the Valkey server. Subsequent operations on this adapter will throw. ```js await store.disconnect(); ``` ## Events `KeyvValkey` extends [Hookified](https://hookified.org), so you can use `on`, `once`, `off`, and `emit`. The adapter re-emits the following events from the underlying iovalkey client: | Event | Source | Payload | | --- | --- | --- | | `error` | client `error` | The `Error` from the client | | `connect` | client `connect` | The iovalkey client instance | | `reconnecting` | client `reconnecting` | Arguments from the client (e.g. delay) | | `disconnect` | client `close` | The iovalkey client instance | ```js const store = new KeyvValkey('redis://localhost:6379'); store.on('error', (error) => { console.error(error); }); store.on('connect', (client) => { console.log('connected', client); }); store.on('reconnecting', () => { console.log('reconnecting'); }); store.on('disconnect', () => { console.log('disconnected'); }); ``` Replacing `store.client` removes listeners from the previous client and attaches them to the new one, so events are not duplicated or leaked. ## Expiration and TTL Keyv hands this adapter an **absolute** expiry — a Unix timestamp in milliseconds — computed once on the Keyv host. The adapter writes it with `SET ... PXAT`, the absolute-expiry option, so the deadline is immune to clock skew and to any latency between Keyv computing the expiry and Valkey receiving the command. The same applies to `setMany`, including the per-hash-slot grouping used in cluster mode. Unlike the [Redis adapter](https://github.com/jaredwray/keyv/tree/main/storage/redis#expiration-and-ttl), there is **no relative `PX` fallback** and none is needed: `PXAT` was added in Redis 6.2, and every Valkey release is forked from Redis 7.2+, so absolute expiry is always available. You always call `keyv.set(key, value, ttl)` with a relative millisecond `ttl` (or rely on the `ttl` option); Keyv converts it to the absolute `PXAT` deadline for you. ## Clustering The adapter supports Valkey and Redis clusters via iovalkey's `Cluster` class. Pass a `Redis.Cluster` instance directly to the constructor: ```js import KeyvValkey from '@keyv/valkey'; import Redis from 'iovalkey'; const cluster = new Redis.Cluster([ { host: '127.0.0.1', port: 7001 }, { host: '127.0.0.1', port: 7002 }, { host: '127.0.0.1', port: 7003 }, ]); const store = new KeyvValkey(cluster); ``` `getMany`, `setMany`, and `hasMany` automatically group keys by hash slot and run separate commands per slot group. This avoids `CROSSSLOT` errors without any extra configuration. `deleteMany` deletes each key individually, which is also cluster-safe. `clear()` and `iterator()` search every master node, since `KEYS` and `SCAN` only see the node they run on, and remove or fetch the keys they find one hash slot at a time. Single-key methods (`get`, `set`, `delete`, `has`) work automatically in cluster mode — iovalkey routes each command to the correct node. ### `useSets` in cluster mode The tracking set and the data keys hash to different slots, which a cluster can't update in one `MULTI` transaction. In cluster mode the adapter updates them with separate commands instead. The commands run in an order that keeps every stored key in the set, even when another client writes, deletes or clears at the same time, or a command fails part-way: - `set()` and `setMany()` add keys to the set both before and after writing them. - `delete()` removes a key from the set between two `UNLINK`s. `clear()` does the same for every key it removes. The set can end up listing keys that are no longer stored, which `clear()` removes harmlessly. Each `set()` and `delete()` takes three round trips instead of one transaction. Every write in a namespace also updates the one node that holds the namespace's set. ## License [MIT © Jared Wray](LICENSE) ### @keyv/postgres URL: https://keyv.org/docs/storage-adapters/postgres/ # @keyv/postgres [keyv](https://github.com/jaredwray/keyv) > PostgreSQL storage adapter for Keyv [![build](https://github.com/jaredwray/keyv/actions/workflows/tests.yaml/badge.svg)](https://github.com/jaredwray/keyv/actions/workflows/tests.yaml) [![codecov](https://codecov.io/gh/jaredwray/keyv/branch/main/graph/badge.svg?token=bRzR3RyOXZ)](https://codecov.io/gh/jaredwray/keyv) [![npm](https://img.shields.io/npm/v/@keyv/postgres.svg)](https://www.npmjs.com/package/@keyv/postgres) [![npm](https://img.shields.io/npm/dm/@keyv/postgres)](https://npmjs.com/package/@keyv/postgres) PostgreSQL storage adapter for [Keyv](https://github.com/jaredwray/keyv). Requires Postgres 9.5 or newer for `ON CONFLICT` support to allow performant upserts. [Why?](https://stackoverflow.com/questions/17267417/how-to-upsert-merge-insert-on-duplicate-update-in-postgresql/17267423#17267423) ## Table of Contents - [Install](#install) - [Usage](#usage) - [Migrating to v6](#migrating-to-v6) - [Constructor Options](#constructor-options) - [Properties](#properties) - [capabilities](#capabilities) - [uri](#uri) - [table](#table) - [keyLength](#keylength) - [namespaceLength](#namespacelength) - [schema](#schema) - [ssl](#ssl) - [iterationLimit](#iterationlimit) - [useUnloggedTable](#useunloggedtable) - [clearExpiredInterval](#clearexpiredinterval) - [namespace](#namespace) - [Methods](#methods) - [.get(key)](#getkey) - [.getMany(keys)](#getmanykeys) - [.set(key, value, expires?)](#setkey-value-expires) - [.setMany(entries)](#setmanyentries) - [.delete(key)](#deletekey) - [.deleteMany(keys)](#deletemanykeys) - [.has(key)](#haskey) - [.hasMany(keys)](#hasmanykeys) - [.clear()](#clear) - [.clearExpired()](#clearexpired) - [.iterator()](#iterator) - [.disconnect()](#disconnect) - [Events and Hooks](#events-and-hooks) - [Using an Unlogged Table for Performance](#using-an-unlogged-table-for-performance) - [Connection Pooling](#connection-pooling) - [SSL/TLS Connections](#ssltls-connections) - [Amazon RDS for PostgreSQL](#amazon-rds-for-postgresql) - [Testing](#testing) - [License](#license) # Install ```shell npm install --save keyv @keyv/postgres ``` # Usage ```js import Keyv from 'keyv'; import KeyvPostgres from '@keyv/postgres'; const store = new KeyvPostgres('postgresql://user:pass@localhost:5432/dbname'); store.on('error', (error) => { console.error(error); }); const keyv = new Keyv({ store }); ``` You can specify the `table` and `schema` options: ```js const keyvPostgres = new KeyvPostgres({ uri: 'postgresql://user:pass@localhost:5432/dbname', table: 'cache', schema: 'keyv' }); const keyv = new Keyv({ store: keyvPostgres }); ``` You can also use the `createKeyv` helper function to create `Keyv` with `KeyvPostgres` store: ```js import { createKeyv } from '@keyv/postgres'; const keyv = createKeyv({ uri: 'postgresql://user:pass@localhost:5432/dbname', table: 'cache', schema: 'keyv' }); ``` # Migrating to v6 ## Breaking changes v6 changes how namespaces are stored and which base class the adapter extends. Configuration is now exposed through dedicated [properties](#properties) (getters/setters) on the instance rather than a generic options bag. The sections below describe the changes and how to migrate existing data. ### Native namespace support In v5, namespaces were stored as key prefixes in the `key` column (e.g. `key="myns:mykey"` with `namespace=NULL`). In v6, the namespace is stored in a dedicated `namespace` column (e.g. `key="mykey"`, `namespace="myns"`). This enables more efficient queries and proper namespace isolation. The adapter automatically adds the `namespace` column and creates the appropriate index when it connects, so no manual schema changes are needed for new installations. ### Hookified integration The adapter now extends [Hookified](https://hookified.org) instead of a custom EventEmitter. Use `on` / `once` / `emit` for events. Connection and query failures emit `error`. Middleware hooks (`onHook`, `hook`) are available but are **not** invoked automatically on `get`/`set` — Keyv core owns those hooks. See [Events and Hooks](#events-and-hooks). ### `keySize` renamed to `keyLength`, `dialect` removed The v5 `keySize` option is now `keyLength`, and the `dialect` option is gone. TypeScript rejects both old names. In JavaScript, v6 does not read them and passes them on to the `pg` pool config, so an old `keySize` has no effect. ```js // v5 const store = new KeyvPostgres({ uri, keySize: 512 }); // v6 const store = new KeyvPostgres({ uri, keyLength: 512 }); ``` `keyLength` only sets the key column size when the adapter creates the table. An existing table keeps its current key column. The [migration script](#running-the-migration-script) is different: it resizes the key column to `--keyLength` (default `255`). If you used a custom `keySize` in v5, pass the same value with `--keyLength`. ## New features ### Native TTL support with `expires` column v6 adds an `expires BIGINT` column to the table. Keyv core converts a relative TTL into an absolute Unix-ms timestamp and passes it to `set`/`setMany`; the adapter stores that timestamp in the column. It does **not** parse expiry out of the serialized value. A partial index is created on `expires` for efficient cleanup queries. The schema migration is automatic on connect — existing tables get the column added via `ADD COLUMN IF NOT EXISTS`. Legacy rows still need the [migration script](#running-the-migration-script) so namespaced keys and existing JSON `expires` values are rewritten. ### `clearExpired()` method A new utility method that deletes all rows where the `expires` column is set and the timestamp is in the past: ```js await store.clearExpired(); ``` ### `clearExpiredInterval` option Set an interval (in milliseconds) to automatically call `clearExpired()` on a schedule. Disabled by default (`0`). The timer uses `unref()` so it won't keep the Node.js process alive. ```js const store = new KeyvPostgres({ uri: 'postgresql://user:pass@localhost:5432/dbname', clearExpiredInterval: 60_000, // clean up every 60 seconds }); ``` ### Bulk operations New methods for efficient multi-key operations: - `.setMany(entries)` — bulk upsert using PostgreSQL `UNNEST` - `.getMany(keys)` — bulk retrieve using `ANY` - `.deleteMany(keys)` — bulk delete using `ANY` - `.hasMany(keys)` — bulk existence check ### `createKeyv()` helper A convenience function to create a `Keyv` instance with `KeyvPostgres` as the store in one call: ```js import { createKeyv } from '@keyv/postgres'; const keyv = createKeyv({ uri: 'postgresql://user:pass@localhost:5432/dbname' }); ``` ### Improved iterator The iterator now uses cursor-based (keyset) pagination instead of `OFFSET`. This handles concurrent deletions during iteration without skipping entries and is more efficient for large datasets. ## Running the migration script If you have existing data from v5, you need to run the migration script to move namespace prefixes from keys into the new `namespace` column. The script ships in the npm package at `scripts/migrate-v6.ts`. Run it from your project root with `tsx`. Node.js refuses to strip TypeScript types from files under `node_modules`, so running the script with plain `node` from there fails with `ERR_UNSUPPORTED_NODE_MODULES_TYPE_STRIPPING`. Preview the changes first with `--dry-run`. Dry-run mode only reads schema metadata and previews affected rows; it does not modify the schema or data: ```shell npx tsx node_modules/@keyv/postgres/scripts/migrate-v6.ts --uri postgresql://user:pass@localhost:5432/dbname --dry-run ``` Run the migration: ```shell npx tsx node_modules/@keyv/postgres/scripts/migrate-v6.ts --uri postgresql://user:pass@localhost:5432/dbname ``` You can also specify a custom table, schema, and column lengths: ```shell npx tsx node_modules/@keyv/postgres/scripts/migrate-v6.ts --uri postgresql://user:pass@localhost:5432/dbname --table cache --schema keyv npx tsx node_modules/@keyv/postgres/scripts/migrate-v6.ts --uri postgresql://user:pass@localhost:5432/dbname --keyLength 512 --namespaceLength 512 ``` From a clone of this repo you can run `node scripts/migrate-v6.ts` in `storage/postgres` with the same flags. The data rewrite runs inside a transaction and will roll back automatically if it fails. **Important notes:** - Dry-run does not add columns, drop the legacy primary key, or rewrite rows. - The script drops the legacy single-column primary key on `key` **before** rewriting rows. That is required so two namespaces can share the same unprefixed key (for example `ns1:foo` and `ns2:foo` both become `key=foo` with different `namespace` values). - After the data rewrite it creates the unique `(key, COALESCE(namespace, ''))` index and the partial `expires` index, matching what the adapter creates on connect. - The script only migrates rows where `namespace IS NULL` (or all colon-prefixed keys if the column does not exist yet). Rows that already have a namespace value (e.g. from a partial earlier migration) are skipped. - Keys are split on the first colon — the part before becomes the namespace, the rest becomes the key. Namespaces containing colons are not supported. - Keyv v5 used `keyv` as the namespace when none was set, so rows written that way migrate into namespace `keyv`. Pass `namespace: 'keyv'` to Keyv afterwards to keep reading them. See the [v5 to v6 migration guide](https://keyv.org/docs/migration/v5-to-v6/#the-default-keyv-namespace-was-removed). - The `expires` column is populated from legacy JSON envelopes (`{"value":...,"expires":...}`). Non-JSON values (compressed, encrypted, custom serializers) are left with `expires` NULL; new writes from Keyv v6 store expiry in the column directly. # Constructor Options `KeyvPostgres` accepts a connection URI string or an options object. The options object accepts the following properties along with any [`PoolConfig`](https://node-postgres.com/apis/pool) properties from the `pg` library (e.g. `max`, `idleTimeoutMillis`, `connectionTimeoutMillis`): | Option | Type | Default | Description | | --- | --- | --- | --- | | `uri` | `string` | `'postgresql://localhost:5432'` | PostgreSQL connection URI | | `table` | `string` | `'keyv'` | Table name for key-value storage | | `keyLength` | `number` | `255` | Maximum key column length (VARCHAR length) | | `namespaceLength` | `number` | `255` | Maximum namespace column length (VARCHAR length) | | `schema` | `string` | `'public'` | PostgreSQL schema name (created automatically if it doesn't exist) | | `ssl` | `boolean \| ConnectionOptions` | `undefined` | SSL/TLS configuration passed to the `pg` driver (`true`/`false` or a Node.js `tls.ConnectionOptions` object) | | `iterationLimit` | `number` | `10` | Number of rows fetched per batch during iteration | | `useUnloggedTable` | `boolean` | `false` | Use a PostgreSQL UNLOGGED table for better write performance | | `clearExpiredInterval` | `number` | `0` | Interval in milliseconds to automatically clear expired entries (0 = disabled) | # Properties All configuration options are exposed as properties with getters and setters on the `KeyvPostgres` instance. `namespace`, `iterationLimit`, and `clearExpiredInterval` take effect immediately. `uri` and `ssl` are applied when the connection pool is created (constructor); changing them later does not reconnect. `table`, `schema`, `keyLength`, `namespaceLength`, and `useUnloggedTable` are used to create/migrate the table at construction — changing `table`/`schema` afterward retargets subsequent queries but does not create the new table. ## capabilities Read-only capability descriptor from Keyv core. Declares the v6 absolute-`expires` storage contract (`expires: true`) so Keyv does not wrap the adapter in a relative-TTL bridge. - Type: `KeyvStorageCapability` (from `keyv`) - Default: computed from the instance (`compatible`, `store: 'keyvStorage'`, method map, `expires: true`) ```js const store = new KeyvPostgres({ uri: 'postgresql://user:pass@localhost:5432/dbname' }); console.log(store.capabilities.expires); // true ``` ## uri Get or set the PostgreSQL connection URI. The URI is used when the connection pool is created, so changing it afterwards does not reconnect; `disconnect()` still releases the pool the adapter connected with. - Type: `string` - Default: `'postgresql://localhost:5432'` ```js const store = new KeyvPostgres({ uri: 'postgresql://user:pass@localhost:5432/dbname' }); console.log(store.uri); // 'postgresql://user:pass@localhost:5432/dbname' ``` ## table Get or set the table name used for storage. - Type: `string` - Default: `'keyv'` ```js const store = new KeyvPostgres({ uri: 'postgresql://user:pass@localhost:5432/dbname' }); console.log(store.table); // 'keyv' store.table = 'cache'; ``` ## keyLength Get or set the maximum key length (VARCHAR length) for the key column. - Type: `number` - Default: `255` ```js const store = new KeyvPostgres({ uri: 'postgresql://user:pass@localhost:5432/dbname', keyLength: 512 }); console.log(store.keyLength); // 512 ``` ## namespaceLength Get or set the maximum namespace length (VARCHAR length) for the namespace column. - Type: `number` - Default: `255` ```js const store = new KeyvPostgres({ uri: 'postgresql://user:pass@localhost:5432/dbname', namespaceLength: 512 }); console.log(store.namespaceLength); // 512 ``` ## schema Get or set the PostgreSQL schema name. Non-public schemas are created automatically if they don't exist. - Type: `string` - Default: `'public'` ```js const store = new KeyvPostgres({ uri: 'postgresql://user:pass@localhost:5432/dbname', schema: 'keyv' }); console.log(store.schema); // 'keyv' ``` ## ssl Get or set the SSL configuration for the PostgreSQL connection. Passed directly to the `pg` driver. - Type: `boolean | ConnectionOptions | undefined` - Default: `undefined` ```js const store = new KeyvPostgres({ uri: 'postgresql://user:pass@localhost:5432/dbname', ssl: { rejectUnauthorized: false }, }); console.log(store.ssl); // { rejectUnauthorized: false } ``` ## iterationLimit Get or set the number of rows to fetch per iteration batch. - Type: `number` - Default: `10` ```js const store = new KeyvPostgres({ uri: 'postgresql://user:pass@localhost:5432/dbname', iterationLimit: 50 }); console.log(store.iterationLimit); // 50 ``` ## useUnloggedTable Get or set whether to use a PostgreSQL unlogged table for better write performance. Unlogged tables are faster but data is lost on crash. - Type: `boolean` - Default: `false` ```js const store = new KeyvPostgres({ uri: 'postgresql://user:pass@localhost:5432/dbname', useUnloggedTable: true }); console.log(store.useUnloggedTable); // true ``` ## clearExpiredInterval Get or set the interval in milliseconds between automatic expired-entry cleanup runs. When set to a value greater than 0, the adapter will automatically call `clearExpired()` at the specified interval. The timer uses `unref()` so it won't keep the Node.js process alive. Setting to 0 disables the automatic cleanup. An interval longer than about 24.8 days (2,147,483,647 ms, the longest delay Node.js timers accept) runs cleanup at that limit. - Type: `number` - Default: `0` (disabled) ```js // Clean up expired entries every 60 seconds const store = new KeyvPostgres({ uri: 'postgresql://user:pass@localhost:5432/dbname', clearExpiredInterval: 60_000 }); console.log(store.clearExpiredInterval); // 60000 // Disable it later store.clearExpiredInterval = 0; ``` ## namespace Get or set the namespace for the adapter. Used for key prefixing and scoping operations like `clear()`. - Type: `string | undefined` - Default: `undefined` ```js const store = new KeyvPostgres({ uri: 'postgresql://user:pass@localhost:5432/dbname' }); store.namespace = 'my-namespace'; console.log(store.namespace); // 'my-namespace' ``` # Methods ## .get(key) Get a value by key. Returns `undefined` if the key does not exist or has expired. A SQL `NULL` value is normalized to `undefined` (the adapter never returns `null`). - `key` *(string)* - The key to retrieve. - Returns: `Promise` ```js const value = await store.get('foo'); // 'bar' ``` ## .getMany(keys) Get multiple values at once. Returns an array of values in the same order as the keys, with `undefined` for missing, expired, or SQL `NULL` entries (never `null`). - `keys` *(string[])* - The keys to retrieve. - Returns: `Promise>` ```js const values = await store.getMany(['foo', 'baz']); // ['bar', 'qux'] ``` ## .set(key, value, expires?) Set a key-value pair. Returns `true` on success, `false` on failure (an `error` event is also emitted). - `key` *(string)* - The key to set. - `value` *(any)* - The value to store. - `expires` *(number, optional)* - Absolute expiry as Unix milliseconds since epoch. `undefined` means no expiry. A value `<= Date.now()` is already expired. - Returns: `Promise` When you call `keyv.set(key, value, ttl)` on a Keyv instance, core converts the relative TTL into this absolute `expires` timestamp before it reaches the adapter. Do not pass a relative TTL to `KeyvPostgres#set` directly. ```js await store.set('foo', 'bar'); await store.set('foo', 'bar', Date.now() + 5000); // expires in 5 seconds ``` ## .setMany(entries) Set multiple key-value pairs at once using a single atomic PostgreSQL `INSERT ... UNNEST ... ON CONFLICT` statement. Each entry is a `KeyvStorageEntry` object (`{ key: string, value: Value, expires?: number }`), where `expires` is an absolute Unix-ms timestamp and `Value` is inferred from the entries provided. Returns a `boolean[]` indicating whether each entry was set successfully. Since the SQL statement is atomic, all entries either succeed (`true`) or all fail (`false`) together. On failure, an `error` event is emitted. An empty input returns `[]`. - `entries` *(KeyvStorageEntry[])* - The entries to upsert. - Returns: `Promise` ```js const results = await store.setMany([ { key: 'foo', value: 'bar' }, { key: 'baz', value: 'qux', expires: Date.now() + 5000 }, ]); // [true, true] ``` ## .delete(key) Delete a key. Returns `true` if the key existed, `false` otherwise. - `key` *(string)* - The key to delete. - Returns: `Promise` ```js const deleted = await store.delete('foo'); // true ``` ## .deleteMany(keys) Delete multiple keys at once. Returns a `boolean[]` indicating whether each key existed. - `keys` *(string[])* - The keys to delete. - Returns: `Promise` ```js const results = await store.deleteMany(['foo', 'baz']); // [true, true] ``` ## .has(key) Check if a key exists. Expired entries are deleted on check and reported as missing. - `key` *(string)* - The key to check. - Returns: `Promise` ```js const exists = await store.has('foo'); // true ``` ## .hasMany(keys) Check if multiple keys exist. Returns an array of booleans in the same order as the input keys. Expired entries are deleted on check and reported as missing. - `keys` *(string[])* - The keys to check. - Returns: `Promise` ```js await store.set('foo', 'bar'); await store.set('baz', 'qux'); const results = await store.hasMany(['foo', 'baz', 'unknown']); // [true, true, false] ``` ## .clear() Clear all keys in the current namespace. If no namespace is set, only keys without a namespace (SQL `NULL`) are removed. - Returns: `Promise` ```js await store.clear(); ``` ## .clearExpired() Utility helper method to delete all expired entries from the store. This removes any rows where the `expires` column is set and the timestamp is in the past. This is useful for periodic cleanup of expired data. - Returns: `Promise` ```js await store.clearExpired(); ``` ## .iterator() Iterate over all key-value pairs. The iterator uses the namespace configured on the instance. Uses cursor-based pagination controlled by the `iterationLimit` property. SQL `NULL` values are yielded as `undefined` (never `null`). Expired rows are skipped. - Returns: `AsyncGenerator<[string, string | undefined]>` ```js const iterator = store.iterator(); for await (const [key, value] of iterator) { console.log(key, value); } ``` ## .disconnect() Disconnect from the PostgreSQL database and release this instance's connection-pool reference. The shared `pg.Pool` is closed when the last adapter using it disconnects. Also stops the automatic expired-entry cleanup interval if running. The reference released is the one taken when the adapter connected, even if `uri` or `ssl` changed since. It is released only once, so calling `disconnect()` again has no further effect. - Returns: `Promise` ```js await store.disconnect(); ``` # Events and Hooks `KeyvPostgres` extends [Hookified](https://hookified.org) with `throwOnEmptyListeners: false`, so emitting `error` with no listeners does not throw. **Events** (`on`, `once`, `emit`): - `error` — connection failures (constructor init) and query failures (`set` / `setMany`). Listen on the **adapter**, not only on the wrapping `Keyv` instance. ```js const store = new KeyvPostgres('postgresql://user:pass@localhost:5432/dbname'); store.on('error', (error) => { console.error(error); }); ``` **Hooks** (`onHook`, `hook`): available for custom middleware. The adapter does not call `hook()` on `get`/`set`/`delete` — those hooks belong to Keyv core. Register a hook and invoke it yourself when you need adapter-level middleware: ```js store.onHook('audit', (action, key) => { console.log(action, key); }); await store.hook('audit', 'set', 'foo'); ``` # Using an Unlogged Table for Performance By default, the adapter creates a logged table. If you want to use an unlogged table for performance, you can pass the `useUnloggedTable` option to the constructor. ```js const keyvPostgres = new KeyvPostgres({ uri: 'postgresql://user:pass@localhost:5432/dbname', useUnloggedTable: true }); const keyv = new Keyv({ store: keyvPostgres }); ``` From the [PostgreSQL documentation](https://www.postgresql.org/docs/current/sql-createtable.html#SQL-CREATETABLE-UNLOGGED): If specified, the table is created as an unlogged table. Data written to unlogged tables is not written to the write-ahead log (see Chapter 28), which makes them considerably faster than ordinary tables. However, they are not crash-safe: an unlogged table is automatically truncated after a crash or unclean shutdown. The contents of an unlogged table are also not replicated to standby servers. Any indexes created on an unlogged table are automatically unlogged as well. If this is specified, any sequences created together with the unlogged table (for identity or serial columns) are also created as unlogged. # Connection Pooling The adapter automatically uses the default settings on the `pg` package for connection pooling. You can override these settings by passing the options to the constructor such as setting the `max` pool size. ```js const keyv = new Keyv({ store: new KeyvPostgres({ uri: 'postgresql://user:pass@localhost:5432/dbname', max: 20 }) }); ``` Adapters that share the same URI and pool options reuse a single `pg.Pool`. `disconnect()` releases this instance's reference; the underlying pool is closed only when the last adapter using it disconnects. # SSL/TLS Connections You can configure SSL/TLS connections by passing the `ssl` option. This is passed directly to the underlying `pg` driver. ```js const keyvPostgres = new KeyvPostgres({ uri: 'postgresql://user:pass@localhost:5432/dbname', ssl: { rejectUnauthorized: false, }, }); const keyv = new Keyv({ store: keyvPostgres }); ``` For more details on SSL configuration, see the [node-postgres SSL documentation](https://node-postgres.com/features/ssl). # Amazon RDS for PostgreSQL `@keyv/postgres` connects to Amazon RDS for PostgreSQL with the same `uri` and `ssl` options it uses for any PostgreSQL server. The adapter passes `uri` to `pg` as its `connectionString` and passes `ssl` to `pg` unchanged, so the TLS settings below are standard `pg` settings. `createKeyv` accepts the same options. ## Connection URI The endpoint and port are on the **Connectivity & security** tab of the DB instance in the RDS console. Put them in a regular PostgreSQL URI along with the database user, password, and database name: ```js const uri = 'postgresql://user:pass@mydb.123456789012.us-east-1.rds.amazonaws.com:5432/dbname'; ``` If the user name or password contains reserved URI characters such as `@`, `:`, `/`, or `#`, encode it first: ```js const password = encodeURIComponent(process.env.RDS_PASSWORD); const uri = `postgresql://keyv:${password}@mydb.123456789012.us-east-1.rds.amazonaws.com:5432/dbname`; ``` RDS for PostgreSQL 15 and later reject connections that don't use SSL, because the `rds.force_ssl` parameter defaults to `1`. On earlier versions it defaults to `0`. Encrypt and verify the connection in production either way. ## Verifying the server certificate with the RDS CA bundle RDS signs its server certificates with Amazon RDS certificate authorities, and Node.js does not trust those by default. Download the CA bundle from [Using SSL/TLS to encrypt a connection to a DB instance](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.SSL.html). `global-bundle.pem` covers every commercial AWS Region, and each Region also has its own bundle. Pass the bundle as `ssl.ca`: ```js import fs from 'node:fs'; import Keyv from 'keyv'; import KeyvPostgres from '@keyv/postgres'; const keyvPostgres = new KeyvPostgres({ uri: 'postgresql://user:pass@mydb.123456789012.us-east-1.rds.amazonaws.com:5432/dbname', ssl: { ca: fs.readFileSync('/path/to/global-bundle.pem').toString(), }, }); const keyv = new Keyv({ store: keyvPostgres }); ``` `rejectUnauthorized` defaults to `true`, so Node.js checks that the certificate was signed by an RDS CA and that it was issued for the hostname in `uri`. Connect with the RDS endpoint hostname. An IP address or your own DNS alias fails the hostname check. Don't use these settings for RDS in production: - `ssl: true` encrypts the connection but checks the certificate only against Node.js's built-in CAs. Verification fails because the RDS CAs aren't among them. - `ssl: { rejectUnauthorized: false }` connects, but accepts any certificate, so it does not protect against an attacker in the middle. The [SSL/TLS Connections](#ssltls-connections) sample uses it, and it is only suitable for local or test servers. ## Configuring TLS in the URI `pg` also reads SSL settings from query parameters on the URI, so you can configure TLS there instead of with the `ssl` option: ```js const keyvPostgres = new KeyvPostgres( 'postgresql://user:pass@mydb.123456789012.us-east-1.rds.amazonaws.com:5432/dbname?sslmode=verify-full&sslrootcert=/path/to/global-bundle.pem', ); ``` - Use `sslmode=verify-full`, which verifies both the CA and the hostname. `pg` 8 treats `prefer`, `require`, and `verify-ca` as `verify-full` and logs a security warning. As a result, `sslmode=require` without `sslrootcert` fails against RDS for the same reason `ssl: true` does. - `sslrootcert` is a file path, and `pg` reads the bundle from that file. - When the URI has SSL parameters, `pg` builds its SSL settings from the URI and ignores the `ssl` option. Configure TLS in one place, either on the URI or with `ssl`. # Testing When testing you can use our `docker compose` postgresql instance by having docker installed and running. This will start a postgres server, run the tests, and stop the server: At the root of the Keyv mono repo: ```shell pnpm test:services:start ``` To just test the postgres adapter go to the postgres directory (storage/postgres) and run: ```shell pnpm test ``` # License [MIT © Jared Wray](LICENSE) ### @keyv/mysql URL: https://keyv.org/docs/storage-adapters/mysql/ # @keyv/mysql [keyv](https://github.com/jaredwray/keyv) > MySQL/MariaDB storage adapter for Keyv [![build](https://github.com/jaredwray/keyv/actions/workflows/tests.yaml/badge.svg)](https://github.com/jaredwray/keyv/actions/workflows/tests.yaml) [![codecov](https://codecov.io/gh/jaredwray/keyv/branch/main/graph/badge.svg?token=bRzR3RyOXZ)](https://codecov.io/gh/jaredwray/keyv) [![npm](https://img.shields.io/npm/v/@keyv/mysql.svg)](https://www.npmjs.com/package/@keyv/mysql) [![npm](https://img.shields.io/npm/dm/@keyv/mysql)](https://npmjs.com/package/@keyv/mysql) MySQL/MariaDB storage adapter for [Keyv](https://github.com/jaredwray/keyv). ## Table of Contents - [Install](#install) - [Usage](#usage) - [Migrating to v6](#migrating-to-v6) - [Constructor Options](#constructor-options) - [Properties](#properties) - [uri](#uri) - [table](#table) - [keyLength](#keylength) - [namespaceLength](#namespacelength) - [iterationLimit](#iterationlimit) - [intervalExpiration](#intervalexpiration) - [namespace](#namespace-1) - [Namespace Support](#namespace-support) - [Methods](#methods) - [.get(key)](#getkey) - [.getMany(keys)](#getmanykeys) - [.set(key, value, expires?)](#setkey-value-expires) - [.setMany(entries)](#setmanyentries) - [.delete(key)](#deletekey) - [.deleteMany(keys)](#deletemanykeys) - [.clear()](#clear) - [.has(key)](#haskey) - [.hasMany(keys)](#hasmanykeys) - [.clearExpired()](#clearexpired) - [.iterator()](#iterator) - [.disconnect()](#disconnect) - [Connection Pooling](#connection-pooling) - [SSL](#ssl) - [License](#license) ## Install ```shell npm install --save keyv @keyv/mysql ``` ## Usage ```js import Keyv from 'keyv'; import KeyvMysql from '@keyv/mysql'; const keyv = new Keyv(new KeyvMysql('mysql://user:pass@localhost:3306/dbname')); keyv.on('error', handleConnectionError); ``` You can also use the `createKeyv` helper function to create a `Keyv` instance with `KeyvMysql` as the store: ```js import { createKeyv } from '@keyv/mysql'; const keyv = createKeyv('mysql://user:pass@localhost:3306/dbname'); ``` Or with an options object: ```js import { createKeyv } from '@keyv/mysql'; const keyv = createKeyv({ uri: 'mysql://user:pass@localhost:3306/dbname', table: 'cache', keyLength: 512 }); ``` You can specify a custom table with the `table` option and the primary key length with `keyLength`. To delete expired keys periodically in the background, specify `intervalExpiration` in seconds. e.g: ```js import Keyv from 'keyv'; import KeyvMysql from '@keyv/mysql'; const keyv = new Keyv(new KeyvMysql({ uri: 'mysql://user:pass@localhost:3306/dbname', table: 'cache', keyLength: 255, intervalExpiration: 60 })); ``` ## Migrating to v6 ### Breaking changes #### Native namespace support In v5, namespaces were stored as key prefixes in the `id` column (e.g. `id="myns:mykey"` with `namespace=''`). In v6, the namespace is stored in a dedicated `namespace` column (e.g. `id="mykey"`, `namespace="myns"`). This enables more efficient queries and proper namespace isolation. The adapter automatically adds the `namespace` column and makes `(namespace, id)` the table's primary key when it connects, so no manual schema changes are needed for new installations. It replaces v5's primary key on `id`, a primary key on only a prefix of `namespace` or `id` (which treats keys that share the prefix as one key), and the primary key MySQL generates for a table created without one, dropping its `my_row_id` column. Each is replaced in a single statement, so the table always has a primary key, as servers with `sql_require_primary_key` or generated invisible primary keys require. A primary key you added on any other column, including a `my_row_id` column of your own, is kept with its column, and `(namespace, id)` gets a unique index instead. #### `keySize` renamed to `keyLength` The `keySize` option and property has been renamed to `keyLength` for consistency with the migration script and to better reflect that it controls key length. ```js // v5 const store = new KeyvMysql({ uri, keySize: 512 }); store.keySize; // 512 // v6 const store = new KeyvMysql({ uri, keyLength: 512 }); store.keyLength; // 512 ``` ### New features #### Native TTL support with `expires` column v6 adds an `expires BIGINT` column to the table. When you store a value with a TTL through Keyv core, Keyv passes an absolute `expires` timestamp (Unix ms) to the adapter's `set`, and the adapter stores it in the column. The adapter does not parse the serialized value. The `intervalExpiration` application timer queries this column directly instead of extracting from JSON, which is significantly more efficient. The schema migration is automatic on connect — existing tables get the column and index added automatically. #### `clearExpired()` method A new utility method that deletes all rows where the `expires` column is set and the timestamp is in the past: ```js await keyvMysql.clearExpired(); ``` #### Bulk operations v6 adds new methods for efficient multi-key operations: - `.setMany(entries)` — bulk upsert using `ON DUPLICATE KEY UPDATE` - `.hasMany(keys)` — bulk existence check ### Running the migration script If you have existing data from v5, you need to run the migration script to move namespace prefixes from keys into the new `namespace` column. The script ships in the npm package at `scripts/migrate-v6.ts`. Run it from your project root with `tsx`. Node.js refuses to strip TypeScript types from files under `node_modules`, so running the script with plain `node` from there fails with `ERR_UNSUPPORTED_NODE_MODULES_TYPE_STRIPPING`. Preview the changes first with `--dry-run`: ```shell npx tsx node_modules/@keyv/mysql/scripts/migrate-v6.ts --uri mysql://user:pass@localhost:3306/dbname --dry-run ``` Dry-run mode only reads schema metadata and previews affected rows; it does not modify the schema or data. Run the migration: ```shell npx tsx node_modules/@keyv/mysql/scripts/migrate-v6.ts --uri mysql://user:pass@localhost:3306/dbname ``` You can also specify a custom table and column lengths: ```shell npx tsx node_modules/@keyv/mysql/scripts/migrate-v6.ts --uri mysql://user:pass@localhost:3306/dbname --table cache npx tsx node_modules/@keyv/mysql/scripts/migrate-v6.ts --uri mysql://user:pass@localhost:3306/dbname --keyLength 512 --namespaceLength 256 ``` From a clone of this repo you can run `node scripts/migrate-v6.ts` in `storage/mysql` with the same flags. The migration runs inside a transaction and will roll back automatically if anything fails. The migration script also populates the new `expires` column from existing JSON values in the `value` column. **Important notes:** - The script only migrates namespace rows where `namespace = ''` (the default). Rows that already have a namespace value (e.g. from a partial earlier migration) are skipped. - Keys are split on the first colon — the part before becomes the namespace, the rest becomes the key. Namespaces containing colons are not supported. - Keyv v5 used `keyv` as the namespace when none was set, so rows written that way migrate into namespace `keyv`. Pass `namespace: 'keyv'` to Keyv afterwards to keep reading them. See the [v5 to v6 migration guide](https://keyv.org/docs/migration/v5-to-v6/#the-default-keyv-namespace-was-removed). - The `expires` column is populated by extracting `value->'$.expires'` from existing JSON values. ## Constructor Options `KeyvMysql` accepts a connection URI string or an options object. The options object accepts the following properties along with any [`PoolOptions`](https://sidorares.github.io/node-mysql2/docs) from the `mysql2` library (e.g. `host`, `port`, `user`, `password`, `database`, `connectionLimit`): | Option | Type | Default | Description | | --- | --- | --- | --- | | `uri` | `string` | `'mysql://localhost'` | MySQL connection URI | | `table` | `string` | `'keyv'` | Table name for key-value storage | | `keyLength` | `number` | `255` | Maximum key length in Unicode code points | | `namespaceLength` | `number` | `255` | Maximum namespace length in Unicode code points | | `iterationLimit` | `number` | `10` | Number of rows fetched per batch during iteration | | `intervalExpiration` | `number` | `undefined` | Interval in seconds for application-level expiration cleanup | Because MySQL limits an InnoDB composite index to 3072 bytes and each Unicode code point may require four UTF-8 bytes, `keyLength + namespaceLength` must not exceed 768. The constructor, `resizeKeyColumns()`, and migration script reject larger combinations before changing the schema. ## Properties Connection and schema configuration is exposed through getter-only properties. `uri`, `table`, `keyLength`, and `namespaceLength` cannot be assigned directly because changing them requires asynchronous connection or schema work. Use the awaited `reconnect()`, `useTable()`, and `resizeKeyColumns()` methods instead. `iterationLimit`, `intervalExpiration`, and `namespace` remain mutable because their setters update live adapter behavior. ### uri Get the active MySQL connection URI. This property is getter-only; use `reconnect()` to change it. - Type: `string` - Default: `'mysql://localhost'` ```js const store = new KeyvMysql({ uri: 'mysql://user:pass@localhost:3306/dbname' }); console.log(store.uri); // 'mysql://user:pass@localhost:3306/dbname' ``` ### table Get the active table name. This property is getter-only; use `useTable()` to change it. - Type: `string` - Default: `'keyv'` ```js const store = new KeyvMysql({ uri: 'mysql://user:pass@localhost:3306/dbname' }); console.log(store.table); // 'keyv' ``` ### keyLength Get the active maximum key length in Unicode code points. This property is getter-only because it determines the initialized schema; use `resizeKeyColumns()` to change it. - Type: `number` - Default: `255` ```js const store = new KeyvMysql({ uri: 'mysql://user:pass@localhost:3306/dbname', keyLength: 512 }); console.log(store.keyLength); // 512 ``` ### namespaceLength Get the active maximum namespace length in Unicode code points. This property is getter-only because it determines the initialized schema; use `resizeKeyColumns()` to change it. - Type: `number` - Default: `255` ```js const store = new KeyvMysql({ uri: 'mysql://user:pass@localhost:3306/dbname', namespaceLength: 512 }); console.log(store.namespaceLength); // 512 ``` ### iterationLimit Get or set the number of rows to fetch per iteration batch. - Type: `number` - Default: `10` ```js const store = new KeyvMysql({ uri: 'mysql://user:pass@localhost:3306/dbname', iterationLimit: 50 }); console.log(store.iterationLimit); // 50 ``` ### intervalExpiration Get or set the interval in seconds for automatic expiration cleanup. When set to a value greater than 0, the adapter starts an unref'd application timer that periodically deletes expired entries. Changing the value restarts the timer, while `0` or `undefined` disables it. Cleanup runs never overlap, and changing the interval after `disconnect()` does not restart the timer. Values above `2147483.647` seconds are rejected because they exceed Node.js's maximum timer delay. The timer is stopped by `disconnect()` and does not require MySQL `EVENT` or global-variable privileges. - Type: `number | undefined` - Default: `undefined` (disabled) ```js const store = new KeyvMysql({ uri: 'mysql://user:pass@localhost:3306/dbname', intervalExpiration: 60 }); console.log(store.intervalExpiration); // 60 ``` Earlier v6 prereleases created a schema event named `keyv_delete_expired_keys`. The adapter no longer creates, changes, or drops server events. If that legacy event exists, a database administrator can remove it once with `DROP EVENT IF EXISTS keyv_delete_expired_keys`. ### namespace Get or set the namespace for the adapter. Used for key prefixing and scoping operations like `clear()`. - Type: `string | undefined` - Default: `undefined` ```js const store = new KeyvMysql({ uri: 'mysql://user:pass@localhost:3306/dbname' }); store.namespace = 'my-namespace'; console.log(store.namespace); // 'my-namespace' ``` ## Namespace Support The MySQL adapter supports native namespace scoping. When a namespace is set, keys are stored in a dedicated `namespace` column rather than being embedded in the key name. This provides efficient filtering and proper isolation between namespaces. Keys and namespaces are stored as exact UTF-8 bytes. Comparisons therefore preserve case, accents, Unicode normalization, and trailing spaces regardless of the database's default collation. For example, `AuditKey` and `auditkey`, composed and decomposed forms of `é`, and `key` and `key ` are all distinct. Existing text key columns are converted independently when the adapter initializes, preserving each column's existing character width. The unique composite index is ordered as `(namespace, id)`, allowing MySQL to use the same index for exact key lookups, namespace clears, and namespace-scoped iteration. Existing `(id, namespace)` indexes created by earlier v6 prereleases are replaced atomically. ```js import Keyv from 'keyv'; import KeyvMysql from '@keyv/mysql'; const keyvA = new Keyv({ store: new KeyvMysql(uri), namespace: 'cache-a' }); const keyvB = new Keyv({ store: new KeyvMysql(uri), namespace: 'cache-b' }); // These don't conflict despite having the same key name await keyvA.set('user:1', 'Alice'); await keyvB.set('user:1', 'Bob'); // clear() only affects the namespace it belongs to await keyvA.clear(); // Only clears 'cache-a' entries ``` ## Methods Runtime configuration methods are serialized with one another. Always await them before starting operations that must use the new configuration. `useTable()` and `resizeKeyColumns()` perform schema work and should be run while application writes are paused for a deterministic cutover. ### .reconnect(uri, mysqlOptions?) Creates a replacement mysql2 pool, initializes the currently configured table on it, and switches the adapter only after preparation succeeds. The previous pool remains active during preparation and is closed after its already-started queries settle. If preparation fails, the adapter keeps using the previous connection. Calling `reconnect()` after `disconnect()` reactivates the adapter and restarts automatic expiration cleanup when `intervalExpiration` is configured. - `uri` *(string)* - MySQL connection URI for the replacement pool. - `mysqlOptions` *(PoolOptions, optional)* - Replacement mysql2 pool options applied on top of the URI settings. When omitted, the replacement uses only the URI. - Returns: `Promise` ```js await keyvMysql.reconnect('mysql://user:pass@replica.example.com:3306/cache', { connectionLimit: 20 }); console.log(keyvMysql.uri); // the replica URI ``` ### .useTable(table) Creates or migrates the target table using the same initialization performed by the constructor, then makes it active. The previous table remains active if initialization fails. This method does not copy, move, or delete data from the previous table. - `table` *(string)* - Target table name. Database-qualified names such as `database.cache` are supported. - Returns: `Promise` ```js await keyvMysql.useTable('sessions'); console.log(keyvMysql.table); // 'sessions' ``` ### .resizeKeyColumns(options) Changes the logical character limits and resizes both `VARBINARY` columns in one `ALTER TABLE` operation. Omitted values keep their current limits. Before changing the schema, the adapter validates MySQL's composite-index limit and scans existing UTF-8 keys and namespaces. A narrowing change is rejected if stored data exceeds the requested limit, leaving the schema and active limits unchanged. - `options.keyLength` *(number, optional)* - New maximum key length in Unicode code points. - `options.namespaceLength` *(number, optional)* - New maximum namespace length in Unicode code points. - Returns: `Promise` ```js await keyvMysql.resizeKeyColumns({ keyLength: 384, namespaceLength: 128 }); console.log(keyvMysql.keyLength); // 384 console.log(keyvMysql.namespaceLength); // 128 ``` ### .get(key) Returns the value for the given key. Returns `undefined` if the key does not exist. ```js const value = await keyvMysql.get('foo'); ``` ### .getMany(keys) Returns an array of values for the given keys. Returns `undefined` for any key that does not exist. ```js const values = await keyvMysql.getMany(['foo', 'bar']); ``` ### .set(key, value, expires?) Sets a value for the given key. If the key already exists, it will be updated. Returns `true` on success, `false` on failure. - `key` *(string)* - The key to set. - `value` *(any)* - The value to store. - `expires` *(number, optional)* - Absolute expiry as a Unix timestamp in milliseconds (`Date.now() + ttl`). `undefined` means no expiry. - Returns: `Promise` When you call `keyv.set(key, value, ttl)` on a Keyv instance, `ttl` is still relative. Keyv converts it to `expires` before it calls the adapter. ```js await keyvMysql.set('foo', 'bar'); await keyvMysql.set('foo', 'bar', Date.now() + 5000); // expires in 5 seconds ``` ### .setMany(entries) Set multiple key-value pairs at once using a single atomic `INSERT ... ON DUPLICATE KEY UPDATE` statement. Each entry is a `KeyvStorageEntry` object (`{ key: string, value: Value, expires?: number }`), where `expires` is an absolute Unix timestamp in milliseconds and `Value` is inferred from the entries provided. Returns a `boolean[]` indicating whether each entry was set successfully. Since the SQL statement is atomic, all entries either succeed (`true`) or all fail (`false`) together. On failure, an `error` event is emitted. ```js const results = await keyvMysql.setMany([ { key: 'foo', value: 'bar' }, { key: 'baz', value: 'qux', expires: Date.now() + 5000 }, ]); // [true, true] ``` ### .delete(key) Deletes a key-value pair from the store. Returns `true` if the key existed and was deleted, `false` otherwise. ```js const deleted = await keyvMysql.delete('foo'); ``` ### .deleteMany(keys) Deletes multiple key-value pairs from the store. Returns a `boolean[]` indicating whether each key was deleted. ```js const results = await keyvMysql.deleteMany(['foo', 'bar']); // [true, true] ``` ### .clear() Clears all entries from the store. If a namespace is set, only entries within that namespace are cleared. ```js await keyvMysql.clear(); ``` ### .has(key) Returns `true` if the key exists in the store, `false` otherwise. ```js const exists = await keyvMysql.has('foo'); ``` ### .hasMany(keys) Check if multiple keys exist. Returns an array of booleans in the same order as the input keys. ```js await keyvMysql.set('foo', 'bar'); await keyvMysql.set('baz', 'qux'); const results = await keyvMysql.hasMany(['foo', 'baz', 'unknown']); // [true, true, false] ``` ### .clearExpired() Deletes all entries where the `expires` column is set and the timestamp is in the past. Useful for periodic cleanup of expired entries. ```js await keyvMysql.clearExpired(); ``` ### .iterator() Returns an async iterator for iterating over all key-value pairs in the store. The iterator uses the namespace configured on the instance. Uses keyset pagination to efficiently handle large datasets. ```js for await (const [key, value] of keyvMysql.iterator()) { console.log(key, value); } ``` ### .disconnect() Stops the adapter from accepting new queries, waits for queries that have already started, and closes the adapter's connection pool. Repeated calls are safe and wait for the same shutdown. ```js await keyvMysql.disconnect(); ``` ## Connection Pooling Each `KeyvMysql` adapter creates and owns one `mysql2` connection pool. Pools are not shared implicitly between adapter instances, even when those adapters use the same URI and connection options. This keeps connection configuration and shutdown isolated: disconnecting one adapter does not affect another adapter. Pool options such as `connectionLimit`, `maxIdle`, `idleTimeout`, and `queueLimit` are passed through to `mysql2` and apply separately to each adapter. If an application creates multiple adapters, account for the combined number of database connections. Call `disconnect()` when an adapter is no longer needed, especially for short-lived instances: ```js const store = new KeyvMysql({ uri: 'mysql://user:pass@localhost:3306/dbname', connectionLimit: 10, }); const keyv = new Keyv({ store }); try { await keyv.set('foo', 'bar'); } finally { await keyv.disconnect(); } ``` ## SSL SSL options are passed through to `mysql2` as part of the options object. The constructor takes a single argument, so include the `uri` alongside the `ssl` configuration: ```js import Keyv from 'keyv'; import KeyvMysql from '@keyv/mysql'; import fs from 'fs'; import path from 'path'; const keyvMysql = new KeyvMysql({ uri: 'mysql://user:pass@localhost:3306/dbname', ssl: { rejectUnauthorized: false, ca: fs.readFileSync(path.join(__dirname, '/certs/ca.pem')).toString(), key: fs.readFileSync(path.join(__dirname, '/certs/client-key.pem')).toString(), cert: fs.readFileSync(path.join(__dirname, '/certs/client-cert.pem')).toString(), }, }); const keyv = new Keyv({ store: keyvMysql }); ``` ## License [MIT © Jared Wray](LICENSE) ### @keyv/mongo URL: https://keyv.org/docs/storage-adapters/mongo/ # @keyv/mongo [keyv](https://github.com/jaredwray/keyv) > MongoDB storage adapter for Keyv [![build](https://github.com/jaredwray/keyv/actions/workflows/tests.yaml/badge.svg)](https://github.com/jaredwray/keyv/actions/workflows/tests.yaml) [![codecov](https://codecov.io/gh/jaredwray/keyv/branch/main/graph/badge.svg?token=bRzR3RyOXZ)](https://codecov.io/gh/jaredwray/keyv) [![npm](https://img.shields.io/npm/v/@keyv/mongo.svg)](https://www.npmjs.com/package/@keyv/mongo) [![npm](https://img.shields.io/npm/dm/@keyv/mongo)](https://npmjs.com/package/@keyv/mongo) MongoDB storage adapter for [Keyv](https://github.com/jaredwray/keyv). Uses TTL indexes to automatically remove expired documents. However [MongoDB doesn't guarantee data will be deleted immediately upon expiration](https://docs.mongodb.com/manual/core/index-ttl/#timing-of-the-delete-operation), so expiry dates are revalidated in Keyv. ## Table of Contents - [Install](#install) - [Usage](#usage) - [Constructor Options](#constructor-options) - [Properties](#properties) - [url](#url) - [collection](#collection) - [namespace](#namespace) - [useGridFS](#usegridfs) - [db](#db) - [readPreference](#readpreference) - [Methods](#methods) - [set](#set) - [setMany](#setmany) - [get](#get) - [getMany](#getmany) - [has](#has) - [hasMany](#hasmany) - [delete](#delete) - [deleteMany](#deletemany) - [clear](#clear) - [iterator](#iterator) - [disconnect](#disconnect) - [clearExpired](#clearexpired) - [clearUnusedFor](#clearunusedfor) - [Migration from v3 to v6](#migration-from-v3-to-v6) - [Running the migration script](#running-the-migration-script) - [License](#license) ## Install ```shell npm install --save keyv @keyv/mongo ``` ## Usage ```js import Keyv from 'keyv'; import KeyvMongo from '@keyv/mongo'; const keyv = new Keyv(new KeyvMongo('mongodb://user:pass@localhost:27017/dbname')); keyv.on('error', handleConnectionError); ``` You can specify the collection name, by default `'keyv'` is used. e.g: ```js const keyv = new Keyv(new KeyvMongo('mongodb://user:pass@localhost:27017/dbname', { collection: 'cache' })); ``` You can also use the `createKeyv` helper function to create a `Keyv` instance with `KeyvMongo` as the store: ```js import { createKeyv } from '@keyv/mongo'; const keyv = createKeyv('mongodb://user:pass@localhost:27017/dbname'); ``` ## Constructor Options The `KeyvMongo` constructor accepts a connection URI string or an options object: ```js // With URI string const store = new KeyvMongo('mongodb://user:pass@localhost:27017/dbname'); // With options object const store = new KeyvMongo({ url: 'mongodb://user:pass@localhost:27017/dbname', collection: 'cache', db: 'mydb', useGridFS: false, }); // With URI string and additional options const store = new KeyvMongo('mongodb://user:pass@localhost:27017/dbname', { collection: 'cache' }); ``` | Option | Type | Default | Description | |---|---|---|---| | `url` | `string` | `'mongodb://127.0.0.1:27017'` | MongoDB connection URI | | `collection` | `string` | `'keyv'` | Collection name for storage | | `namespace` | `string \| undefined` | `undefined` | Namespace for keys, stored in each document's `namespace` field | | `useGridFS` | `boolean` | `false` | Whether to use GridFS for storing values | | `db` | `string \| undefined` | `undefined` | Database name | | `readPreference` | `ReadPreference \| undefined` | `undefined` | MongoDB read preference for GridFS operations | Any additional options are passed through to the MongoDB driver as `MongoClientOptions`. ## Properties Most configuration options are exposed as properties with getters and setters on the `KeyvMongo` instance. You can read or update them after construction. Some properties like `useGridFS` are read-only and can only be set via the constructor. ### url Get or set the MongoDB connection URI. - Type: `string` - Default: `'mongodb://127.0.0.1:27017'` ```js const store = new KeyvMongo({ url: 'mongodb://user:pass@localhost:27017/dbname' }); console.log(store.url); // 'mongodb://user:pass@localhost:27017/dbname' ``` ### collection Get or set the collection name used for storage. - Type: `string` - Default: `'keyv'` ```js const store = new KeyvMongo({ url: 'mongodb://user:pass@localhost:27017/dbname' }); console.log(store.collection); // 'keyv' store.collection = 'cache'; ``` ### namespace Get or set the namespace for the adapter. It is stored in each document's `namespace` field (or `metadata.namespace` with GridFS) and scopes operations like `clear()`. - Type: `string | undefined` - Default: `undefined` ```js const store = new KeyvMongo({ url: 'mongodb://user:pass@localhost:27017/dbname' }); store.namespace = 'my-namespace'; console.log(store.namespace); // 'my-namespace' ``` ### useGridFS Get whether GridFS is used for storing values. When enabled, values are stored using MongoDB's GridFS specification, which is useful for storing large files. This property is read-only and can only be set via the constructor, because the connection shape differs between GridFS and standard modes. Each value is a GridFS file named after its key. `set` writes a new file and then deletes the key's older files, so a key keeps a single file. Reads always use the newest file for a key, and `delete` removes every file for it. - Type: `boolean` - Default: `false` - Read-only (set via constructor only) ```js const store = new KeyvMongo({ url: 'mongodb://user:pass@localhost:27017/dbname', useGridFS: true }); console.log(store.useGridFS); // true ``` ### db Get or set the database name for the MongoDB connection. - Type: `string | undefined` - Default: `undefined` ```js const store = new KeyvMongo({ url: 'mongodb://user:pass@localhost:27017', db: 'mydb' }); console.log(store.db); // 'mydb' ``` ### readPreference Get or set the MongoDB read preference for GridFS operations. - Type: `ReadPreference | undefined` - Default: `undefined` ```js import { ReadPreference } from 'mongodb'; const store = new KeyvMongo({ url: 'mongodb://user:pass@localhost:27017/dbname', useGridFS: true, readPreference: ReadPreference.SECONDARY, }); console.log(store.readPreference); // ReadPreference.SECONDARY ``` ## Methods ### set `set(key, value, expires?)` - Set a value in the store. - `key` *(string)* - The key to set. - `value` *(any)* - The value to store. - `expires` *(number, optional)* - Absolute expiry time as a Unix timestamp in milliseconds (`Date.now() + ttl`). If specified, the key expires at this time. - Returns: `Promise` Through a `Keyv` instance, `keyv.set(key, value, ttl)` still takes a relative `ttl` in milliseconds. Keyv converts it to `expires` before it calls the adapter. ```js const store = new KeyvMongo('mongodb://localhost:27017'); const keyv = new Keyv({ store }); await keyv.set('foo', 'bar'); await keyv.set('foo', 'bar', 5000); // Keyv takes a relative ttl: expires in 5 seconds await store.set('foo', 'bar', Date.now() + 5000); // the adapter takes an absolute expires ``` ### setMany `setMany(entries)` - Set multiple values in the store at once. - `entries` *(KeyvStorageEntry[])* - Array of entries to set. Each entry has a `key`, `value`, and optional `expires` (an absolute Unix timestamp in milliseconds). A `ttl` field is ignored. `Value` is inferred from the entries provided. - Returns: `Promise` - An array of booleans indicating whether each entry was set successfully. Through a `Keyv` instance, `keyv.setMany()` takes entries with a relative `ttl` (`{ key, value, ttl? }`) and converts them before it calls the adapter. In standard mode, uses a single unordered MongoDB `bulkWrite` operation for efficiency with per-entry error tracking — if individual writes fail, only those entries return `false`. In GridFS mode, each entry is set individually in parallel using `Promise.allSettled`, providing per-entry success tracking. ```js const store = new KeyvMongo('mongodb://localhost:27017'); const results = await store.setMany([ { key: 'key1', value: 'value1' }, { key: 'key2', value: 'value2', expires: Date.now() + 5000 }, ]); // [true, true] ``` ### get `get(key)` - Get a value from the store. - `key` *(string)* - The key to retrieve. - Returns: `Promise` - The stored value, or `undefined` if the key does not exist. In GridFS mode, `get` also updates the `lastAccessed` timestamp on the file, which is used by `clearUnusedFor`. ```js const store = new KeyvMongo('mongodb://localhost:27017'); const keyv = new Keyv({ store }); await keyv.set('foo', 'bar'); const value = await keyv.get('foo'); console.log(value); // 'bar' const missing = await keyv.get('nonexistent'); console.log(missing); // undefined ``` ### getMany `getMany(keys)` - Get multiple values from the store at once. - `keys` *(string[])* - Array of keys to retrieve. - Returns: `Promise>` - Array of values in the same order as the input keys. Missing keys return `undefined` at their position. In standard mode, uses a single MongoDB query with the `$in` operator for efficiency. In GridFS mode, each key is fetched individually. ```js const store = new KeyvMongo('mongodb://localhost:27017'); await store.set('key1', 'value1'); await store.set('key2', 'value2'); const values = await store.getMany(['key1', 'key2', 'key3']); console.log(values); // ['value1', 'value2', undefined] ``` ### has `has(key)` - Check if a key exists in the store. - `key` *(string)* - The key to check. - Returns: `Promise` - `true` if the key exists, `false` otherwise. ```js const store = new KeyvMongo('mongodb://localhost:27017'); const keyv = new Keyv({ store }); await keyv.set('foo', 'bar'); console.log(await keyv.has('foo')); // true console.log(await keyv.has('nonexistent')); // false ``` ### hasMany `hasMany(keys)` - Check if multiple keys exist in the store at once. - `keys` *(string[])* - Array of keys to check. - Returns: `Promise` - Array of booleans in the same order as the input keys. Uses a single MongoDB query with the `$in` operator for efficiency in both standard and GridFS modes. ```js const store = new KeyvMongo('mongodb://localhost:27017'); await store.set('key1', 'value1'); await store.set('key2', 'value2'); const results = await store.hasMany(['key1', 'key2', 'key3']); console.log(results); // [true, true, false] ``` ### delete `delete(key)` - Delete a key from the store. - `key` *(string)* - The key to delete. - Returns: `Promise` - `true` if the key was deleted, `false` if the key was not found. ```js const store = new KeyvMongo('mongodb://localhost:27017'); const keyv = new Keyv({ store }); await keyv.set('foo', 'bar'); console.log(await keyv.delete('foo')); // true console.log(await keyv.delete('nonexistent')); // false ``` ### deleteMany `deleteMany(keys)` - Delete multiple keys from the store at once. - `keys` *(string[])* - Array of keys to delete. - Returns: `Promise` - An array of booleans indicating whether each key was deleted. Each key is deleted individually in parallel so that per-key success/failure information is preserved in the returned array. ```js const store = new KeyvMongo('mongodb://localhost:27017'); await store.set('key1', 'value1'); await store.set('key2', 'value2'); const results = await store.deleteMany(['key1', 'key2', 'key3']); // [true, true, false] ``` ### clear `clear()` - Delete all keys in the current namespace. - Returns: `Promise` Only keys matching the current namespace are removed. If no namespace is set, all keys with an empty namespace are cleared. ```js const store = new KeyvMongo('mongodb://localhost:27017'); const keyv = new Keyv({ store, namespace: 'my-namespace' }); await keyv.set('key1', 'value1'); await keyv.set('key2', 'value2'); await keyv.clear(); // removes all keys in 'my-namespace' ``` ### iterator `iterator()` - Iterate over all key-value pairs in the store. The iterator uses the namespace configured on the instance. - Returns: `AsyncGenerator<[string, any]>` - An async generator yielding `[key, value]` pairs. ```js const store = new KeyvMongo('mongodb://localhost:27017'); const keyv = new Keyv({ store, namespace: 'ns' }); await keyv.set('key1', 'value1'); await keyv.set('key2', 'value2'); for await (const [key, value] of keyv.iterator()) { console.log(key, value); // 'key1' 'value1', 'key2' 'value2' } ``` ### disconnect `disconnect()` - Close the MongoDB connection. - Returns: `Promise` ```js const store = new KeyvMongo('mongodb://localhost:27017'); const keyv = new Keyv({ store }); // ... use the store ... await keyv.disconnect(); ``` ### clearExpired `clearExpired()` - Remove all expired files from GridFS. This method only works in GridFS mode and is a no-op that returns `false` in standard mode. - Returns: `Promise` - `true` if running in GridFS mode, `false` otherwise. This is useful for manual cleanup of expired GridFS files, since GridFS does not support MongoDB TTL indexes. ```js const store = new KeyvMongo({ url: 'mongodb://localhost:27017', useGridFS: true }); await store.set('temp', 'data', Date.now() + 1000); // adapter takes an absolute expires (Unix ms); expires in ~1 second // After expiration... await store.clearExpired(); // removes expired GridFS files ``` ### clearUnusedFor `clearUnusedFor(seconds)` - Remove all GridFS files that have not been accessed for the specified duration. This method only works in GridFS mode and is a no-op that returns `false` in standard mode. - `seconds` *(number)* - The number of seconds of inactivity after which files should be removed. - Returns: `Promise` - `true` if running in GridFS mode, `false` otherwise. The `lastAccessed` timestamp is updated each time a file is read via `get`. ```js const store = new KeyvMongo({ url: 'mongodb://localhost:27017', useGridFS: true }); await store.set('foo', 'bar'); // Remove files not accessed in the last hour await store.clearUnusedFor(3600); ``` ## Migration from v3 to v6 `@keyv/mongo` is jumping from v3 to v6 because the entire Keyv monorepo is now unified under a single version number. This approach, similar to what other popular open source projects do, keeps all `@keyv/*` packages in sync and makes it easier to reason about compatibility across the ecosystem. ### Breaking Changes #### MongoDB Driver Upgraded to v7 The `mongodb` dependency has been upgraded from `^6.x` to `^7.0.0`. Review the [MongoDB Node.js Driver v7 release notes](https://github.com/mongodb/node-mongodb-native/releases/tag/v7.0.0) for any breaking changes that may affect your application. #### Event Handling: EventEmitter Replaced with Hookified `KeyvMongo` no longer extends Node.js `EventEmitter`. It now extends `Hookified`, which provides hook-based event management. ```js // v3 - EventEmitter const store = new KeyvMongo('mongodb://localhost:27017'); store.on('error', err => console.error(err)); // v6 - Hookified (same usage for basic events) const store = new KeyvMongo('mongodb://localhost:27017'); store.on('error', err => console.error(err)); ``` For most use cases the `.on()` API is the same, but if you relied on EventEmitter-specific methods like `.listenerCount()`, `.rawListeners()`, or `.prependListener()`, check the [Hookified documentation](https://github.com/jaredwray/hookified) for equivalents. #### `useGridFS` is Now Read-Only The `useGridFS` property can no longer be changed after construction. The connection shape differs between GridFS and standard modes, so this must be set at construction time. ```js // v3 - Could change after instantiation const store = new KeyvMongo('mongodb://localhost:27017'); store.useGridFS = true; // worked in v3 // v6 - Must set at construction const store = new KeyvMongo({ url: 'mongodb://localhost:27017', useGridFS: true }); console.log(store.useGridFS); // true (read-only) ``` #### `ttlSupport` Property Removed The `ttlSupport` property has been removed. If your code checks for TTL support on the adapter, remove those checks. #### `set` Takes an Absolute `expires` The third argument of the adapter's `set` is now an absolute Unix timestamp in milliseconds, not a relative `ttl`. This only affects code that calls the adapter directly. `keyv.set(key, value, ttl)` still takes a relative `ttl`. ```js // v3 - relative ttl await store.set('foo', 'bar', 5000); // v6 - absolute expires await store.set('foo', 'bar', Date.now() + 5000); ``` #### Namespaces Are Stored in Their Own Field v3 stored the namespace as a prefix of each key (`key: "keyv:foo"`) and wrote no namespace field. v6 stores it separately (`key: "foo"`, `namespace: "keyv"`) and only reads documents that have a `namespace` field, so documents written by v3 stay invisible to v6 until you [run the migration script](#running-the-migration-script). The unique index on the underlying MongoDB collection has also changed from `{ key: 1 }` to `{ key: 1, namespace: 1 }`, so the same key can exist in different namespaces. The adapter drops the old index and creates the new one when it connects. #### Options Type is Now Strongly Typed The constructor options no longer accept arbitrary keys via `[key: string]: unknown`. Options are now strictly typed with explicit properties. Any additional MongoDB driver options should be valid `MongoClientOptions` properties. ```js // v3 - Accepted any properties const store = new KeyvMongo({ url: 'mongodb://...', customProp: true }); // no type error // v6 - Strictly typed const store = new KeyvMongo({ url: 'mongodb://...', collection: 'cache' }); // only known props + MongoClientOptions ``` ### New Features #### `createKeyv` Helper Function A new `createKeyv` helper simplifies creating a Keyv instance with the MongoDB adapter. ```js import { createKeyv } from '@keyv/mongo'; // Before const store = new KeyvMongo('mongodb://localhost:27017'); const keyv = new Keyv({ store, namespace: 'my-ns' }); // After const keyv = createKeyv({ url: 'mongodb://localhost:27017', namespace: 'my-ns' }); ``` #### `setMany` Method Batch set multiple key-value pairs in a single operation using MongoDB `bulkWrite`. Each entry takes an optional absolute `expires` timestamp (Unix ms). ```js await store.setMany([ { key: 'key1', value: 'value1' }, { key: 'key2', value: 'value2', expires: Date.now() + 5000 }, ]); ``` #### `hasMany` Method Check if multiple keys exist in a single query using the `$in` operator. ```js const results = await store.hasMany(['key1', 'key2', 'key3']); // [true, true, false] ``` #### `clearExpired` Method Manually remove expired files from GridFS storage. ```js const store = new KeyvMongo({ url: 'mongodb://localhost:27017', useGridFS: true }); await store.clearExpired(); ``` #### `clearUnusedFor` Method Remove GridFS files that have not been accessed for a specified duration. ```js const store = new KeyvMongo({ url: 'mongodb://localhost:27017', useGridFS: true }); await store.clearUnusedFor(3600); // remove files unused for 1 hour ``` ### Running the migration script If you have documents written by `@keyv/mongo` v3, run the migration script so v6 can read them. The script ships in the npm package at `scripts/migrate-v6.ts`. Run it from your project root with `tsx`. Node.js refuses to strip TypeScript types from files under `node_modules`, so running the script with plain `node` from there fails with `ERR_UNSUPPORTED_NODE_MODULES_TYPE_STRIPPING`. Preview the changes first with `--dry-run`. Dry-run mode only counts and previews the documents that would change: ```shell npx tsx node_modules/@keyv/mongo/scripts/migrate-v6.ts --uri mongodb://user:pass@localhost:27017/dbname --dry-run ``` Run the migration: ```shell npx tsx node_modules/@keyv/mongo/scripts/migrate-v6.ts --uri mongodb://user:pass@localhost:27017/dbname ``` Pass `--collection` if you set a custom collection, `--db` if the database is not in the URI, and `--gridfs` for a store created with `useGridFS: true`: ```shell npx tsx node_modules/@keyv/mongo/scripts/migrate-v6.ts --uri mongodb://user:pass@localhost:27017 --db cache --collection sessions npx tsx node_modules/@keyv/mongo/scripts/migrate-v6.ts --uri mongodb://user:pass@localhost:27017/dbname --gridfs ``` From a clone of this repo you can run `node scripts/migrate-v6.ts` in `storage/mongo` with the same flags. **Important notes:** - The script only changes documents that have no `namespace` field, so it is safe to run again. Documents already in the v6 layout are never touched. - Keys are split on the first colon: the part before becomes the namespace, the rest becomes the key. A key without a colon gets the empty namespace v6 uses when none is set. Namespaces containing colons are not supported. The split is also wrong for colon-containing keys that Keyv v5 stored without a prefix, which happens only when it ran with `useKeyPrefix: false` or an empty namespace. - Keyv v5 used `keyv` as the namespace when none was set, so those documents migrate into namespace `keyv`. Pass `namespace: 'keyv'` to Keyv afterwards to keep reading them. See the [v5 to v6 migration guide](https://keyv.org/docs/migration/v5-to-v6/#the-default-keyv-namespace-was-removed). - In standard mode the script first replaces the unique index on `key` with the unique index on `{ key, namespace }`, the same change the adapter makes when it connects. - If v6 already stores a value under the same key and namespace, that value was written after the upgrade and is kept. The v3 document is left unchanged and listed in the output. - In GridFS mode, v3 kept every revision of a file and read the newest. The script migrates only the newest revision of each key and lists the older ones, which v6 cannot read. - The rewrite is not transactional. If it stops part way, documents already migrated keep their new layout, so run the script again to finish. ## License [MIT © Jared Wray](LICENSE) ### @keyv/sqlite URL: https://keyv.org/docs/storage-adapters/sqlite/ # @keyv/sqlite [keyv](https://github.com/jaredwray/keyv) > SQLite storage adapter for Keyv with multi-driver support for `nodejs`, `bun`, and custom drivers. [![build](https://github.com/jaredwray/keyv/actions/workflows/tests.yaml/badge.svg)](https://github.com/jaredwray/keyv/actions/workflows/tests.yaml) [![codecov](https://codecov.io/gh/jaredwray/keyv/branch/main/graph/badge.svg?token=bRzR3RyOXZ)](https://codecov.io/gh/jaredwray/keyv) [![npm](https://img.shields.io/npm/v/@keyv/sqlite.svg)](https://www.npmjs.com/package/@keyv/sqlite) [![npm](https://img.shields.io/npm/dm/@keyv/sqlite)](https://npmjs.com/package/@keyv/sqlite) SQLite storage adapter for [Keyv](https://github.com/jaredwray/keyv). ## Table of Contents - [Install](#install) - [Usage](#usage) - [Using createKeyv](#using-createkeyv) - [Multi-Driver Support](#multi-driver-support) - [Creating a Custom Driver](#creating-a-custom-driver) - [Using sqlite3](#using-sqlite3) - [Migrating to v6](#migrating-to-v6) - [Constructor Options](#constructor-options) - [Properties](#properties) - [capabilities](#capabilities) - [namespace](#namespace) - [uri](#uri) - [table](#table) - [keySize](#keysize) - [keyLength](#keylength) - [namespaceLength](#namespacelength) - [db](#db) - [iterationLimit](#iterationlimit) - [wal](#wal) - [busyTimeout](#busytimeout) - [driver](#driver) - [driverName](#drivername) - [clearExpiredInterval](#clearexpiredinterval) - [ready](#ready) - [opts](#opts) - [Methods](#methods) - [.set(key, value, expires?)](#setkey-value-expires) - [.setMany(entries)](#setmanyentries) - [.get(key)](#getkey) - [.getMany(keys)](#getmanykeys) - [.has(key)](#haskey) - [.hasMany(keys)](#hasmanykeys) - [.delete(key)](#deletekey) - [.deleteMany(keys)](#deletemanykeys) - [.clear()](#clear) - [.clearExpired()](#clearexpired) - [.iterator()](#iterator) - [.query(sql, ...params)](#querysql-params) - [.close()](#close) - [.disconnect()](#disconnect) - [Events](#events) - [Clearing Expired Keys](#clearing-expired-keys) - [WAL Mode](#wal-mode) - [Benchmarks](#benchmarks) - [License](#license) # Install ```shell npm install --save keyv @keyv/sqlite ``` # Usage ```js import Keyv from 'keyv'; import KeyvSqlite from '@keyv/sqlite'; const keyv = new Keyv({ store: new KeyvSqlite('sqlite://path/to/database.sqlite') }); keyv.on('error', err => console.error(err)); ``` You can specify the `table`, `busyTimeout`, and `wal` options: ```js const keyvSqlite = new KeyvSqlite({ uri: 'sqlite://path/to/database.sqlite', table: 'cache', busyTimeout: 10000, wal: true, }); const keyv = new Keyv({ store: keyvSqlite }); ``` # Using createKeyv The `createKeyv` helper creates a `Keyv` instance with `KeyvSqlite` as the store in one call: ```js import { createKeyv } from '@keyv/sqlite'; // With a URI string const keyv = createKeyv('sqlite://path/to/database.sqlite'); // With an options object const keyv = createKeyv({ uri: 'sqlite://path/to/database.sqlite', table: 'cache', wal: true, }); ``` # Multi-Driver Support `@keyv/sqlite` supports multiple SQLite drivers and automatically selects the best one available for your runtime: | Driver | Package | Runtime | Type | | --- | --- | --- | --- | | `better-sqlite3` | `better-sqlite3` | Node.js | Synchronous (bundled fallback) | | `node:sqlite` | Built-in | Node.js 22.13+ | Synchronous (auto-detected default; still experimental) | | `bun:sqlite` | Built-in | Bun | Synchronous | The built-in runtime drivers are preferred: on Node.js 22.13+ the built-in `node:sqlite` driver is used (unflagged since 22.13, still experimental — [Stability 1.1](https://nodejs.org/api/sqlite.html)), and on Bun the native `bun:sqlite` driver is used. `better-sqlite3` is included as a direct dependency and used as a fallback when a built-in driver is unavailable, or explicitly via `driver: 'better-sqlite3'`. If you still need to use `sqlite3` then go to the [using sqlite3](#using-sqlite3). ## Selecting a specific driver You can explicitly choose a driver via the `driver` option: ```js const store = new KeyvSqlite({ uri: 'sqlite://path/to/database.sqlite', driver: 'better-sqlite3', // or 'node:sqlite' or 'bun:sqlite' }); ``` ## Auto-detection order When no `driver` is specified, the adapter tries drivers in this order: - **Bun**: `bun:sqlite` then `better-sqlite3` - **Node.js**: `node:sqlite` then `better-sqlite3` # Creating a Custom Driver You can pass a custom driver object that implements the `SqliteDriver` interface. A custom driver must provide a `name` and a `connect()` method that returns `{ query, close }`: ```ts import KeyvSqlite from '@keyv/sqlite'; import type { SqliteDriver } from '@keyv/sqlite'; const customDriver: SqliteDriver = { name: 'custom', async connect(options) { // options: { filename: string, busyTimeout?: number, wal?: boolean } return { async query(sql, ...params) { // Execute SQL and return rows for SELECT/PRAGMA, empty array for mutations }, async close() { // Close the database connection }, }; }, }; const store = new KeyvSqlite({ uri: 'sqlite://path/to/database.sqlite', driver: customDriver, }); ``` The `query` function must return an array of row objects for `SELECT` and `PRAGMA` statements, and an empty array for all other statements (`INSERT`, `UPDATE`, `DELETE`, etc.). ## Type exports The following types are available for building custom drivers: ```ts import type { SqliteDriver, // Driver interface: { name, connect() } SqliteDriverName, // 'better-sqlite3' | 'node:sqlite' | 'bun:sqlite' | 'custom' KeyvSqliteOptions, // Constructor options Sqlite3ModuleLike, // Structural type for the sqlite3 module Sqlite3DatabaseLike, // Structural type for a sqlite3.Database instance } from '@keyv/sqlite'; ``` The `createSqlite3Driver` export is a real-world example of a custom driver — see [Using sqlite3](#using-sqlite3). # Using sqlite3 The callback-based [`sqlite3`](https://www.npmjs.com/package/sqlite3) package is not auto-detected or bundled with `@keyv/sqlite`. If you need to use it, install it in your project and pass it via the `createSqlite3Driver` helper. Note that `sqlite3` ships no prebuilt binaries for newer Node.js versions (it fails to compile on Node 26+), so prefer the default `better-sqlite3` or `node:sqlite` drivers unless you have an existing dependency on it: ```bash npm install sqlite3 ``` ```ts import KeyvSqlite, { createSqlite3Driver } from '@keyv/sqlite'; import sqlite3 from 'sqlite3'; const store = new KeyvSqlite({ uri: 'sqlite://path/to/database.sqlite', driver: createSqlite3Driver(sqlite3), }); ``` `sqlite3.verbose()` also works: ```ts const store = new KeyvSqlite({ uri: 'sqlite://path/to/database.sqlite', driver: createSqlite3Driver(sqlite3.verbose()), }); ``` All standard options (`wal`, `busyTimeout`, etc.) are supported. # Migrating to v6 ## Breaking changes ### Driver changed from `sqlite3` v5 used the callback-based `sqlite3` package. v6 no longer depends on it. It prefers the built-in `node:sqlite` driver on Node.js and `bun:sqlite` on Bun, and falls back to the bundled `better-sqlite3`. See [Multi-Driver Support](#multi-driver-support). If you must keep `sqlite3`, install it yourself and pass it with `createSqlite3Driver(sqlite3)`. See [Using sqlite3](#using-sqlite3). Otherwise, if your project lists `sqlite3` only for `@keyv/sqlite`, you can remove it. ### Properties instead of opts The `opts` getter still exists for backward compatibility and returns all current settings as a plain object. New top-level getters and setters have been added for `namespace` and `clearExpiredInterval`: ```js store.namespace = 'my-namespace'; store.clearExpiredInterval = 60_000; ``` ### Native namespace support In v5, namespaces were stored as key prefixes in the `key` column (e.g. `key="myns:mykey"` with no namespace column). In v6, the namespace is stored in a dedicated `namespace` column (e.g. `key="mykey"`, `namespace="myns"`). This enables more efficient queries and proper namespace isolation. The adapter automatically detects old schemas and migrates existing data the first time a v6 `KeyvSqlite` connects to the database. It connects as soon as you create it. No manual migration steps are needed. The migration runs in a single transaction. During migration, prefixed keys like `myns:mykey` are split into `key="mykey"` and `namespace="myns"`. **The migration is one-way.** Before you upgrade, back up the database file and stop every v5 process that writes to it. Don't run v5 and v6 against the same file. Keyv v5 used `keyv` as the namespace when none was set, so rows written that way migrate into namespace `keyv`. Pass `namespace: 'keyv'` to Keyv to keep reading them: `new Keyv(new KeyvSqlite(uri), { namespace: 'keyv' })`. See the [v5 to v6 migration guide](https://keyv.org/docs/migration/v5-to-v6/#the-default-keyv-namespace-was-removed). **Colon caveat:** migration splits on the **first** colon. That is correct for v5 namespaced keys (`namespace:actualKey`, including keys that themselves contain colons). It is incorrect for colon-containing keys that v5 stored **without a prefix**, which happens only when v5 ran with `useKeyPrefix: false` or an empty namespace (e.g. `http://example.com` becomes `namespace="http"`, `key="//example.com"`). If you stored colon-containing keys that way, migrate those rows yourself before upgrading. **Expiry caveat:** migrated rows keep their expiry inside the stored value, but the new `expires` column is left `NULL`. Keyv still enforces that expiry on read through its `checkExpired` option (default `true`), so keep `checkExpired` enabled while you have migrated data. `clearExpired()` and `clearExpiredInterval` only use the `expires` column, so they don't remove migrated rows until those rows are written again. ### Hookified integration The adapter now extends [Hookified](https://hookified.org) instead of a custom EventEmitter. Events work the same (`on`, `emit`), but hooks are also available via the standard Hookified API. ## New features ### Native TTL support with `expires` column v6 adds an `expires BIGINT` column to the table. Keyv core computes the absolute expiry and passes it to the adapter as the `expires` argument on `set` / `setMany` — the adapter stores that timestamp directly and does **not** parse the serialized value. A partial index is created on the `expires` column for efficient cleanup queries. The schema migration is automatic on connect. v5 tables get the column when they are rebuilt (see [Native namespace support](#native-namespace-support)). Tables that already have a `namespace` column get it via `ALTER TABLE ... ADD COLUMN`. ### `clearExpired()` method A new utility method that deletes all rows where the `expires` column is set and the timestamp is in the past: ```js await store.clearExpired(); ``` ### `clearExpiredInterval` option Set an interval (in milliseconds) to automatically call `clearExpired()` on a schedule. Disabled by default (`0`). The timer uses `unref()` so it won't keep the Node.js process alive. ```js const store = new KeyvSqlite({ uri: 'sqlite://path/to/database.sqlite', clearExpiredInterval: 60_000, // clean up every 60 seconds }); ``` ### Bulk operations New methods for efficient multi-key operations: - `.setMany(entries)` — bulk upsert with automatic batching (249 entries per batch to stay within SQLite's 999 parameter limit) - `.getMany(keys)` — bulk retrieve with automatic batching - `.deleteMany(keys)` — bulk delete with automatic batching - `.hasMany(keys)` — bulk existence check ### `createKeyv()` helper A convenience function to create a `Keyv` instance with `KeyvSqlite` as the store in one call: ```js import { createKeyv } from '@keyv/sqlite'; const keyv = createKeyv('sqlite://path/to/database.sqlite'); ``` ### Multi-driver support v6 prefers the built-in `node:sqlite` driver on Node.js 22.13+ (unflagged, still experimental) and `bun:sqlite` on Bun, with `better-sqlite3` bundled as the fallback (replacing the old callback-based `sqlite3` package). You can still select a driver explicitly via the `driver` option. See [Multi-Driver Support](#multi-driver-support) for details. ### Improved iterator The iterator now uses cursor-based (keyset) pagination instead of `OFFSET`. This handles concurrent modifications during iteration without skipping entries and is more efficient for large datasets. # Constructor Options `KeyvSqlite` accepts a connection URI string or an options object: | Option | Type | Default | Description | | --- | --- | --- | --- | | `uri` | `string` | `'sqlite://:memory:'` | SQLite connection URI | | `table` | `string` | `'keyv'` | Table name for key-value storage | | `keySize` | `number` | `255` | Maximum key column length (VARCHAR length, max 65535). Alias: `keyLength` | | `namespaceLength` | `number` | `255` | Maximum namespace column length (VARCHAR length) | | `busyTimeout` | `number` | `undefined` | SQLite [busy timeout](https://sqlite.org/c3ref/busy_timeout.html) in milliseconds | | `iterationLimit` | `number` | `10` | Number of rows fetched per batch during iteration | | `wal` | `boolean` | `false` | Enable [WAL mode](https://sqlite.org/wal.html) for better concurrency | | `clearExpiredInterval` | `number` | `0` | Interval in milliseconds to automatically clear expired entries (0 = disabled) | | `driver` | `string \| SqliteDriver` | `undefined` | Explicit driver selection (`'better-sqlite3'`, `'node:sqlite'`, `'bun:sqlite'`) or custom driver object. Auto-detected if omitted | # Properties ## capabilities Read-only capability descriptor. `capabilities.expires` is `true`, which tells Keyv that `set` / `setMany` accept an **absolute** Unix-ms `expires` timestamp (the v6 storage contract). - Type: `KeyvStorageCapability` ```js const store = new KeyvSqlite('sqlite://:memory:'); console.log(store.capabilities.expires); // true ``` ## namespace Get or set the namespace for the adapter. Used for key prefixing and scoping operations like `clear()` and `iterator()`. - Type: `string | undefined` - Default: `undefined` ```js const store = new KeyvSqlite('sqlite://path/to/database.sqlite'); store.namespace = 'my-namespace'; console.log(store.namespace); // 'my-namespace' ``` ## uri Get the SQLite connection URI. - Type: `string` - Default: `'sqlite://:memory:'` ```js const store = new KeyvSqlite('sqlite://path/to/database.sqlite'); console.log(store.uri); // 'sqlite://path/to/database.sqlite' ``` ## table Get or set the table name used for storage. The name is sanitized and escaped for safe use in SQL queries to prevent SQL injection. Changing this after construction does not create or migrate the new table — it only changes which table subsequent queries target. - Type: `string` - Default: `'keyv'` ```js const store = new KeyvSqlite({ uri: 'sqlite://:memory:', table: 'cache' }); console.log(store.table); // 'cache' store.table = 'sessions'; ``` ## keySize Get or set the maximum key length (VARCHAR length) for the key column. - Type: `number` - Default: `255` ```js const store = new KeyvSqlite({ uri: 'sqlite://:memory:', keySize: 512 }); console.log(store.keySize); // 512 ``` ## keyLength Alias for `keySize`. The constructor option `keyLength` is deprecated; prefer `keySize`. - Type: `number` - Default: `255` ```js const store = new KeyvSqlite({ uri: 'sqlite://:memory:', keyLength: 512 }); console.log(store.keyLength); // 512 console.log(store.keySize); // 512 ``` ## namespaceLength Get or set the maximum namespace column length (VARCHAR length). - Type: `number` - Default: `255` ```js const store = new KeyvSqlite({ uri: 'sqlite://:memory:', namespaceLength: 128 }); console.log(store.namespaceLength); // 128 ``` ## db Get the resolved file path for the SQLite database, derived from the URI. - Type: `string` - Default: `':memory:'` ```js const store = new KeyvSqlite('sqlite://data/app.sqlite'); console.log(store.db); // 'data/app.sqlite' ``` ## iterationLimit Get or set the number of rows to fetch per iteration batch. - Type: `number` - Default: `10` ```js const store = new KeyvSqlite({ uri: 'sqlite://:memory:', iterationLimit: 50 }); console.log(store.iterationLimit); // 50 ``` ## wal Get whether WAL (Write-Ahead Logging) mode is enabled. - Type: `boolean` - Default: `false` ```js const store = new KeyvSqlite({ uri: 'sqlite://path/to/database.sqlite', wal: true }); console.log(store.wal); // true ``` ## busyTimeout Get the SQLite busy timeout in milliseconds. - Type: `number | undefined` - Default: `undefined` ```js const store = new KeyvSqlite({ uri: 'sqlite://:memory:', busyTimeout: 5000 }); console.log(store.busyTimeout); // 5000 ``` ## driver Get the explicit driver selection. Returns `undefined` when auto-detected. - Type: `string | SqliteDriver | undefined` - Default: `undefined` (auto-detected) ```js const store = new KeyvSqlite({ uri: 'sqlite://:memory:', driver: 'better-sqlite3' }); console.log(store.driver); // 'better-sqlite3' ``` ## driverName Get the name of the resolved driver after connection. This is useful to check which driver was auto-detected. - Type: `string | undefined` - Default: `undefined` (set after connection is established) ```js const store = new KeyvSqlite('sqlite://:memory:'); await store.ready; console.log(store.driverName); // 'better-sqlite3', 'node:sqlite', 'bun:sqlite', or 'custom' ``` ## clearExpiredInterval Get or set the interval in milliseconds between automatic expired-entry cleanup runs. When set to a value greater than 0, the adapter will automatically call `clearExpired()` at the specified interval. The timer uses `unref()` so it won't keep the Node.js process alive. Setting to 0 disables the automatic cleanup. An interval longer than about 24.8 days (2,147,483,647 ms, the longest delay Node.js timers accept) runs cleanup at that limit. - Type: `number` - Default: `0` (disabled) ```js // Clean up expired entries every 60 seconds const store = new KeyvSqlite({ uri: 'sqlite://path/to/database.sqlite', clearExpiredInterval: 60_000, }); console.log(store.clearExpiredInterval); // 60000 // Disable it later store.clearExpiredInterval = 0; ``` ## ready A promise that resolves when the database connection and schema setup are complete. You can optionally await this before the first operation to ensure the adapter is fully initialized. - Type: `Promise` ```js const store = new KeyvSqlite('sqlite://path/to/database.sqlite'); await store.ready; // connection and schema migration complete ``` ## opts Get a snapshot of all current settings as a plain object. This getter exists for backward compatibility with v5 — prefer the individual property getters above. `keySize` is also exposed under its `keyLength` alias, and the resolved database path is included as `db`. - Type: `KeyvSqliteOptions & { db: string }` ```js const store = new KeyvSqlite({ uri: 'sqlite://:memory:', table: 'cache', wal: true, }); console.log(store.opts.uri); // 'sqlite://:memory:' console.log(store.opts.table); // 'cache' console.log(store.opts.wal); // true console.log(store.opts.db); // ':memory:' ``` # Methods ## .set(key, value, expires?) Set a key-value pair on the store. Returns `true` on success, `false` on failure (an `error` event is also emitted). The third argument is an **absolute** Unix timestamp in milliseconds (`Date.now() + ttl`), or omitted/`undefined` for no expiry. This is the v6 adapter contract. When you call `keyv.set(key, value, ttl)` on a `Keyv` instance, `ttl` is still a **relative** duration in milliseconds — Keyv converts it to `expires` before calling the adapter. - `key` *(string)* - The key to set. - `value` *(any)* - The value to store. - `expires` *(number, optional)* - Absolute expiry as Unix ms since epoch. - Returns: `Promise` ```js await store.set('foo', 'bar'); await store.set('foo', 'bar', Date.now() + 5000); // expires at an absolute timestamp // Through Keyv, ttl is still relative: await keyv.set('foo', 'bar', 5000); // expires in 5 seconds ``` ## .setMany(entries) Set multiple key-value pairs at once. Each entry is a `KeyvStorageEntry` (`{ key, value, expires? }`) with an absolute `expires` timestamp. Through a `Keyv` instance, `keyv.setMany()` takes `KeyvEntry` objects (`{ key, value, ttl? }`) with a relative `ttl` and converts them before calling the adapter. Entries are automatically batched (249 per batch) to stay within SQLite's bind parameter limit. Returns a `boolean[]` with per-entry success tracking. Each batch is atomic — if a batch fails, entries in that batch return `false` while entries in successful batches return `true`. On batch failure, an `error` event is emitted. - `entries` *(`KeyvStorageEntry[]`)* - Entries to upsert (`{ key, value, expires? }`). - Returns: `Promise` ```js const results = await store.setMany([ { key: 'foo', value: 'bar' }, { key: 'baz', value: 'qux', expires: Date.now() + 5000 }, ]); // [true, true] ``` ## .get(key) Get a value by key. Returns `undefined` if the key does not exist, has expired, or was stored as SQL `NULL`. Never returns `null`. - `key` *(string)* - The key to retrieve. - Returns: `Promise` ```js const value = await store.get('foo'); // 'bar' ``` ## .getMany(keys) Get multiple values at once. Returns an array of values in the same order as the keys, with `undefined` for missing, expired, or SQL `NULL` entries (never `null`). - `keys` *(string[])* - The keys to retrieve. - Returns: `Promise>` ```js const values = await store.getMany(['foo', 'baz']); // ['bar', 'qux'] ``` ## .has(key) Check if a key exists. Returns a boolean. Expired keys are deleted on read and reported as missing. - `key` *(string)* - The key to check. - Returns: `Promise` ```js const exists = await store.has('foo'); // true ``` ## .hasMany(keys) Check if multiple keys exist. Returns an array of booleans in the same order as the input keys. Expired keys are deleted on read and reported as missing. - `keys` *(string[])* - The keys to check. - Returns: `Promise` ```js const results = await store.hasMany(['foo', 'baz', 'unknown']); // [true, true, false] ``` ## .delete(key) Delete a key. Returns `true` if the key existed, `false` otherwise. - `key` *(string)* - The key to delete. - Returns: `Promise` ```js const deleted = await store.delete('foo'); // true ``` ## .deleteMany(keys) Delete multiple keys at once. Returns a `boolean[]` indicating whether each key existed. - `keys` *(string[])* - The keys to delete. - Returns: `Promise` ```js const results = await store.deleteMany(['foo', 'baz']); // [true, true] ``` ## .clear() Clear all keys in the current namespace. If no namespace is set, entries with an empty namespace are removed. - Returns: `Promise` ```js await store.clear(); ``` ## .clearExpired() Utility helper method to delete all expired entries from the store. This removes any rows where the `expires` column is set and the timestamp is in the past. This is useful for periodic cleanup of expired data. - Returns: `Promise` ```js await store.clearExpired(); ``` ## .iterator() Iterate over all key-value pairs. The iterator uses the namespace configured on the instance. Uses cursor-based pagination controlled by the `iterationLimit` option. Expired rows are skipped (not deleted). SQL `NULL` values are yielded as `undefined`. - Returns: `AsyncGenerator<[string, string | undefined]>` - Yields: `[key, value]` tuples. Values are never `null`. ```js for await (const [key, value] of store.iterator()) { console.log(key, value); } ``` ## .query(sql, ...params) Execute a SQL statement against the database. Returns result rows for `SELECT`, `PRAGMA`, and `RETURNING` statements, and an empty array for mutations. - `sql` *(string)* - The SQL statement to execute. - `...params` *(unknown[])* - Bind parameters for the statement. - Returns: `Promise` ```js const rows = await store.query('SELECT * FROM keyv WHERE namespace = ?', 'my-namespace'); ``` ## .close() Close the underlying database connection. Prefer `.disconnect()`, which also stops the expired-entry cleanup timer. - Returns: `Promise` ```js await store.close(); ``` ## .disconnect() Disconnect from the SQLite database and release resources. Stops the automatic expired-entry cleanup interval if running, then closes the connection. - Returns: `Promise` ```js await store.disconnect(); ``` # Events `KeyvSqlite` extends [Hookified](https://hookified.org) (not Node's `EventEmitter`). The constructor calls `super({ throwOnEmptyListeners: false })`, so emitting `error` with no listener does not throw. Use `on`, `once`, and `emit` the same way as EventEmitter. An `error` event is emitted on: - connection / schema-setup failures - `set` / `setMany` failures - iterator failures - `clearExpired` interval failures ```js const store = new KeyvSqlite('sqlite://path/to/database.sqlite'); store.on('error', (error) => console.error(error)); store.once('error', (error) => console.error('first error only', error)); ``` Hooks from the Hookified API (`onHook`, `hook`, `before`, `after`, etc.) are also available. Storage adapters emit events; Keyv core owns operation hooks (`before:get`, `after:set`, etc.). See the [Hookified documentation](https://hookified.org). # Clearing Expired Keys When a key is stored with a TTL, the adapter records the expiration timestamp in the `expires` column. Keyv core enforces TTL automatically — expired keys return `undefined` from `get()` and `false` from `has()`, and are lazily deleted from the store when accessed via `get()`, `getMany()`, `has()`, or `hasMany()`. The iterator skips expired rows but does not delete them. However, expired rows that are never accessed again will remain in the database. The `clearExpired()` method and `clearExpiredInterval` option provide bulk cleanup to remove these stale rows efficiently via SQL, without needing to deserialize every row. ## Automatic cleanup Set the `clearExpiredInterval` option (in milliseconds) to automatically remove expired entries on a recurring timer. The timer uses `unref()` so it won't keep the Node.js process alive. ```js const store = new KeyvSqlite({ uri: 'sqlite://path/to/database.sqlite', clearExpiredInterval: 60_000, // clean up every 60 seconds }); ``` You can change or disable the interval at runtime: ```js // Change to every 5 minutes store.clearExpiredInterval = 300_000; // Disable automatic cleanup store.clearExpiredInterval = 0; ``` ## Manual cleanup Call `clearExpired()` directly to remove all expired entries on demand: ```js await store.clearExpired(); ``` # WAL Mode By default, SQLite uses the rollback journal for transactions. Enabling [WAL (Write-Ahead Logging)](https://sqlite.org/wal.html) mode can significantly improve concurrency and write performance for most workloads. ```js const store = new KeyvSqlite({ uri: 'sqlite://path/to/database.sqlite', wal: true, }); const keyv = new Keyv({ store }); ``` **Note:** WAL mode is not supported for in-memory databases (`:memory:`). If enabled for an in-memory database, a warning will be logged and the option will be ignored. From the [SQLite documentation](https://sqlite.org/wal.html): > WAL provides more concurrency as readers do not block writers and a writer does not block readers. Reading and writing can proceed concurrently. WAL is significantly faster than the default rollback journal in most scenarios involving a single database connection, and is also faster in many scenarios involving multiple database connections. # Benchmarks Simple `set` / `get` benchmarks comparing the built-in SQLite drivers plus an optional `sqlite3` custom-driver setup using in-memory databases with 10,000 pre-generated key-value pairs. Results will vary across machines and runs — they are meant as a relative comparison, not absolute performance numbers. | name | summary | ops/sec | time/op | margin | samples | |---------------------|:---------:|----------:|----------:|:--------:|----------:| | bun set / get | 🥇 | 64K | 18µs | ±0.79% | 57K | | better set / get | -32.0% | 44K | 25µs | ±2.34% | 40K | | node set / get | -32.7% | 43K | 25µs | ±2.46% | 40K | | sqlite3 set / get | -74.7% | 16K | 67µs | ±1.25% | 15K | Note: we included `sqlite3` tests in this but by default we do not have it as a dependency as our fallback is `better-sqlite3` now. Please refer to [using sqlite3](#using-sqlite3) if you want to use it. # License [MIT © Jared Wray](LICENSE) ### @keyv/memcache URL: https://keyv.org/docs/storage-adapters/memcache/ # @keyv/memcache [keyv](https://github.com/jaredwray/keyv) > Memcache storage adapter for [Keyv](https://github.com/jaredwray/keyv) using the [memcache](https://github.com/jaredwray/memcache) client [![build](https://github.com/jaredwray/keyv/actions/workflows/tests.yaml/badge.svg)](https://github.com/jaredwray/keyv/actions/workflows/tests.yaml) [![codecov](https://codecov.io/gh/jaredwray/keyv/branch/main/graph/badge.svg?token=bRzR3RyOXZ)](https://codecov.io/gh/jaredwray/keyv) [![GitHub license](https://img.shields.io/github/license/jaredwray/keyv)](https://github.com/jaredwray/keyv/blob/main/LICENSE) [![npm](https://img.shields.io/npm/dm/@keyv/memcache)](https://npmjs.com/package/@keyv/memcache) ## Features - Built on the [memcache](https://github.com/jaredwray/memcache) package with a fully Promise-based API and TypeScript types - TTL support (millisecond input, converted to seconds for memcache) - Namespace support for key isolation across multiple Keyv instances - Multiple nodes with consistent hashing (KetamaHash) - SASL authentication support - AWS ElastiCache Auto Discovery support - Retry and backoff support for failed commands - `createKeyv` helper for quick setup ## Table of Contents - [Features](#features) - [Install](#install) - [Keyv Compression is not Supported](#keyv-compression-is-not-supported) - [Quick Start with createKeyv](#quick-start-with-createkeyv) - [Usage](#usage) - [Usage with Namespaces](#usage-with-namespaces) - [Keys Memcached Can't Store](#keys-memcached-cant-store) - [How `clear()` Works](#how-clear-works) - [Options](#options) - [Multiple Nodes](#multiple-nodes) - [SASL Authentication](#sasl-authentication) - [AWS ElastiCache Auto Discovery](#aws-elasticache-auto-discovery) - [API](#api) - [constructor(uri?, options?)](#constructoruri-options) - [.get(key)](#getkey) - [.getMany(keys)](#getmanykeys) - [.set(key, value, expires?)](#setkey-value-expires) - [.setMany(entries)](#setmanyentries) - [.delete(key)](#deletekey) - [.deleteMany(keys)](#deletemanykeys) - [.clear()](#clear) - [.has(key)](#haskey) - [.hasMany(keys)](#hasmanykeys) - [.disconnect()](#disconnect) - [.formatKey(key)](#formatkeykey) - [Properties](#properties) - [Works with Memcached and Google Cloud](#works-with-memcached-and-google-cloud) - [Using Memcached](#using-memcached) - [Using Google Cloud](#using-google-cloud) - [Breaking Changes from v2 to v6](#breaking-changes-from-v2-to-v6) - [Underlying Client Changed from `memjs` to `memcache`](#underlying-client-changed-from-memjs-to-memcache) - [`client` Property Type Changed](#client-property-type-changed) - [`KeyvMemcacheOptions` Type Changed](#keyvmemcacheoptions-type-changed) - [`disconnect()` Method Added](#disconnect-method-added) - [`buffer` Dependency Removed](#buffer-dependency-removed) - [`set` Takes an Absolute `expires`](#set-takes-an-absolute-expires) - [`clear()` Only Removes the Store's Own Entries](#clear-only-removes-the-stores-own-entries) - [License](#license) ## Install ```shell npm install --save @keyv/memcache ``` ## Keyv Compression is not Supported This package does not support compression. If you need compression, please use the `@keyv/redis` or another service package instead. ## Expiration Granularity Expiry is enforced server-side by Memcached's `exptime`, which is **second-granular**. TTLs are accepted in milliseconds and rounded up to whole seconds, so Memcached itself can return a value for up to ~1 second past a sub-second (or just-elapsed) deadline before it evicts it. Keyv filters expired reads at its own layer by default (`checkExpired` defaults to `true`), using the absolute `expires` stored with the value, so reads are millisecond-precise out of the box even though Memcached's eviction is coarser. If you prefer to trust Memcached's `exptime` alone (and skip the extra decode on reads), opt out: ```js const keyv = new Keyv({ store: new KeyvMemcache('localhost:11211'), checkExpired: false }); ``` ## Quick Start with createKeyv The `createKeyv` helper creates a `Keyv` instance with a Memcache store in a single call: ```js import { createKeyv } from '@keyv/memcache'; const keyv = createKeyv('localhost:11211'); keyv.on('error', handleConnectionError); // set a value await keyv.set('foo', 'bar', 6000); // get a value const value = await keyv.get('foo'); // delete a value await keyv.delete('foo'); ``` You can also pass an options object: ```js import { createKeyv } from '@keyv/memcache'; const keyv = createKeyv({ nodes: ['localhost:11211'] }); ``` ## Usage ```js import Keyv from 'keyv'; import KeyvMemcache from '@keyv/memcache'; const memcache = new KeyvMemcache('localhost:11211'); const keyv = new Keyv({ store: memcache }); keyv.on('error', handleConnectionError); //set await keyv.set("foo","bar", 6000) //Expiring time is optional //get const obj = await keyv.get("foo"); //delete await keyv.delete("foo"); //clear await keyv.clear(); //disconnect await memcache.disconnect(); ``` ## Usage with Namespaces The namespace lives on the store adapter, which prefixes every key with `namespace::` (the separator is the `namespaceSeparator` option). Because the namespace is held on the adapter, give each namespace its own `KeyvMemcache` instance rather than sharing a single store between multiple `Keyv` instances: ```js import Keyv from 'keyv'; import KeyvMemcache from '@keyv/memcache'; const keyv1 = new Keyv({ store: new KeyvMemcache('localhost:11211'), namespace: "namespace1" }); const keyv2 = new Keyv({ store: new KeyvMemcache('localhost:11211'), namespace: "namespace2" }); //set await keyv1.set("foo","bar1", 6000) //Expiring time is optional await keyv2.set("foo","bar2", 6000) //Expiring time is optional //get const obj1 = await keyv1.get("foo"); //will return bar1 const obj2 = await keyv2.get("foo"); //will return bar2 ``` You can also set the namespace directly on the store, which is handy when you only need a single namespace: ```js const memcache = new KeyvMemcache('localhost:11211'); memcache.namespace = "namespace1"; const keyv = new Keyv({ store: memcache }); ``` `clear()` on one namespace leaves the others alone. See [How `clear()` Works](#how-clear-works). ## Keys Memcached Can't Store Memcached only stores keys of up to 250 bytes with no whitespace or control characters. The adapter stores any other key, such as a long URL or a key with a space, under a SHA-256 digest of the namespaced key, `keyv:sha256:`, so every key works. Keys that Memcached accepts are stored as they are, except a key that already starts with `keyv:sha256:`, or with `keyv:gen:`, the prefix of the [generation keys](#how-clear-works). It's hashed too, so it can't overwrite the entry of the key it's the digest of or a generation token. The 250-byte limit is the client's `maxKeySize` option. If you set it below the 76 characters a digest key takes, the digest is shortened to fit, keeping at least 128 bits. That takes a `maxKeySize` of at least 44. Below that, keys that need hashing fail with the client's key-length error. ```js const keyv = new Keyv({ store: new KeyvMemcache('localhost:11211') }); await keyv.set('user name', 'a key with a space'); await keyv.set(`https://example.com/search?${'q=keyv&'.repeat(50)}`, 'a key over 250 bytes'); ``` ## How `clear()` Works Memcached can't list keys or delete them by prefix, so the adapter clears by generation. Each namespace has a random token, stored under `keyv:gen:` and a digest of the namespace, and every value is stored after the token it was written under. `clear()` writes a new token. Values under an old token read as missing, and Memcached evicts them or lets them expire. Other namespaces, and keys other clients wrote, are left alone. ```js const sessions = new Keyv({ store: new KeyvMemcache('localhost:11211'), namespace: 'sessions' }); const cache = new Keyv({ store: new KeyvMemcache('localhost:11211'), namespace: 'cache' }); await sessions.set('user', 'alice'); await cache.set('page', ''); await cache.clear(); await cache.get('page'); // undefined await sessions.get('user'); // 'alice' ``` Without a namespace, `clear()` removes only the entries written without one. To flush the whole server instead, as v5 did, set `noNamespaceAffectsAll: true`. A store without a namespace then also stores values as given, without a token. A store with a namespace always clears only that namespace. Every store reads the current token when it reads or writes, so a `clear()` in one process takes effect for all of them. What it costs: - Each read fetches the token in the same multi-get as the values, and each write reads it alongside. Each value takes 17 more bytes: the token and a `:`. - Cleared values take memory until they expire or Memcached evicts them. - If the token is lost, because Memcached evicted it or the node holding it restarted, the adapter creates a new one and the namespace reads as empty. It never serves values from before a `clear()`. With several nodes, restarting the node that holds a namespace's token empties that namespace on every node. - `delete()` returns `true` for a cleared value that Memcached still holds. - A value without a token, such as one v5 or an earlier v6 release wrote, reads as missing. ## Options The `KeyvMemcacheOptions` type extends `MemcacheOptions` from the `memcache` package with `namespace`, `namespaceSeparator`, and `noNamespaceAffectsAll` properties: | Option | Type | Default | Description | |---|---|---|---| | `namespace` | `string` | `undefined` | Key prefix for namespace isolation | | `namespaceSeparator` | `string` | `'::'` | Separator placed between the namespace and key | | `noNamespaceAffectsAll` | `boolean` | `false` | Without a namespace, flush the whole server on `clear()` and store values without a token. See [How `clear()` Works](#how-clear-works) | | `nodes` | `(string \| MemcacheNode)[]` | `['localhost:11211']` | Array of memcache server URIs or MemcacheNode instances | | `timeout` | `number` | `5000` | Operation timeout in milliseconds | | `keepAlive` | `boolean` | `true` | Keep the connection alive | | `keepAliveDelay` | `number` | `1000` | Keep-alive delay in milliseconds | | `retries` | `number` | `0` | Number of retry attempts for failed commands (0 to disable) | | `retryDelay` | `number` | `100` | Base delay in milliseconds between retries | | `retryBackoff` | `function` | fixed delay | Function to calculate backoff delay between retries | | `retryOnlyIdempotent` | `boolean` | `true` | Only retry idempotent commands to prevent double-execution | | `sasl` | `{ username, password, mechanism? }` | `undefined` | SASL PLAIN authentication credentials | | `autoDiscover` | `AutoDiscoverOptions` | `undefined` | AWS ElastiCache Auto Discovery configuration | ```js import KeyvMemcache from '@keyv/memcache'; const memcache = new KeyvMemcache({ nodes: ['server1:11211', 'server2:11211'], timeout: 3000, retries: 2, retryDelay: 200, }); ``` ## Multiple Nodes The adapter supports connecting to multiple memcache servers. Keys are distributed across nodes using consistent hashing (KetamaHash): ```js import Keyv from 'keyv'; import KeyvMemcache from '@keyv/memcache'; const memcache = new KeyvMemcache({ nodes: ['server1:11211', 'server2:11211', 'server3:11211'], }); const keyv = new Keyv({ store: memcache }); ``` Node URIs support multiple formats: - Simple: `localhost:11211` - With protocol: `memcache://localhost:11211` - IPv6: `[::1]:11211` ## SASL Authentication To connect to a memcache server that requires SASL authentication: ```js import Keyv from 'keyv'; import KeyvMemcache from '@keyv/memcache'; const memcache = new KeyvMemcache({ nodes: ['localhost:11211'], sasl: { username: 'myuser', password: 'mypassword', }, }); const keyv = new Keyv({ store: memcache }); ``` ## AWS ElastiCache Auto Discovery When using AWS ElastiCache, you can enable auto discovery to automatically detect cluster topology changes: ```js import Keyv from 'keyv'; import KeyvMemcache from '@keyv/memcache'; const memcache = new KeyvMemcache({ nodes: ['my-cluster.cfg.use1.cache.amazonaws.com:11211'], autoDiscover: { enabled: true, pollingInterval: 60000, // poll every 60 seconds (default) }, }); const keyv = new Keyv({ store: memcache }); ``` | Option | Type | Default | Description | |---|---|---|---| | `enabled` | `boolean` | — | Enable auto discovery | | `pollingInterval` | `number` | `60000` | How often to poll for topology changes (ms) | | `configEndpoint` | `string` | first node | The `.cfg` endpoint for discovery | | `useLegacyCommand` | `boolean` | `false` | Use legacy command for engine versions < 1.4.14 | ## API ### constructor(uri?, options?) Creates a new `KeyvMemcache` instance. - `uri` — A memcache server URI string (e.g., `'localhost:11211'`) or a `KeyvMemcacheOptions` object. Defaults to `'localhost:11211'` if not provided. - `options` — Optional `KeyvMemcacheOptions` object. When both `uri` and `options` are objects, they are merged together. The `namespace` property is extracted from the resolved options and used for key prefixing. All remaining options are passed directly to the underlying `Memcache` client. ```js import KeyvMemcache from '@keyv/memcache'; // Using a URI string const memcache = new KeyvMemcache('localhost:11211'); // Using an options object const memcache2 = new KeyvMemcache({ nodes: ['localhost:11211'], timeout: 3000 }); // Using multiple nodes const memcache3 = new KeyvMemcache({ nodes: ['server1:11211', 'server2:11211', 'server3:11211'], namespace: 'myapp', }); // Using a URI string with additional options const memcache4 = new KeyvMemcache('localhost:11211', { namespace: 'myapp' }); ``` ### .get(key) Retrieves a value from the memcache server. Returns the stored value, or `undefined` if the key does not exist or has expired. ```js const memcache = new KeyvMemcache('localhost:11211'); await memcache.set('foo', 'bar'); const result = await memcache.get('foo'); // 'bar' ``` ### .getMany(keys) Retrieves multiple values from the memcache server. Returns an array of values corresponding to each key, with `undefined` for any key that does not exist. ```js const memcache = new KeyvMemcache('localhost:11211'); await memcache.set('key1', 'value1'); await memcache.set('key2', 'value2'); const results = await memcache.getMany(['key1', 'key2', 'key3']); // ['value1', 'value2', undefined] ``` ### .set(key, value, expires?) Stores a value in the memcache server. The optional `expires` parameter is an absolute Unix timestamp in milliseconds (`Date.now() + ttl`). It is converted to Memcached's `exptime` in seconds internally. Through a `Keyv` instance, `keyv.set(key, value, ttl)` still takes a relative `ttl` in milliseconds, and Keyv converts it to `expires` for you. Returns `true` when the value was stored. When Memcached doesn't store it, for example a value over Memcached's item size limit, it returns `false` and emits an error. ```js const memcache = new KeyvMemcache('localhost:11211'); await memcache.set('foo', 'bar'); // no expiration await memcache.set('foo', 'bar', Date.now() + 5000); // expires in 5 seconds ``` ### .setMany(entries) Stores multiple values in the memcache server. Each entry is a `KeyvStorageEntry` object (`{ key: string, value: Value, expires?: number }`), where `expires` is an absolute Unix timestamp in milliseconds and `Value` is inferred from the entries provided. Returns a `boolean[]` indicating whether each entry was set successfully. ```js const memcache = new KeyvMemcache('localhost:11211'); const results = await memcache.setMany([ { key: 'key1', value: 'value1' }, { key: 'key2', value: 'value2', expires: Date.now() + 5000 }, ]); // [true, true] ``` ### .delete(key) Deletes a key from the memcache server. Returns `true` if the key was deleted. ```js const memcache = new KeyvMemcache('localhost:11211'); await memcache.set('foo', 'bar'); const deleted = await memcache.delete('foo'); // true ``` ### .deleteMany(keys) Deletes multiple keys from the memcache server. Returns a `boolean[]` indicating whether each key was deleted. ```js const memcache = new KeyvMemcache('localhost:11211'); await memcache.set('key1', 'value1'); await memcache.set('key2', 'value2'); const results = await memcache.deleteMany(['key1', 'key2']); // [true, true] ``` ### .clear() Removes the entries the store wrote under its namespace by writing a new generation token, and leaves other namespaces and keys other clients wrote alone. See [How `clear()` Works](#how-clear-works). Without a namespace and with `noNamespaceAffectsAll: true`, it flushes the whole server instead. If Memcached doesn't store the new token or doesn't flush, an error is emitted. ```js const memcache = new KeyvMemcache('localhost:11211'); await memcache.clear(); ``` ### .has(key) Checks whether a key exists in the memcache server. A cleared value doesn't count. Returns `false` on an error, which is emitted. ```js const memcache = new KeyvMemcache('localhost:11211'); await memcache.set('foo', 'bar'); const exists = await memcache.has('foo'); // true const missing = await memcache.has('baz'); // false ``` ### .hasMany(keys) Checks whether multiple keys exist in the memcache server. Returns an array of booleans corresponding to each key. ```js const memcache = new KeyvMemcache('localhost:11211'); await memcache.set('key1', 'value1'); await memcache.set('key2', 'value2'); const results = await memcache.hasMany(['key1', 'key2', 'key3']); // [true, true, false] ``` ### .disconnect() Gracefully disconnects from the memcache server. ```js const memcache = new KeyvMemcache('localhost:11211'); await memcache.disconnect(); ``` ### .formatKey(key) Formats a key by prepending the namespace and `namespaceSeparator` if a namespace is set. A key Memcached can't store, one over 250 bytes or with whitespace or control characters, is formatted as a SHA-256 digest of the namespaced key instead, and so is a key that starts with `keyv:sha256:` or `keyv:gen:`. See [Keys Memcached Can't Store](#keys-memcached-cant-store). ```js const memcache = new KeyvMemcache('localhost:11211'); memcache.formatKey('foo'); // 'foo' memcache.namespace = 'myapp'; memcache.formatKey('foo'); // 'myapp::foo' memcache.formatKey('user name'); // 'keyv:sha256:…' ``` ### Properties The following public properties are available on a `KeyvMemcache` instance: | Property | Type | Description | |---|---|---| | `client` | `Memcache` | The underlying [memcache](https://github.com/jaredwray/memcache) client instance for advanced use. | | `namespace` | `string \| undefined` | The namespace used to prefix keys. Can be read and set directly. | | `namespaceSeparator` | `string` | The separator placed between the namespace and key, `'::'` by default. Can be read and set directly. | | `noNamespaceAffectsAll` | `boolean` | Without a namespace, whether `clear()` flushes the whole server. Can be read and set directly. | | `generationKey` | `string` | The key that holds the current namespace's generation token (read-only). | | `nodes` | `(string \| MemcacheNode)[]` | The configured memcache nodes (read-only). | | `timeout` | `number \| undefined` | The configured operation timeout in milliseconds (read-only). | | `keepAlive` | `boolean \| undefined` | The configured keep-alive setting (read-only). | | `retries` | `number \| undefined` | The configured number of retry attempts (read-only). | | `retryDelay` | `number \| undefined` | The configured base retry delay in milliseconds (read-only). | ## Works with Memcached and Google Cloud ### Using Memcached 1. Install Memcached and start an instance ```js import Keyv from 'keyv'; import KeyvMemcache from '@keyv/memcache'; //set the server to the correct address and port const memcache = new KeyvMemcache("localhost:11211"); const keyv = new Keyv({ store: memcache}); ``` ### Using Google Cloud 1. Go to https://cloud.google.com/ and sign up. 2. Go to the memcached configuration page in the google cloud console by navigating to Memorystore > Memcached. 3. On the memcached page (Eg. https://console.cloud.google.com/memorystore/memcached/instances?project=example), Click Create Instance 4. Fill in all mandatory fields as needed. You will need to set up a private service connection. 5. To set up a private service connection, click the Set Up Connection button. 6. Once required fields are complete, click the Create button to create the instance. 7. Google provides further documentation for connecting to and managing your Memcached instance [here](https://cloud.google.com/memorystore/docs/memcached). ```js import Keyv from 'keyv'; import KeyvMemcache from '@keyv/memcache'; const memcache = new KeyvMemcache("insert the internal google memcached discovery endpoint"); const keyv = new Keyv({ store: memcache}); ``` # Breaking Changes from v2 to v6 ## Underlying Client Changed from `memjs` to `memcache` The underlying memcache client has been replaced from [memjs](https://github.com/alevy/memjs) to [memcache](https://github.com/jaredwray/memcache). This brings a fully Promise-based API, built-in TypeScript types, and removes the need for the `buffer` dependency. ## `client` Property Type Changed The `client` property on `KeyvMemcache` is now an instance of `Memcache` from the `memcache` package instead of `memjs.Client`. If you were accessing `client` directly, you will need to update your code to use the new API. ## `KeyvMemcacheOptions` Type Changed The options type no longer extends `memjs.ClientOptions`. It now extends `MemcacheOptions` from the `memcache` package. Options such as `logger`, `username`, `password` passed directly are no longer supported. Use the `memcache` package options format instead: ```js // Before (v2) const memcache = new KeyvMemcache('user:pass@localhost:11211', { logger: { log: console.log } }); // After (v6) const memcache = new KeyvMemcache('localhost:11211', { sasl: { username: 'user', password: 'pass' } }); ``` ## `disconnect()` Method Added A new `disconnect()` method is available to gracefully close the connection to the memcache server: ```js await memcache.disconnect(); ``` ## `buffer` Dependency Removed The `buffer` polyfill dependency has been removed. Values are now handled as strings instead of Buffers. ## `set` Takes an Absolute `expires` The third argument of the adapter's `set` is now an absolute Unix timestamp in milliseconds, not a relative `ttl`. This only affects code that calls the adapter directly. `keyv.set(key, value, ttl)` still takes a relative `ttl`. ```js // Before (v2) await memcache.set('foo', 'bar', 5000); // After (v6) await memcache.set('foo', 'bar', Date.now() + 5000); ``` ## `clear()` Only Removes the Store's Own Entries In v2, `clear()` flushed the whole Memcached server, with or without a namespace, which removed other namespaces' entries and keys other clients wrote. In v6 it removes only the store's own entries by writing a new generation token; see [How `clear()` Works](#how-clear-works). Values v2 wrote have no token, so v6 reads them as missing, and the cache fills again. To flush the whole server from a store without a namespace, set `noNamespaceAffectsAll: true`. ## License [MIT © Jared Wray](LICENSE) ### @keyv/etcd URL: https://keyv.org/docs/storage-adapters/etcd/ # @keyv/etcd [keyv](https://github.com/jaredwray/keyv) > Etcd storage adapter for [Keyv](https://github.com/jaredwray/keyv), powered by our own from-scratch etcd v3 client — no third-party etcd library required [![build](https://github.com/jaredwray/keyv/actions/workflows/tests.yaml/badge.svg)](https://github.com/jaredwray/keyv/actions/workflows/tests.yaml) [![codecov](https://codecov.io/gh/jaredwray/keyv/branch/main/graph/badge.svg?token=bRzR3RyOXZ)](https://codecov.io/gh/jaredwray/keyv) [![GitHub license](https://img.shields.io/github/license/jaredwray/keyv)](https://github.com/jaredwray/keyv/blob/main/LICENSE) [![npm](https://img.shields.io/npm/v/@keyv/etcd.svg)](https://www.npmjs.com/package/@keyv/etcd) [![npm](https://img.shields.io/npm/dm/@keyv/etcd)](https://npmjs.com/package/@keyv/etcd) ## Features - Talks to etcd directly over its HTTP/JSON gateway via a small in-house client — no `etcd3` or other third-party etcd packages - Full TypeScript support - TTL support via etcd leases (millisecond input, converted to seconds internally) - Namespace support for key isolation across multiple Keyv instances - Async iterator support for scanning keys - `setMany`, `getMany`, `deleteMany`, and `hasMany` batch operations - `createKeyv` helper for quick setup ## Requirements - **etcd 3.4 or newer** — this adapter uses the etcd v3 API (`/v3/kv/range`, `/v3/kv/put`, `/v3/lease/grant`, etc.) exposed by etcd's built-in HTTP/JSON gateway. etcd serves these `/v3/` paths from version 3.4 on. etcd v2 is not supported. - **Node.js 22.19 or newer** — the client uses the global `fetch` and `AbortSignal.timeout` APIs. ## Table of Contents - [Requirements](#requirements) - [Install](#install) - [Quick Start with createKeyv](#quick-start-with-createkeyv) - [Usage](#usage) - [Usage with Namespaces](#usage-with-namespaces) - [Migrating to v6](#migrating-to-v6) - [Options](#options) - [Properties](#properties) - [.client](#client) - [.url](#url) - [.ttl](#ttl) - [.busyTimeout](#busytimeout) - [.namespace](#namespace) - [.namespaceSeparator](#namespaceseparator) - [Methods](#methods) - [constructor(url?, options?)](#constructorurl-options) - [.get(key)](#getkey) - [.getMany(keys)](#getmanykeys) - [.set(key, value, expires?)](#setkey-value-expires) - [.setMany(entries)](#setmanyentries) - [.delete(key)](#deletekey) - [.deleteMany(keys)](#deletemanykeys) - [.clear()](#clear) - [.has(key)](#haskey) - [.hasMany(keys)](#hasmanykeys) - [.iterator()](#iterator) - [.disconnect()](#disconnect) - [.formatKey(key)](#formatkeykey) - [.createKeyPrefix(key, namespace?)](#createkeyprefixkey-namespace) - [.removeKeyPrefix(key, namespace?)](#removekeyprefixkey-namespace) - [License](#license) ## Install ```shell npm install --save keyv @keyv/etcd ``` You also need a running etcd 3.4+ server reachable from your Node process. For local development: ```shell docker run --rm -p 2379:2379 registry.k8s.io/etcd:3.5.15-0 \ etcd --listen-client-urls=http://0.0.0.0:2379 --advertise-client-urls=http://0.0.0.0:2379 ``` ## Quick Start with createKeyv ```js import { createKeyv } from '@keyv/etcd'; const keyv = createKeyv('etcd://localhost:2379'); // set a value await keyv.set('foo', 'bar'); // get a value const value = await keyv.get('foo'); // set with TTL (milliseconds) await keyv.set('foo', 'bar', 6000); // delete a value await keyv.delete('foo'); ``` You can also pass options: ```js import { createKeyv } from '@keyv/etcd'; const keyv = createKeyv('etcd://localhost:2379', { ttl: 5000 }); // or using an options object const keyv2 = createKeyv({ url: '127.0.0.1:2379', ttl: 5000 }); ``` ## Usage ```js import Keyv from 'keyv'; import KeyvEtcd from '@keyv/etcd'; const store = new KeyvEtcd('etcd://localhost:2379'); const keyv = new Keyv({ store }); // set a value await keyv.set('foo', 'bar'); // set a value with TTL (in milliseconds) await keyv.set('foo', 'bar', 6000); // get a value const value = await keyv.get('foo'); // delete a value await keyv.delete('foo'); // clear the values written without a namespace await keyv.clear(); // disconnect await store.disconnect(); ``` ## Usage with Namespaces Namespacing is handled natively by the adapter — keys are prefixed with the namespace and separator (`namespace::key`, set with `namespaceSeparator`) before being written to etcd, and the prefix is stripped from keys returned by `iterator()`. Setting a `namespace` on a `Keyv` instance propagates it to the underlying store automatically. Use a separate store instance per namespace so each keeps its own prefix: ```js import Keyv from 'keyv'; import KeyvEtcd from '@keyv/etcd'; const keyv1 = new Keyv({ store: new KeyvEtcd('etcd://localhost:2379'), namespace: 'namespace1' }); const keyv2 = new Keyv({ store: new KeyvEtcd('etcd://localhost:2379'), namespace: 'namespace2' }); // keys are isolated by namespace await keyv1.set('foo', 'bar1'); await keyv2.set('foo', 'bar2'); const value1 = await keyv1.get('foo'); // 'bar1' const value2 = await keyv2.get('foo'); // 'bar2' ``` With no namespace, `clear()` and `iterator()` only touch entries written without a namespace. They leave other namespaces' entries and other applications' keys in etcd alone. Each value records the namespace it was written under, and entries written before that was recorded count when their key has no `:`. Entries Keyv v5 wrote are left alone too, since nothing sets their `{ value, expires }` JSON apart from another application's. To have `clear()` delete every key in etcd and `iterator()` return every key, set `noNamespaceAffectsAll: true`: ```js const store = new KeyvEtcd('etcd://localhost:2379', { noNamespaceAffectsAll: true }); await store.clear(); // deletes every key in etcd ``` You can also set the namespace directly on the store: ```js const store = new KeyvEtcd('etcd://localhost:2379'); store.namespace = 'myapp'; await store.set('foo', 'bar'); // stored as 'myapp:foo' await store.get('foo'); // 'bar' ``` ## Migrating to v6 - **The `etcd3` package was replaced by a built-in client.** v5 used the `etcd3` package, which talks gRPC. v6 has no etcd dependency. It sends HTTP/JSON requests to etcd's gRPC gateway, using the `/v3/` endpoints that etcd 3.4 and later serve. etcd turns the gateway on by default, so don't start the server with `--enable-grpc-gateway=false`. `store.client` is now the built-in `EtcdClient`, not an `Etcd3` instance. - **The store `ttl` applies per key.** In v5, `ttl` created one etcd lease when the store was constructed, and every key was attached to it. When that lease expired, every key on it was deleted at once, no matter when it was written, and later writes failed. In v6, a key written without an expiry lives for `ttl` from its own write, on its own lease. Keys written with a TTL through Keyv also get their own lease. - **The `lease` property was removed.** Remove any code that reads or assigns `store.lease`. - **The `ttlSupport` and `opts` properties were removed.** Read settings from the store's own properties instead, such as `store.url`, `store.ttl`, and `store.busyTimeout`. - **Keys written by v5 need the same namespace and separator.** v5 stored keys as `:`, and Keyv v5 used `keyv` as the namespace when none was set. Keyv v6 has no default namespace, and it joins the namespace and key with `::`. To read those keys, pass the same namespace to Keyv and set `namespaceSeparator` to `':'`: ```js const keyv = new Keyv(new KeyvEtcd('etcd://localhost:2379', { namespaceSeparator: ':' }), { namespace: 'keyv' }); ``` If v5 ran with `useKeyPrefix: false`, its keys have no prefix, so leave the namespace unset. Without a namespace, `clear()` deletes every key in etcd. See the [v5 to v6 migration guide](https://keyv.org/docs/migration/v5-to-v6/#keyvetcd-default-ttl-applies-per-key) for more. ## Options | Option | Type | Default | Description | |---|---|---|---| | `url` | `string` | `'127.0.0.1:2379'` | The etcd server URL. The `etcd://` protocol prefix is automatically stripped. | | `uri` | `string` | — | Alias for `url` | | `ttl` | `number` | `undefined` | Default TTL in milliseconds for keys written without an expiry, counted from each write. Each such key gets its own etcd lease. | | `busyTimeout` | `number` | `undefined` | Per-request timeout in milliseconds. Aborts hung requests via `AbortSignal.timeout`. | | `namespace` | `string` | `undefined` | Key prefix for namespace isolation | | `namespaceSeparator` | `string` | `'::'` | Separator placed between the namespace and key | | `noNamespaceAffectsAll` | `boolean` | `false` | With no namespace, whether `clear()` and `iterator()` reach every key in etcd instead of only entries written without a namespace | ```js import KeyvEtcd from '@keyv/etcd'; // Using a URI string const store = new KeyvEtcd('etcd://localhost:2379'); // Using an options object const store2 = new KeyvEtcd({ url: '127.0.0.1:2379', ttl: 5000 }); // Using a URI string with additional options const store3 = new KeyvEtcd('etcd://localhost:2379', { ttl: 5000, busyTimeout: 3000 }); ``` ## Properties ### .client The underlying `EtcdClient` instance — a lightweight wrapper around the etcd v3 HTTP/JSON gateway. Can be used to issue raw etcd requests directly. | Type | Default | |---|---| | `EtcdClient` | Created from the `url` option | ### .url The etcd server URL. | Type | Default | |---|---| | `string` | `'127.0.0.1:2379'` | ### .ttl Default TTL in milliseconds for keys written without an expiry, counted from each write. It can be changed at any time, and each such key gets its own etcd lease, rounded up to whole seconds. | Type | Default | |---|---| | `number \| undefined` | `undefined` | ### .busyTimeout Per-request timeout in milliseconds. When set, every HTTP request to etcd is aborted via `AbortSignal.timeout` if it does not complete within this window. Updating the setter applies to subsequent requests. | Type | Default | |---|---| | `number \| undefined` | `undefined` | ### .namespace Key prefix for namespace isolation. When set, all keys are prefixed with `namespace:`. | Type | Default | |---|---| | `string \| undefined` | `undefined` | ### .namespaceSeparator The separator between the namespace and key. | Type | Default | |---|---| | `string` | `'::'` | ### .noNamespaceAffectsAll With no namespace set, whether `clear()` and `iterator()` reach every key in etcd. When `false`, they only touch entries written without a namespace. It has no effect when a namespace is set. | Type | Default | |---|---| | `boolean` | `false` | ## Methods ### constructor(url?, options?) Creates a new `KeyvEtcd` instance. - `url` — An etcd server URI string (e.g., `'etcd://localhost:2379'`) or a `KeyvEtcdOptions` object. Defaults to `'127.0.0.1:2379'` if not provided. - `options` — Optional `KeyvEtcdOptions` object. When both `url` and `options` are objects, they are merged together. ```js import KeyvEtcd from '@keyv/etcd'; // Using a URI string const store = new KeyvEtcd('etcd://localhost:2379'); // Using an options object const store2 = new KeyvEtcd({ url: '127.0.0.1:2379', ttl: 5000 }); // Using a URI string with additional options const store3 = new KeyvEtcd('etcd://localhost:2379', { ttl: 5000 }); ``` ### .get(key) Retrieves a value from the etcd server. Returns the stored value or `undefined` if the key does not exist. ```js const store = new KeyvEtcd('etcd://localhost:2379'); await store.set('foo', 'bar'); const result = await store.get('foo'); // 'bar' ``` ### .getMany(keys) Retrieves multiple values from the etcd server. Returns an array of stored data corresponding to each key. ```js const store = new KeyvEtcd('etcd://localhost:2379'); await store.set('key1', 'value1'); await store.set('key2', 'value2'); const results = await store.getMany(['key1', 'key2']); ``` ### .set(key, value, expires?) Stores a value in the etcd server. If `expires` is provided, a dedicated etcd lease (sized from the remaining time) is created for that key. Otherwise, a positive default `ttl` expires the key `ttl` milliseconds after this write, on its own lease. Returns `true` on success, `false` on failure. > When you call the adapter directly, the third argument is an **absolute** `expires` timestamp (Unix ms since epoch), not a relative duration. Through Keyv (`keyv.set(key, value, ttl)`) you still pass a relative TTL — Keyv converts it to `expires` for you. - `key` *(string)* - The key to set. - `value` *(any)* - The value to store. - `expires` *(number, optional)* - Absolute expiry as Unix ms since epoch. `undefined` means no expiry. - Returns: `Promise` ```js const store = new KeyvEtcd('etcd://localhost:2379'); await store.set('foo', 'bar'); await store.set('foo', 'bar', Date.now() + 5000); // expires in ~5 seconds ``` ### .setMany(entries) Stores multiple values in the etcd server. Each entry is a `KeyvStorageEntry` object (`{ key: string, value: Value, expires?: number }`) where `expires` is an absolute Unix ms timestamp, and `Value` is inferred from the entries provided. Returns a `boolean[]` indicating whether each entry was set successfully. ```js const store = new KeyvEtcd('etcd://localhost:2379'); const results = await store.setMany([ { key: 'key1', value: 'value1' }, { key: 'key2', value: 'value2' }, ]); // [true, true] ``` ### .delete(key) Deletes a key from the etcd server. Returns `true` if the key was deleted, `false` otherwise. ```js const store = new KeyvEtcd('etcd://localhost:2379'); await store.set('foo', 'bar'); const deleted = await store.delete('foo'); // true ``` ### .deleteMany(keys) Deletes multiple keys from the etcd server. Returns a `boolean[]` indicating whether each key was deleted. ```js const store = new KeyvEtcd('etcd://localhost:2379'); await store.set('key1', 'value1'); await store.set('key2', 'value2'); const results = await store.deleteMany(['key1', 'key2']); // [true, true] ``` ### .clear() Clears data from the etcd server. If a namespace is set, only keys with the namespace prefix are deleted. Otherwise only entries written without a namespace are deleted, and other namespaces' entries and other applications' keys stay. Set `noNamespaceAffectsAll` to `true` to delete every key in etcd instead. With no namespace, `clear()` reads every key in etcd, a page at a time, to find the entries to delete. ```js const store = new KeyvEtcd('etcd://localhost:2379'); await store.clear(); ``` ### .has(key) Checks whether a key exists in the etcd server. ```js const store = new KeyvEtcd('etcd://localhost:2379'); await store.set('foo', 'bar'); const exists = await store.has('foo'); // true const missing = await store.has('baz'); // false ``` ### .hasMany(keys) Checks whether multiple keys exist in the etcd server. Returns an array of booleans corresponding to each key. ```js const store = new KeyvEtcd('etcd://localhost:2379'); await store.set('key1', 'value1'); await store.set('key2', 'value2'); const results = await store.hasMany(['key1', 'key2', 'key3']); // [true, true, false] ``` ### .iterator() Returns an async iterator over `[key, value]` pairs. If a namespace is set, only keys with that namespace are yielded and the namespace prefix is removed from the returned keys. The namespace does not need to be passed in — it uses the namespace configured on the adapter. With no namespace, only entries written without a namespace are yielded, unless `noNamespaceAffectsAll` is `true`, which yields every key in etcd. Expired entries are skipped and deleted. ```js const store = new KeyvEtcd('etcd://localhost:2379'); await store.set('key1', 'value1'); await store.set('key2', 'value2'); for await (const [key, value] of store.iterator()) { console.log(key, value); } ``` ### .disconnect() Gracefully disconnects from the etcd server. ```js const store = new KeyvEtcd('etcd://localhost:2379'); await store.disconnect(); ``` ### .formatKey(key) Formats a key by prepending the namespace if one is set. A key that already starts with the namespace prefix gets it again, so `myapp:foo` and `foo` stay separate keys. ```js const store = new KeyvEtcd('etcd://localhost:2379'); store.formatKey('foo'); // 'foo' store.namespace = 'myapp'; store.formatKey('foo'); // 'myapp:foo' store.formatKey('myapp:foo'); // 'myapp:myapp:foo' ``` ### .createKeyPrefix(key, namespace?) Creates a prefixed key by prepending the namespace and separator. If no namespace is provided, the key is returned unchanged. ```js const store = new KeyvEtcd('etcd://localhost:2379'); store.createKeyPrefix('key', 'ns'); // 'ns::key' store.createKeyPrefix('key'); // 'key' ``` ### .removeKeyPrefix(key, namespace?) Removes the namespace prefix from the start of a key. If no namespace is provided or the key does not start with the prefix, the key is returned unchanged. ```js const store = new KeyvEtcd('etcd://localhost:2379'); store.removeKeyPrefix('ns::key', 'ns'); // 'key' store.removeKeyPrefix('key'); // 'key' ``` ## License [MIT © Jared Wray](LICENSE) ### @keyv/dynamo URL: https://keyv.org/docs/storage-adapters/dynamo/ # @keyv/dynamo [keyv](https://github.com/jaredwray/keyv) > DynamoDB storage adapter for [Keyv](https://github.com/jaredwray/keyv) [![build](https://github.com/jaredwray/keyv/actions/workflows/tests.yaml/badge.svg)](https://github.com/jaredwray/keyv/actions/workflows/tests.yaml) [![codecov](https://codecov.io/gh/jaredwray/keyv/branch/main/graph/badge.svg?token=bRzR3RyOXZ)](https://codecov.io/gh/jaredwray/keyv) [![GitHub license](https://img.shields.io/github/license/jaredwray/keyv)](https://github.com/jaredwray/keyv/blob/main/LICENSE) [![npm](https://img.shields.io/npm/v/@keyv/dynamo.svg)](https://www.npmjs.com/package/@keyv/dynamo) [![npm](https://img.shields.io/npm/dm/@keyv/dynamo)](https://npmjs.com/package/@keyv/dynamo) ## Features - Built on [@aws-sdk/client-dynamodb](https://www.npmjs.com/package/@aws-sdk/client-dynamodb) and [@aws-sdk/lib-dynamodb](https://www.npmjs.com/package/@aws-sdk/lib-dynamodb) with full TypeScript support - TTL support via DynamoDB TTL on the `expiresAt` attribute. Keys set without a TTL never expire - Namespace support for key isolation across multiple Keyv instances - Automatic table creation with `PAY_PER_REQUEST` billing mode - `setMany`, `getMany`, `deleteMany`, and `hasMany` batch operations - Async `iterator` support with namespace-aware filtering - `createKeyv` helper for quick setup > **Note:** DynamoDB doesn't guarantee data will be deleted immediately upon expiration. See the [DynamoDB TTL documentation](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/TTL.html) for details. ## Table of Contents - [Install](#install) - [Quick Start with createKeyv](#quick-start-with-createkeyv) - [Usage](#usage) - [Usage with Namespaces](#usage-with-namespaces) - [Usage with NestJS](#usage-with-nestjs) - [Migrating to v6](#migrating-to-v6) - [Options](#options) - [Properties](#properties) - [.client](#client) - [.namespace](#namespace) - [.namespaceSeparator](#namespaceseparator) - [.tableName](#tablename) - [.endpoint](#endpoint) - [Methods](#methods) - [constructor(options?)](#constructoroptions) - [.get(key)](#getkey) - [.getMany(keys)](#getmanykeys) - [.set(key, value, expires?)](#setkey-value-expires) - [.setMany(entries)](#setmanyentries) - [.delete(key)](#deletekey) - [.deleteMany(keys)](#deletemanykeys) - [.clear()](#clear) - [.has(key)](#haskey) - [.hasMany(keys)](#hasmanykeys) - [.iterator()](#iterator) - [.disconnect()](#disconnect) - [.formatKey(key)](#formatkeykey) - [.createKeyPrefix(key, namespace?)](#createkeyprefixkey-namespace) - [.removeKeyPrefix(key, namespace?)](#removekeyprefixkey-namespace) - [.ensureTable(tableName)](#ensuretabletablename) - [.createTable(tableName)](#createtabletablename) - [License](#license) ## Install ```shell npm install --save keyv @keyv/dynamo ``` ## Quick Start with createKeyv ```js import { createKeyv } from '@keyv/dynamo'; const keyv = createKeyv({ endpoint: 'http://localhost:8000' }); // set a value await keyv.set('foo', 'bar'); // get a value const value = await keyv.get('foo'); // set with TTL (milliseconds) await keyv.set('foo', 'bar', 6000); // delete a value await keyv.delete('foo'); ``` You can also pass options: ```js import { createKeyv } from '@keyv/dynamo'; const keyv = createKeyv({ endpoint: 'http://localhost:8000', tableName: 'cacheTable', namespace: 'my-app', }); ``` ## Usage ```js import Keyv from 'keyv'; import KeyvDynamo from '@keyv/dynamo'; const store = new KeyvDynamo({ endpoint: 'http://localhost:8000' }); const keyv = new Keyv(store); // set a value await keyv.set('foo', 'bar'); // set a value with TTL (in milliseconds) await keyv.set('foo', 'bar', 6000); // get a value const value = await keyv.get('foo'); // delete a value await keyv.delete('foo'); // clear all values await keyv.clear(); ``` ## Usage with Namespaces ```js import Keyv from 'keyv'; import KeyvDynamo from '@keyv/dynamo'; // Keyv passes its namespace to the adapter, which stores `foo` as `namespace1:foo`. // Give each Keyv instance its own adapter. const store1 = new KeyvDynamo({ endpoint: 'http://localhost:8000' }); const keyv1 = new Keyv(store1, { namespace: 'namespace1' }); const store2 = new KeyvDynamo({ endpoint: 'http://localhost:8000' }); const keyv2 = new Keyv(store2, { namespace: 'namespace2' }); // keys are isolated by namespace await keyv1.set('foo', 'bar1'); await keyv2.set('foo', 'bar2'); const value1 = await keyv1.get('foo'); // 'bar1' const value2 = await keyv2.get('foo'); // 'bar2' ``` ## Usage with NestJS > **Note:** `cache-manager` 7 depends on Keyv v5. It reads expiry data with `store.get(key, { raw: true })`, which a v6 `Keyv` ignores, so `ttl()` and the refresh logic in `wrap()` stop working with a v6 store. Check which Keyv version your `cache-manager` needs with `npm view cache-manager dependencies.keyv`. See [Libraries That Embed Keyv v5](https://keyv.org/docs/migration/v5-to-v6/#libraries-that-embed-keyv-v5). Since DynamoDB has a 400KB limit per item, compressing data can help in some cases. ### With a payload less than or equal to 400KB ```js import { Keyv } from 'keyv' import { KeyvDynamo } from '@keyv/dynamo' import { CacheModule } from '@nestjs/cache-manager' import { Module } from '@nestjs/common' @Module({ imports: [ CacheModule.registerAsync({ isGlobal: true, useFactory: async () => { return { stores: [ new Keyv({ store: new KeyvDynamo({ tableName: 'TableName', }), }), ], } }, }), ], }) export class InfrastructureModule {} ``` ### With a payload greater than 400KB ```js import { Keyv } from 'keyv' import KeyvBrotli from '@keyv/compress-brotli' import { KeyvDynamo } from '@keyv/dynamo' import { CacheModule } from '@nestjs/cache-manager' import { Module } from '@nestjs/common' @Module({ imports: [ CacheModule.registerAsync({ isGlobal: true, useFactory: async () => { return { stores: [ new Keyv({ store: new KeyvDynamo({ tableName: 'TableName', }), compression: new KeyvBrotli(), }), ], } }, }), ], }) export class InfrastructureModule {} ``` ## Migrating to v6 - **Keys written without a TTL no longer expire.** In v5, every key written without a TTL got an expiry six hours after the write. In v6, such a key has no expiry and is kept until it is deleted. To keep a default expiry, set Keyv's `ttl` option: ```js const keyv = new Keyv(store, { ttl: 6 * 60 * 60 * 1000 }); ``` - **`sixHoursInMilliseconds` was removed.** Remove any code that reads or assigns `store.sixHoursInMilliseconds`. - **Keys written by v5 keep the expiry they were written with** until they are written again. - **The `ttlSupport` and `opts` properties were removed.** Use the `tableName` and `endpoint` properties instead. - **The adapter's `set` takes an absolute `expires`.** v5's `set(key, value, ttl)` took a relative `ttl`. This only affects code that calls the adapter directly. See [.set(key, value, expires?)](#setkey-value-expires). - **Keys written by v5 need matching namespace settings.** Keyv v6 has no default namespace. - v5's default setup, `new Keyv(new KeyvDynamo(options))`, stored `foo` as `keyv:foo`. v6 joins the namespace and key with `::`, so read those keys with `new Keyv(new KeyvDynamo({ ...options, namespaceSeparator: ':' }), { namespace: 'keyv' })`. If you set your own namespace in v5, pass that one instead. - Keys written through v5's `createKeyv()` were stored without a prefix, even when you passed a `namespace`. The same is true when v5 ran with `useKeyPrefix: false`. Read those keys without a namespace. Without a namespace, `clear()` deletes every item in the table. See the [v5 to v6 migration guide](https://keyv.org/docs/migration/v5-to-v6/#keyvdynamo-keys-without-a-ttl-no-longer-expire) for more. ## Options Options extend [`DynamoDBClientConfig`](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/dynamodb/) so all AWS SDK options (endpoint, region, credentials, etc.) are supported. | Option | Type | Default | Description | |---|---|---|---| | `tableName` | `string` | `'keyv'` | The DynamoDB table name. Created automatically if it doesn't exist. | | `namespace` | `string` | `undefined` | Key prefix for namespace isolation | | `namespaceSeparator` | `string` | `'::'` | Separator placed between the namespace and key | | `endpoint` | `string` | — | The DynamoDB endpoint URL (e.g., `'http://localhost:8000'` for local development) | | `uri` | `string` | — | Alias for `endpoint` (for consistency with other Keyv adapters). `endpoint` takes precedence when both are set. | | `region` | `string` | — | The AWS region (e.g., `'us-east-1'`) | ```js import KeyvDynamo from '@keyv/dynamo'; // Using an endpoint string const store = new KeyvDynamo('http://localhost:8000'); // Using an options object const store2 = new KeyvDynamo({ endpoint: 'http://localhost:8000', tableName: 'cacheTable' }); ``` ## Properties ### .client The underlying `DynamoDBDocument` client instance. Can be used to access the DynamoDB client directly. | Type | Default | |---|---| | `DynamoDBDocument` | Created from the options | ### .namespace Key prefix for namespace isolation. When set, all keys are prefixed with `namespace:`. | Type | Default | |---|---| | `string \| undefined` | `undefined` | ### .namespaceSeparator The separator between the namespace and key. | Type | Default | |---|---| | `string` | `'::'` | ### .tableName The DynamoDB table name in use. Read-only. | Type | Default | |---|---| | `string` | `'keyv'` | ### .endpoint The configured DynamoDB endpoint URL, if one was provided. Read-only. | Type | Default | |---|---| | `string \| undefined` | `undefined` | ## Methods ### constructor(options?) Creates a new `KeyvDynamo` instance. Automatically creates the DynamoDB table if it doesn't exist. - `options` — A `KeyvDynamoOptions` object or an endpoint string. Defaults to `{ tableName: 'keyv' }`. ```js import KeyvDynamo from '@keyv/dynamo'; // Using an endpoint string const store = new KeyvDynamo('http://localhost:8000'); // Using an options object const store2 = new KeyvDynamo({ endpoint: 'http://localhost:8000', tableName: 'cacheTable' }); ``` ### .get(key) Retrieves a value from DynamoDB. Returns the stored value or `undefined` if the key does not exist. ```js const store = new KeyvDynamo({ endpoint: 'http://localhost:8000' }); await store.set('foo', 'bar'); const result = await store.get('foo'); // 'bar' ``` ### .getMany(keys) Retrieves multiple values from DynamoDB. Returns an array of stored data corresponding to each key. ```js const store = new KeyvDynamo({ endpoint: 'http://localhost:8000' }); await store.set('key1', 'value1'); await store.set('key2', 'value2'); const results = await store.getMany(['key1', 'key2']); ``` ### .set(key, value, expires?) Stores a value in DynamoDB. With `expires`, the item records it in `expiresAt` (seconds), which DynamoDB TTL uses to delete the item, and in `expiresAtMs` (milliseconds), which reads check so an expired item is never returned. Without `expires`, the item has no expiry and is kept until it is deleted. Returns `true` on success, `false` on failure. > When you call the adapter directly, the third argument is an **absolute** `expires` timestamp (Unix ms since epoch), not a relative duration. Through Keyv (`keyv.set(key, value, ttl)`) you still pass a relative TTL — Keyv converts it to `expires` for you. ```js const store = new KeyvDynamo({ endpoint: 'http://localhost:8000' }); await store.set('foo', 'bar'); // never expires await store.set('foo', 'bar', Date.now() + 60000); // expires in ~60 seconds ``` ### .setMany(entries) Stores multiple values in DynamoDB using `BatchWriteItem` in chunks of 25. Each entry is a `KeyvStorageEntry` object (`{ key: string, value: Value, expires?: number }`), where `expires` is an absolute Unix ms timestamp as in `.set()`, and `Value` is inferred from the entries provided. Returns a `boolean[]` with per-entry success tracking — any items reported as `UnprocessedItems` by DynamoDB are marked as `false`. ```js const store = new KeyvDynamo({ endpoint: 'http://localhost:8000' }); const results = await store.setMany([ { key: 'key1', value: 'value1' }, { key: 'key2', value: 'value2', expires: Date.now() + 60000 }, ]); // [true, true] ``` ### .delete(key) Deletes a key from DynamoDB. Returns `true` if the key was deleted, `false` otherwise. ```js const store = new KeyvDynamo({ endpoint: 'http://localhost:8000' }); await store.set('foo', 'bar'); const deleted = await store.delete('foo'); // true ``` ### .deleteMany(keys) Deletes multiple keys from DynamoDB. Returns a `boolean[]` indicating whether each key was deleted. ```js const store = new KeyvDynamo({ endpoint: 'http://localhost:8000' }); await store.set('key1', 'value1'); await store.set('key2', 'value2'); const results = await store.deleteMany(['key1', 'key2']); // [true, true] ``` ### .clear() Clears data from DynamoDB. If a namespace is set, only keys with the namespace prefix are deleted. Otherwise, all keys are deleted. It scans the whole table, one page per 1 MB of data, so it reads every item in the table even when a namespace is set. ```js const store = new KeyvDynamo({ endpoint: 'http://localhost:8000' }); await store.clear(); ``` ### .has(key) Checks whether a key exists in DynamoDB. ```js const store = new KeyvDynamo({ endpoint: 'http://localhost:8000' }); await store.set('foo', 'bar'); const exists = await store.has('foo'); // true const missing = await store.has('baz'); // false ``` ### .hasMany(keys) Checks whether multiple keys exist in DynamoDB. Returns an array of booleans corresponding to each key. ```js const store = new KeyvDynamo({ endpoint: 'http://localhost:8000' }); await store.set('key1', 'value1'); await store.set('key2', 'value2'); const results = await store.hasMany(['key1', 'key2', 'key3']); // [true, true, false] ``` ### .iterator() Returns an async iterator over all `[key, value]` pairs in the store. If a namespace is set, only keys with that namespace are yielded and the namespace prefix is removed from the returned keys. The namespace does not need to be passed in — it uses the namespace configured on the adapter. Expired entries are skipped and deleted. ```js const store = new KeyvDynamo({ endpoint: 'http://localhost:8000' }); await store.set('key1', 'value1'); await store.set('key2', 'value2'); for await (const [key, value] of store.iterator()) { console.log(key, value); } ``` ### .disconnect() Disconnects from the DynamoDB client. This is a no-op for DynamoDB since it communicates over HTTP requests and does not maintain a persistent connection. ```js const store = new KeyvDynamo({ endpoint: 'http://localhost:8000' }); await store.disconnect(); ``` ### .formatKey(key) Formats a key by prepending the namespace if one is set. A key that already starts with the namespace prefix gets it again, so `myapp:foo` and `foo` stay separate keys. ```js const store = new KeyvDynamo({ endpoint: 'http://localhost:8000' }); store.formatKey('foo'); // 'foo' store.namespace = 'myapp'; store.formatKey('foo'); // 'myapp:foo' store.formatKey('myapp:foo'); // 'myapp:myapp:foo' ``` ### .createKeyPrefix(key, namespace?) Creates a prefixed key by prepending the namespace and separator. Returns the key as-is if no namespace is provided. ```js const store = new KeyvDynamo({ endpoint: 'http://localhost:8000' }); store.createKeyPrefix('key', 'ns'); // 'ns::key' store.createKeyPrefix('key'); // 'key' ``` ### .removeKeyPrefix(key, namespace?) Removes the namespace prefix from the start of a key. Returns the key as-is if no namespace is provided or the key does not start with the prefix. ```js const store = new KeyvDynamo({ endpoint: 'http://localhost:8000' }); store.removeKeyPrefix('ns::key', 'ns'); // 'key' store.removeKeyPrefix('key'); // 'key' ``` ### .ensureTable(tableName) Ensures the DynamoDB table exists and is active. If the table is in `CREATING` status, waits for it to become active. If it doesn't exist, creates it. ```js const store = new KeyvDynamo({ endpoint: 'http://localhost:8000' }); await store.ensureTable('my-table'); ``` ### .createTable(tableName) Creates a new DynamoDB table with TTL support enabled on the `expiresAt` attribute. Uses `PAY_PER_REQUEST` billing mode. ```js const store = new KeyvDynamo({ endpoint: 'http://localhost:8000' }); await store.createTable('my-table'); ``` ## License [MIT © Jared Wray](LICENSE) ### @keyv/cloudflare-kv URL: https://keyv.org/docs/storage-adapters/cloudflare-kv/ # @keyv/cloudflare-kv [keyv](https://github.com/jaredwray/keyv) > Cloudflare Workers KV storage adapter for [Keyv](https://github.com/jaredwray/keyv) [![build](https://github.com/jaredwray/keyv/actions/workflows/tests.yaml/badge.svg)](https://github.com/jaredwray/keyv/actions/workflows/tests.yaml) [![codecov](https://codecov.io/gh/jaredwray/keyv/branch/main/graph/badge.svg?token=bRzR3RyOXZ)](https://codecov.io/gh/jaredwray/keyv) [![GitHub license](https://img.shields.io/github/license/jaredwray/keyv)](https://github.com/jaredwray/keyv/blob/main/LICENSE) [![npm](https://img.shields.io/npm/v/@keyv/cloudflare-kv.svg)](https://www.npmjs.com/package/@keyv/cloudflare-kv) [![npm](https://img.shields.io/npm/dm/@keyv/cloudflare-kv)](https://npmjs.com/package/@keyv/cloudflare-kv) Use [Cloudflare Workers KV](https://developers.cloudflare.com/kv/) as a Keyv storage backend in one of two **modes**: - **`bind`** (default) — a native KV **binding**, the object exposed as `env.MY_KV` inside a Cloudflare Worker (or a [Miniflare](https://developers.cloudflare.com/workers/testing/miniflare/) namespace in tests). Use this when your code runs inside the Workers runtime. - **`rest`** — the Cloudflare **REST API**, authenticated with account credentials. Use this from any plain Node.js process (a server, a job, a CLI) that can't get a Worker binding. ## Features - Two transport modes — `bind` (native binding, default) and `rest` (REST API) — selectable via the `mode` option - Millisecond-precise TTLs enforced client-side, with a native KV `expirationTtl` on every expiring key so Cloudflare reclaims space on its own - Namespace support for key isolation across multiple Keyv instances - `setMany`, `getMany`, `deleteMany`, and `hasMany` batch operations - Async `iterator` support with namespace-aware filtering and automatic pagination - Fully testable locally with Miniflare — no Cloudflare account required - `createKeyv` helper for quick setup > **Note:** Cloudflare KV is eventually consistent. It caches reads (for 60 seconds by default), so a read after a write or delete can return the previous value until that cache expires. Changes are usually visible straight away in the location that made them, but not always: over the REST API, a `get()` straight after `delete()` can still return the deleted value. KV's native expiry also has a 60-second minimum. This adapter stores an expiry timestamp alongside each value and enforces it on read, so TTLs behave precisely regardless of the native minimum. See the [Cloudflare KV docs](https://developers.cloudflare.com/kv/concepts/how-kv-works/) for details. ## Table of Contents - [Install](#install) - [Quick Start with createKeyv](#quick-start-with-createkeyv) - [Usage with a Worker Binding](#usage-with-a-worker-binding) - [Usage with the REST API](#usage-with-the-rest-api) - [Usage with Namespaces](#usage-with-namespaces) - [Testing Locally with Miniflare](#testing-locally-with-miniflare) - [How Values Are Stored](#how-values-are-stored) - [Options](#options) - [Properties](#properties) - [Methods](#methods) - [License](#license) ## Install ```shell npm install --save keyv @keyv/cloudflare-kv ``` ## Quick Start with createKeyv ```js import { createKeyv } from '@keyv/cloudflare-kv'; // REST mode (from any Node.js process) const keyv = createKeyv({ mode: 'rest', accountId: process.env.CF_ACCOUNT_ID, namespaceId: process.env.CF_KV_NAMESPACE_ID, apiToken: process.env.CF_API_TOKEN, }); // set a value await keyv.set('foo', 'bar'); // get a value const value = await keyv.get('foo'); // set with TTL (milliseconds) await keyv.set('foo', 'bar', 60000); // delete a value await keyv.delete('foo'); ``` ## Usage with a Worker Binding Inside a Cloudflare Worker, pass the binding (e.g. `env.MY_KV`) directly: ```js import Keyv from 'keyv'; import KeyvCloudflareKV from '@keyv/cloudflare-kv'; export default { async fetch(request, env) { // `bind` is the default mode; passing a binding is all you need. const store = new KeyvCloudflareKV({ kvNamespace: env.MY_KV }); const keyv = new Keyv(store); await keyv.set('foo', 'bar'); return new Response(await keyv.get('foo')); }, }; ``` You can also pass the binding directly as the only argument: ```js const store = new KeyvCloudflareKV(env.MY_KV); ``` ## Usage with the REST API From a regular Node.js server, set `mode: 'rest'` and authenticate with a Cloudflare API token that has the `Workers KV Storage` Edit permission: ```js import Keyv from 'keyv'; import KeyvCloudflareKV from '@keyv/cloudflare-kv'; const store = new KeyvCloudflareKV({ mode: 'rest', accountId: 'your-account-id', namespaceId: 'your-kv-namespace-id', apiToken: 'your-api-token', }); const keyv = new Keyv(store); await keyv.set('foo', 'bar'); const value = await keyv.get('foo'); // 'bar' ``` > `mode` defaults to `'bind'`. If you omit it, the adapter infers `'rest'` when you pass REST > credentials and `'bind'` when you pass a binding — but setting it explicitly is recommended. ## Usage with Namespaces ```js import Keyv from 'keyv'; import KeyvCloudflareKV from '@keyv/cloudflare-kv'; // Keyv passes its namespace to the adapter, which stores `foo` as `namespace1:foo`. // Give each Keyv instance its own adapter. const store1 = new KeyvCloudflareKV({ kvNamespace }); const keyv1 = new Keyv(store1, { namespace: 'namespace1' }); const store2 = new KeyvCloudflareKV({ kvNamespace }); const keyv2 = new Keyv(store2, { namespace: 'namespace2' }); // keys are isolated by namespace await keyv1.set('foo', 'bar1'); await keyv2.set('foo', 'bar2'); const value1 = await keyv1.get('foo'); // 'bar1' const value2 = await keyv2.get('foo'); // 'bar2' ``` ## Testing Locally with Miniflare The adapter accepts any object implementing the Cloudflare `KVNamespace` interface, so you can test against a real local KV — no account needed — using [Miniflare](https://developers.cloudflare.com/workers/testing/miniflare/): ```js import { Miniflare } from 'miniflare'; import KeyvCloudflareKV from '@keyv/cloudflare-kv'; const mf = new Miniflare({ modules: true, script: "export default { fetch() { return new Response('ok'); } };", kvNamespaces: ['KV'], }); const kvNamespace = await mf.getKVNamespace('KV'); const store = new KeyvCloudflareKV({ kvNamespace }); await store.set('foo', 'bar'); console.log(await store.get('foo')); // 'bar' await mf.dispose(); ``` ### How this package is tested The test suite runs against a **real local Cloudflare KV**, not in-memory stubs: - **`bind` mode** is tested directly against a Miniflare KV namespace. - **`rest` mode** is tested end-to-end against a small local HTTP server that implements the Cloudflare KV REST API on top of that *same* Miniflare namespace — so the REST client exercises real local storage rather than mocked `fetch` responses. This local server emulates Cloudflare's live REST environment. We keep it in sync with the Cloudflare API and additionally run a **live integration test** (the `cloudflare-keyv-integration` GitHub workflow) against the real Cloudflare KV API, so we notice if the live behavior ever drifts from the emulation. That workflow requires the `CLOUDFLARE_ACCOUNT_ID`, `CLOUDFLARE_KV_NAMESPACE_ID`, and `CLOUDFLARE_API_TOKEN_KV_TESTS` repository secrets and self-skips when they are absent. ## How Values Are Stored Keyv owns serialization, so the adapter stores the **already-serialized value string directly** — it does not wrap values in its own JSON envelope. The absolute expiry is stored in Cloudflare KV **metadata** (`{ e: }`) rather than mixed into the value. Because KV's native expiry has a 60-second minimum, the adapter enforces expiry on every read using that metadata, so TTLs are millisecond-precise. It also passes a native KV `expirationTtl`, so Cloudflare removes the entry on its own, even one that is never read again. A TTL shorter than the 60-second minimum gets the minimum, so the entry stays in KV for up to about a minute after its deadline, but reads already treat it as missing. > When used directly (not through Keyv), the adapter expects string values, since KV only stores > strings. A non-string passed directly is coerced with `String()`. Wrap the adapter in a `Keyv` > instance to store arbitrary values. ## Options For **`bind`** mode provide a `kvNamespace` binding; for **`rest`** mode provide `accountId`, `namespaceId`, and `apiToken`. | Option | Type | Default | Description | |---|---|---|---| | `mode` | `'bind' \| 'rest'` | `'bind'` | Transport to use. Inferred from the other options when omitted. | | `kvNamespace` | `KVNamespace` | — | A Cloudflare KV binding (Worker binding or Miniflare namespace). Used by `bind` mode. | | `accountId` | `string` | — | Cloudflare account ID (`rest` mode). | | `namespaceId` | `string` | — | KV namespace ID — not the binding name (`rest` mode). | | `apiToken` | `string` | — | Cloudflare API token with Workers KV Edit permission (`rest` mode). | | `url` | `string` | `https://api.cloudflare.com/client/v4` | Override the REST base URL (`rest` mode). | | `namespace` | `string` | `undefined` | Key prefix for namespace isolation. | | `namespaceSeparator` | `string` | `'::'` | Separator placed between the namespace and key. | ## Properties ### .mode The resolved transport mode in use. Read-only. | Type | Default | |---|---| | `'bind' \| 'rest'` | `'bind'` | ### .client The underlying `KVNamespace` (a binding or the built-in `CloudflareKVRestClient`). Useful for direct, low-level access. | Type | Default | |---|---| | `CloudflareKVNamespace` | Derived from the options | ### .namespace Key prefix for namespace isolation. When set, all keys are prefixed with `namespace:`. | Type | Default | |---|---| | `string \| undefined` | `undefined` | ### .namespaceSeparator The separator between the namespace and key. | Type | Default | |---|---| | `string` | `'::'` | ## Methods ### constructor(options) Creates a new `KeyvCloudflareKV` instance. Pass a `KeyvCloudflareKVOptions` object or a Cloudflare KV binding directly. ```js import KeyvCloudflareKV from '@keyv/cloudflare-kv'; // Binding const store = new KeyvCloudflareKV({ kvNamespace }); // REST credentials const store2 = new KeyvCloudflareKV({ accountId, namespaceId, apiToken }); ``` ### .get(key) Retrieves a value. Returns the stored value or `undefined` if the key does not exist or has expired. ### .getMany(keys) Retrieves multiple values. Returns an array of values (`undefined` for missing/expired keys). ### .set(key, value, expires?) Stores a value with an optional absolute `expires` timestamp (Unix ms since epoch). ### .setMany(entries) Stores multiple `{ key, value, expires? }` entries. Returns a `boolean[]` with per-entry success. ### .delete(key) Deletes a key. Returns `true` if the key existed, `false` otherwise. ### .deleteMany(keys) Deletes multiple keys. Returns a `boolean[]` indicating which keys existed. ### .clear() Clears the store. If a namespace is set, only keys with that prefix are deleted; otherwise all keys in the KV namespace are removed. ### .has(key) Returns `true` if a key exists and is not expired, `false` otherwise. ### .hasMany(keys) Returns a `boolean[]` indicating whether each key exists. ### .iterator() Returns an async iterator over `[key, value]` pairs. When a namespace is set, only namespaced keys are yielded and the prefix is stripped from the returned keys. Pagination is handled automatically. ```js for await (const [key, value] of store.iterator()) { console.log(key, value); } ``` ### .disconnect() No-op. Cloudflare KV uses stateless HTTP requests / in-process bindings, so there is no connection to close. ### .formatKey(key) / .createKeyPrefix(key, namespace?) / .removeKeyPrefix(key, namespace?) Namespace-aware key helpers, matching the other Keyv adapters. ## License [MIT © Jared Wray](LICENSE) ### @keyv/bigmap URL: https://keyv.org/docs/storage-adapters/bigmap/ # @keyv/bigmap [keyv](https://github.com/jaredwray/keyv) > Bigmap for Keyv [![build](https://github.com/jaredwray/keyv/actions/workflows/tests.yaml/badge.svg)](https://github.com/jaredwray/keyv/actions/workflows/tests.yaml) [![codecov](https://codecov.io/gh/jaredwray/keyv/branch/main/graph/badge.svg?token=bRzR3RyOXZ)](https://codecov.io/gh/jaredwray/keyv) [![npm](https://img.shields.io/npm/v/@keyv/bigmap.svg)](https://www.npmjs.com/package/@keyv/bigmap) [![npm](https://img.shields.io/npm/dm/@keyv/bigmap)](https://npmjs.com/package/@keyv/bigmap) # Features * Based on the Map interface and uses the same API. * Lightweight and easy to use. * Scales to past the 17 million key limit of a regular Map. * Ability to use your own hash function. * Built in Typescript and Generics for type safety. * Used in `@cacheable/memory` for scalable in-memory caching. * Maintained regularly with a focus on performance and reliability. # Table of Contents - [Features](#features) - [Installation](#installation) - [Overview](#overview) - [Basic Usage](#basic-usage) - [Custom Store Size](#custom-store-size) - [Custom Hash Function](#custom-hash-function) - [Iteration](#iteration) - [For...of Loop](#forof-loop) - [forEach](#foreach) - [Keys, Values, and Entries](#keys-values-and-entries) - [Events](#events) - [Advanced Features](#advanced-features) - [Type Safety with Generics](#type-safety-with-generics) - [Large-Scale Data](#large-scale-data) - [Using with Keyv](#using-with-keyv) - [createKeyv](#createkeyv) - [With Custom Options](#with-custom-options) - [Type Safety](#type-safety) - [Integration with Keyv Ecosystem](#integration-with-keyv-ecosystem) - [API](#api) - [Constructor](#constructor) - [Properties](#properties) - [Methods](#methods) - [set](#set) - [get](#get) - [has](#has) - [delete](#delete) - [clear](#clear) - [forEach](#foreach) - [keys](#keys) - [values](#values) - [entries](#entries) - [Symbol.iterator](#symboliterator) - [getStore](#getstorekey) - [getStoreMap](#getstoremapindex) - [initStore](#initstore) - [Types](#types) - [StoreHashFunction](#storehashfunction) - [BigMapEvents](#bigmapevents) - [defaultHashFunction(key, storeSize)](#defaulthashfunctionkey-storesize) - [Benchmark](#benchmark) - [Migrating to v6](#migrating-to-v6) - [Contributing](#contributing) - [License](#license) # Installation ```bash npm install --save keyv @keyv/bigmap ``` # Overview BigMap is a scalable Map implementation that overcomes JavaScript's built-in Map limit of approximately 17 million entries. It uses a distributed hash approach with multiple internal Map instances. # Basic Usage ```typescript import { BigMap } from '@keyv/bigmap'; // Create a new BigMap const bigMap = new BigMap(); // Set values bigMap.set('key1', 100); bigMap.set('key2', 200); // Get values const value = bigMap.get('key1'); // 100 // Check if key exists bigMap.has('key1'); // true // Delete a key bigMap.delete('key1'); // true // Get size console.log(bigMap.size); // 1 // Clear all entries bigMap.clear(); ``` # Custom Store Size By default, BigMap uses 2 internal Map instances. You can configure this: ```typescript const bigMap = new BigMap({ storeSize: 10 }); ``` Changing `storeSize` after initialization keeps every entry: BigMap moves each one into the internal `Map` its key maps to at the new size. That takes one pass over all entries, so set `storeSize` in the constructor for a large map. # Custom Hash Function Provide your own hash function for key distribution: ```typescript const customHashFunction = (key: string, storeSize: number) => { return key.length % storeSize; }; const bigMap = new BigMap({ storeHashFunction: customHashFunction }); ``` You can also set `storeHashFunction` later. BigMap then moves every existing entry into the `Map` the new function picks, so `get()`, `has()` and `delete()` keep finding them. If the function throws while entries are moved, the setter rethrows and the map is left as it was. ## Using Hashery for Hash Functions [Hashery](https://github.com/jaredwray/hashery) is a powerful hashing library that provides multiple hash algorithms. You can use it for better key distribution and it is available as an export: ```typescript import { BigMap, Hashery } from '@keyv/bigmap'; const hashery = new Hashery(); // Using Hashery's toNumberSync for deterministic key distribution const bigMap = new BigMap({ storeHashFunction: (key: string, storeSize: number) => { return hashery.toNumberSync(key, { min: 0, max: storeSize - 1 }); } }); // You can also use different algorithms const hasheryFnv1 = new Hashery({ defaultAlgorithmSync: 'fnv1' }); const bigMapWithFnv1 = new BigMap({ storeHashFunction: (key: string, storeSize: number) => { return hasheryFnv1.toNumberSync(key, { min: 0, max: storeSize - 1 }); } }); ``` Hashery supports multiple synchronous hash algorithms: - **djb2** - Fast hash function (default) - **fnv1** - Excellent distribution for hash tables - **murmer** - MurmurHash algorithm - **crc32** - Cyclic Redundancy Check # Iteration BigMap supports all standard Map iteration methods: ## For...of Loop ```typescript const bigMap = new BigMap(); bigMap.set('a', 1); bigMap.set('b', 2); for (const [key, value] of bigMap) { console.log(key, value); } ``` ## forEach ```typescript bigMap.forEach((value, key) => { console.log(key, value); }); // With custom context const context = { sum: 0 }; bigMap.forEach(function(value) { this.sum += value; }, context); ``` ## Keys, Values, and Entries ```typescript // Iterate over keys for (const key of bigMap.keys()) { console.log(key); } // Iterate over values for (const value of bigMap.values()) { console.log(value); } // Iterate over entries for (const [key, value] of bigMap.entries()) { console.log(key, value); } ``` # Events `BigMap` extends [Hookified](https://github.com/jaredwray/hookified), so it emits events on mutating operations. Subscribe with `on` (or `once`) using the `BigMapEvents` enum (the values are also plain strings such as `"set"`). Listeners are invoked synchronously, and `BigMapOptions` also accepts any [Hookified options](https://github.com/jaredwray/hookified). | Event | Enum | Payload | Description | |-------------------|----------------------|----------------|------------------------------------------------------------------------------| | `set` | `BigMapEvents.SET` | `(key, value)` | Emitted after a value is set. | | `delete` | `BigMapEvents.DELETE`| `(key)` | Emitted after an existing entry is removed. Not emitted when the key was absent. | | `clear` | `BigMapEvents.CLEAR` | _(none)_ | Emitted after all entries are cleared by `clear()`. | ```typescript import { BigMap, BigMapEvents } from '@keyv/bigmap'; const bigMap = new BigMap(); bigMap.on(BigMapEvents.SET, (key, value) => { console.log('set', key, value); }); bigMap.on(BigMapEvents.DELETE, (key) => { console.log('deleted', key); }); bigMap.on(BigMapEvents.CLEAR, () => { console.log('cleared'); }); bigMap.set('key1', 100); // logs: set key1 100 bigMap.delete('key1'); // logs: deleted key1 bigMap.clear(); // logs: cleared ``` > **Note:** When Hookified's `eventLogger` option is enabled, event arguments — including the value passed to `set` — are serialized with `JSON.stringify` for logging. Values that cannot be JSON-serialized, such as `BigInt` or circular objects, will cause the operation to throw while logging. Leave `eventLogger` unset (the default) if you need to store such values. # Advanced Features ## Type Safety with Generics ```typescript interface User { id: number; name: string; } const userMap = new BigMap(); userMap.set('user1', { id: 1, name: 'Alice' }); ``` ## Large-Scale Data BigMap is designed to handle millions of entries: ```typescript const bigMap = new BigMap({ storeSize: 16 }); // Add 20+ million entries without hitting Map limits for (let i = 0; i < 20000000; i++) { bigMap.set(`key${i}`, i); } console.log(bigMap.size); // 20000000 ``` # Using with Keyv BigMap can be used as a storage adapter for [Keyv](https://github.com/jaredwray/keyv), providing a scalable in-memory store with TTL support. ## createKeyv The `createKeyv` function creates a Keyv instance with BigMap as the storage adapter. **Parameters:** - `options` (optional): BigMap configuration options - `storeSize` (number): Number of internal Map instances. Default: `2` - `storeHashFunction` (StoreHashFunction): Custom hash function for key distribution **Returns:** `Keyv` instance with BigMap adapter **Example:** ```typescript import { createKeyv } from '@keyv/bigmap'; // Basic usage const keyv = createKeyv(); // Set with TTL (in milliseconds) await keyv.set('user:123', { name: 'Alice', age: 30 }, 60000); // Expires in 60 seconds // Get value const user = await keyv.get('user:123'); console.log(user); // { name: 'Alice', age: 30 } // Check if key exists const exists = await keyv.has('user:123'); // Delete key await keyv.delete('user:123'); // Clear all keys await keyv.clear(); ``` ## With Custom Options ```typescript import { createKeyv } from '@keyv/bigmap'; // Create with custom store size for better performance with millions of keys const keyv = createKeyv({ storeSize: 16 }); // With custom hash function const keyv = createKeyv({ storeSize: 8, storeHashFunction: (key, storeSize) => { // Custom distribution logic return key.length % storeSize; } }); ``` ## Type Safety ```typescript import { createKeyv } from '@keyv/bigmap'; interface Product { id: string; name: string; price: number; } const keyv = createKeyv(); await keyv.set('product:1', { id: '1', name: 'Laptop', price: 999 }); const product = await keyv.get('product:1'); ``` # Integration with Keyv Ecosystem BigMap works seamlessly with the Keyv ecosystem: ```typescript import { createKeyv } from '@keyv/bigmap'; const cache = createKeyv({ storeSize: 16 }); // Use with namespaces const users = cache.namespace('users'); const products = cache.namespace('products'); await users.set('123', { name: 'Alice' }); await products.set('456', { name: 'Laptop' }); // Iterate over keys for await (const [key, value] of cache.iterator()) { console.log(key, value); } ``` # API ## Constructor `new BigMap(options?)` Creates a new BigMap instance. **Parameters:** - `options` (optional): Configuration options - `storeSize` (number): Number of internal Map instances to use. Default: `2`. Must be at least 1. - `storeHashFunction` (StoreHashFunction): Custom hash function for key distribution. Default: `defaultHashFunction` **Example:** ```typescript const bigMap = new BigMap(); const customBigMap = new BigMap({ storeSize: 10, storeHashFunction: (key, storeSize) => key.length % storeSize }); ``` ## Properties | Property | Type | Access | Description | |----------|------|--------|-------------| | `size` | `number` | Read-only | Gets the total number of entries in the BigMap. | | `storeSize` | `number` | Read/Write | Gets or sets the number of internal Map instances. Setting it moves every entry into the new layout, so no entries are lost. Default: `2` | | `storeHashFunction` | `StoreHashFunction \| undefined` | Read/Write | Gets or sets the hash function used for key distribution. Setting it moves every entry into the `Map` the new function picks. | | `store` | `Array>` | Read-only | Gets the internal array of Map instances. | **Examples:** ```typescript const bigMap = new BigMap(); // size property bigMap.set('key1', 100); console.log(bigMap.size); // 1 // storeSize property console.log(bigMap.storeSize); // 2 (default) bigMap.storeSize = 8; // Changes size and keeps every entry // storeHashFunction property bigMap.storeHashFunction = (key, storeSize) => key.length % storeSize; // store property console.log(bigMap.store.length); // 8 ``` ## Methods ### set Sets the value for a key in the map. **Parameters:** - `key` (K): The key to set - `value` (V): The value to associate with the key **Returns:** `BigMap` - The BigMap instance, enabling method chaining (matches the native `Map.set` API). **Example:** ```typescript bigMap.set('user123', { name: 'Alice' }); // set() returns the BigMap instance, so calls can be chained bigMap.set('a', { name: 'Alice' }).set('b', { name: 'Bob' }); ``` ### get Gets the value associated with a key. **Parameters:** - `key` (K): The key to retrieve **Returns:** `V | undefined` - The value, or undefined if not found **Example:** ```typescript const value = bigMap.get('user123'); ``` ### has Checks if a key exists in the map. **Parameters:** - `key` (K): The key to check **Returns:** `boolean` - True if the key exists, false otherwise **Example:** ```typescript if (bigMap.has('user123')) { console.log('User exists'); } ``` ### delete Deletes a key-value pair from the map. **Parameters:** - `key` (K): The key to delete **Returns:** `boolean` - True if the entry was deleted, false if the key was not found **Example:** ```typescript const deleted = bigMap.delete('user123'); ``` ### clear Removes all entries from the map. **Returns:** `void` **Example:** ```typescript bigMap.clear(); console.log(bigMap.size); // 0 ``` ### forEach Executes a provided function once for each key-value pair. **Parameters:** - `callbackfn` (function): Function to execute for each entry - `value` (V): The value of the current entry - `key` (K): The key of the current entry - `map` (`Map`): The BigMap instance - `thisArg` (optional): Value to use as `this` when executing the callback **Returns:** `void` **Example:** ```typescript bigMap.forEach((value, key) => { console.log(`${key}: ${value}`); }); // With custom context const context = { total: 0 }; bigMap.forEach(function(value) { this.total += value; }, context); ``` ### keys Returns an iterator of all keys in the map. **Returns:** `IterableIterator` **Example:** ```typescript for (const key of bigMap.keys()) { console.log(key); } ``` ### values Returns an iterator of all values in the map. **Returns:** `IterableIterator` **Example:** ```typescript for (const value of bigMap.values()) { console.log(value); } ``` ### entries Returns an iterator of all key-value pairs in the map. **Returns:** `IterableIterator<[K, V]>` **Example:** ```typescript for (const [key, value] of bigMap.entries()) { console.log(key, value); } ``` ### Symbol.iterator Returns an iterator for the map (same as `entries()`). Enables `for...of` loops. **Returns:** `IterableIterator<[K, V]>` **Example:** ```typescript for (const [key, value] of bigMap) { console.log(key, value); } ``` ### getStore Gets the internal Map instance for a specific key. **Parameters:** - `key` (K): The key to find the store for **Returns:** `Map` - The internal Map instance **Example:** ```typescript const store = bigMap.getStore('user123'); ``` ### getStoreMap Gets the internal Map instance at a specific index. **Parameters:** - `index` (number): The index of the Map to retrieve (0 to storeSize - 1) **Returns:** `Map` - The Map at the specified index **Throws:** Error if index is out of bounds **Example:** ```typescript const firstMap = bigMap.getStoreMap(0); ``` ### initStore Initializes the internal store with empty Map instances. Called automatically during construction. **Returns:** `void` ## Types ### StoreHashFunction Type definition for custom hash functions. ```typescript type StoreHashFunction = (key: string, storeSize: number) => number; ``` **Parameters:** - `key` (string): The key to hash (converted to string) - `storeSize` (number): The total number of stores **Returns:** `number` - The index of the store to use (0 to storeSize - 1) ### BigMapEvents Enum of the event names emitted by `BigMap`. See [Events](#events) for payloads and usage. ```typescript enum BigMapEvents { SET = 'set', DELETE = 'delete', CLEAR = 'clear', } ``` ### defaultHashFunction The built-in hash function used for distributing keys across stores. It uses a fast multiplicative hash with XOR mixing to produce a bucket index. You can override it via the `storeHashFunction` option. **Example:** ```typescript import { defaultHashFunction } from '@keyv/bigmap'; const index = defaultHashFunction('myKey', 2); ``` # Benchmark This benchmark compares `BigMap` against the native JavaScript `Map` for combined `set` and `get` operations using 10,000 iterations of randomly generated data. BigMap trades raw single-threaded speed for the ability to scale past the ~16.7 million entry limit of a native Map by distributing keys across multiple internal Map instances via a hash function. For most workloads under that limit, native Map will be faster; BigMap is designed for scenarios where you need to go beyond it. | name | summary | ops/sec | time/op | margin | samples | |--------------------|:---------:|----------:|----------:|:--------:|----------:| | Map set / get | 🥇 | 19M | 64ns | ±0.02% | 16M | | BigMap set / get | -23% | 14M | 91ns | ±0.03% | 11M | If you want to see comparable performance just set the `storeSize: 1` and it is `-1%` off from native `Map`. # Migrating to v6 Keyv v5 used `@keyv/bigmap` 1.x. Changes in v6: - **Events.** `BigMap` now emits `set`, `delete` and `clear` through its [Hookified](https://github.com/jaredwray/hookified) base, and the new `BigMapEvents` enum names them. In 1.x, `BigMap` extended Hookified but emitted no events. See [Events](#events). - **`MapInterfacee` renamed.** The exported type is now `MapInterface`. - **`set()` returns the `BigMap`.** Calls chain like `Map.set`. In 1.x, `set()` returned the internal `Map` that held the key. - **Default `storeSize` is `2`.** It was `4` in 1.x. Pass `storeSize: 4` to keep the old layout. - **Hashing.** `defaultHashFunction` is now a built-in hash instead of Hashery, so keys land in different internal `Map`s. A custom `storeHashFunction` now receives the real `storeSize` (1.x passed `storeSize - 1`), and an out-of-range result is wrapped into range instead of throwing. This matters only if you read `store`, `getStore()` or `getStoreMap()` directly. - **Changing `storeSize` or `storeHashFunction` keeps your entries.** Both setters move every entry into the internal `Map` its key now maps to. In 1.x, setting `storeSize` removed every entry, and setting `storeHashFunction` left entries where `get()`, `has()` and `delete()` couldn't find them, while `size` still counted them and `set()` added a second copy. If you set `storeSize` to empty the map, call `clear()` as well. - **Dependencies.** `hashery` moved from `^1.4` to `^3` and is still re-exported as `Hashery`. `hookified` moved from `^1.15` to `^3`; if you pass Hookified options to `BigMap`, note that `logger` is now `eventLogger`. - **`createKeyv`** still returns a `Keyv` instance backed by a new `BigMap`. Keyv v6 wraps the `BigMap` in its `KeyvMemoryAdapter`, which handles TTL and namespaces, so the `BigMap` itself is at `keyv.store.store`. # Contributing Please see our [contributing](https://github.com/jaredwray/keyv/blob/main/CONTRIBUTING.md) guide. # License [MIT © Jared Wray](LICENSE) ### Third-Party Storage Adapters URL: https://keyv.org/docs/storage-adapters/third-party/ Description: Community storage adapters and how to implement KeyvStorageAdapter. # Third-Party Storage Adapters Community adapters let you use backends beyond the [official list](/docs/storage-adapters/overview/). Any store that implements `KeyvStorageAdapter` (or a Map-like / legacy async store that Keyv can [bridge](/docs/legacy-storage-adapters/)) works. # Available Adapters | Adapter | Description | |---------|-------------| | [@resolid/keyv-sqlite](https://github.com/huijiewei/keyv-sqlite) | SQLite storage adapter for Keyv | | [keyv-arango](https://github.com/TimMikeladze/keyv-arango) | ArangoDB storage adapter for Keyv | | [keyv-azuretable](https://github.com/howlowck/keyv-azuretable) | Azure Table Storage/API adapter for Keyv | | [keyv-browser](https://github.com/zaaack/keyv-browser) | Browser storage adapter including localStorage and indexedDB | | [keyv-cloudflare](https://npm.im/keyv-cloudflare) | Storage adapter for Cloudflare Workers KV | | [keyv-dynamodb](https://www.npmjs.com/package/keyv-dynamodb) | DynamoDB storage adapter for Keyv | | [keyv-file](https://github.com/zaaack/keyv-file) | File system storage adapter for Keyv | | [keyv-firestore](https://github.com/goto-bus-stop/keyv-firestore) | Firebase Cloud Firestore adapter for Keyv | | [keyv-lru](https://www.npmjs.com/package/keyv-lru) | LRU storage adapter for Keyv | | [keyv-momento](https://github.com/momentohq/node-keyv-adaptor/) | Momento storage adapter for Keyv | | [keyv-mssql](https://github.com/pmorgan3/keyv-mssql) | Microsoft SQL Server adapter for Keyv | | [keyv-null](https://www.npmjs.com/package/keyv-null) | Null storage adapter for Keyv | | [keyv-s3fifo](https://github.com/BJS-kr/fast-s3-fifo-cache) | S3-FIFO storage adapter for Keyv | | [keyv-upstash](https://github.com/mahdavipanah/keyv-upstash) | Upstash Redis adapter for Keyv | | [quick-lru](https://github.com/sindresorhus/quick-lru) | Simple "Least Recently Used" (LRU) cache | # How to Contribute 1. **Build your adapter** following `KeyvStorageAdapter` (below) 2. **Test** with [@keyv/test-suite](/docs/test-suite/) 3. **Publish** to npm with the `keyv` keyword 4. **Open a PR** adding a row to this page (`website/site/docs/storage-adapters/third-party.md`) PR title: `docs: add [your-adapter-name] to third-party storage adapters`. Add the row in alphabetical order. # Building a Storage Adapter v6 adapters take an **absolute** `expires` (Unix ms) on `set` / `setMany` and declare `capabilities.expires`. Legacy relative-`ttl` adapters still work through `KeyvBridgeAdapter`. ```typescript import type { IEventEmitter } from "hookified"; import type { KeyvStorageCapability, KeyvStorageEntry, KeyvValue } from "keyv"; type KeyvStorageGetResult = KeyvValue | string | undefined; type KeyvStorageAdapter = { namespace?: string; capabilities?: KeyvStorageCapability; get(key: string): Promise>; set(key: string, value: unknown, expires?: number): Promise; setMany(values: KeyvStorageEntry[]): Promise; delete(key: string): Promise; clear(): Promise; has(key: string): Promise; hasMany(keys: string[]): Promise; getMany(keys: string[]): Promise>>; deleteMany(keys: string[]): Promise; disconnect?(): Promise; iterator?(): AsyncGenerator | undefined>, void>; } & IEventEmitter; ``` `KeyvStoreAdapter` is a deprecated alias of `KeyvStorageAdapter`. ## Required methods | Method | Description | |--------|-------------| | `get(key)` | Return the stored payload or `undefined`. | | `set(key, value, expires?)` | Persist a value. `expires` is absolute Unix ms; omit for no expiry. | | `getMany(keys)` | Return stored payloads in the same order as the keys. | | `setMany(entries)` | Persist entries and return one result per entry. | | `delete(key)` | Return `true` if the key existed. | | `deleteMany(keys)` | Delete keys and return one result per key. | | `clear()` | Delete keys in the current namespace. | | `has(key)` | Return whether a live value exists. | | `hasMany(keys)` | Return one existence result per key. | ## Optional methods `disconnect` and `iterator` are optional. The other methods above are part of the direct v6 adapter contract. ## Minimal example ```typescript import { EventEmitter } from "events"; import { keyvStorageCapability, type KeyvStorageAdapter, type KeyvStorageCapability, type KeyvStorageEntry, type KeyvStorageGetResult, } from "keyv"; type StoredEntry = { payload: unknown; expires?: number; }; class MyCustomStore extends EventEmitter implements KeyvStorageAdapter { public namespace?: string; private readonly data: Map; public constructor(data = new Map()) { super(); this.data = data; } public get capabilities(): KeyvStorageCapability { return keyvStorageCapability(this); } private prefix(): string { return this.namespace ? `${this.namespace}:` : ""; } private storageKey(key: string): string { return `${this.prefix()}${key}`; } private liveEntry(key: string): StoredEntry | undefined { const storageKey = this.storageKey(key); const entry = this.data.get(storageKey); if (entry?.expires !== undefined && entry.expires <= Date.now()) { this.data.delete(storageKey); return undefined; } return entry; } public async get(key: string): Promise> { return this.liveEntry(key)?.payload as KeyvStorageGetResult; } public async set(key: string, value: unknown, expires?: number): Promise { const storageKey = this.storageKey(key); if (expires !== undefined && expires <= Date.now()) { this.data.delete(storageKey); return true; } const entry: StoredEntry = expires === undefined ? { payload: value } : { payload: value, expires }; this.data.set(storageKey, entry); return true; } public async setMany(entries: KeyvStorageEntry[]): Promise { return Promise.all( entries.map(({ key, value, expires }) => this.set(key, value, expires)), ); } public async delete(key: string): Promise { return this.data.delete(this.storageKey(key)); } public async deleteMany(keys: string[]): Promise { return Promise.all(keys.map((key) => this.delete(key))); } public async getMany( keys: string[], ): Promise>> { return Promise.all(keys.map((key) => this.get(key))); } public async has(key: string): Promise { return this.liveEntry(key) !== undefined; } public async hasMany(keys: string[]): Promise { return Promise.all(keys.map((key) => this.has(key))); } public async clear(): Promise { const prefix = this.prefix(); if (!prefix) { this.data.clear(); return; } for (const key of this.data.keys()) { if (key.startsWith(prefix)) { this.data.delete(key); } } } public async *iterator(): AsyncGenerator< Array | undefined>, void > { const prefix = this.prefix(); for (const [storageKey, entry] of this.data) { if (prefix && !storageKey.startsWith(prefix)) continue; if (entry.expires !== undefined && entry.expires <= Date.now()) { this.data.delete(storageKey); continue; } const key = prefix ? storageKey.slice(prefix.length) : storageKey; yield [key, entry.payload as Awaited]; } } } export default MyCustomStore; ``` ```typescript import Keyv from "keyv"; import MyCustomStore from "./my-custom-store.js"; const keyv = new Keyv({ store: new MyCustomStore(), namespace: "my-app" }); await keyv.set("foo", "bar"); ``` ## Testing ```bash npm install --save-dev vitest keyv @keyv/test-suite ``` ```javascript import { keyvTestSuite, storageTestSuite } from "@keyv/test-suite"; import { Keyv } from "keyv"; import { test } from "vitest"; import MyCustomStore from "./my-custom-store.js"; const store = () => new MyCustomStore(); keyvTestSuite(test, Keyv, store); storageTestSuite(test, store); ``` See the [storage adapters overview](/docs/storage-adapters/overview/) and [legacy adapters](/docs/legacy-storage-adapters/) for the v6 `expires` contract and bridging. ### Serialization URL: https://keyv.org/docs/serialization/overview/ Description: Built-in JSON serializer plus SuperJSON and MessagePack packages. # Serialization Keyv serializes the `{ value, expires? }` envelope before it reaches the store (unless you turn serialization off). That is the first step of the [encode pipeline](/docs/encode-and-decode/). ## Built-in: `KeyvJsonSerializer` Default. No extra package. Handles JSON types plus `Buffer` / `Uint8Array` and `BigInt`. ```js import Keyv, { jsonSerializer } from "keyv"; const keyv = new Keyv(); // already using it keyv.serialization = jsonSerializer; ``` ## Official packages | Package | Format | Extra types | | --- | --- | --- | | (built-in) | JSON | `Buffer`, `BigInt` | | [@keyv/serialize-superjson](/docs/serialization/superjson/) | SuperJSON | `Date`, `Map`, `Set`, `RegExp`, `URL`, `Error`, `undefined` | | [@keyv/serialize-msgpackr](/docs/serialization/msgpackr/) | MessagePack (base64) | `Date`, `Map`, `Set`, `RegExp`, `Error`, `NaN`, `Infinity` | ```js import { superJsonSerializer } from "@keyv/serialize-superjson"; const keyv = new Keyv({ serialization: superJsonSerializer }); await keyv.set("when", new Date()); (await keyv.get("when")) instanceof Date; // true ``` ## Custom and off Implement `{ stringify, parse }` or pass `serialization: false` for raw in-memory objects. Compression and encryption need a serializer. See [Encode and Decode](/docs/encode-and-decode/) for the full pipeline and the adapter interface. ### @keyv/serialize-superjson URL: https://keyv.org/docs/serialization/superjson/ # @keyv/serialize-superjson [keyv](https://github.com/jaredwray/keyv) > SuperJSON-based serializer for [Keyv](https://github.com/jaredwray/keyv) with support for Date, Map, Set, BigInt, RegExp, and more [![build](https://github.com/jaredwray/keyv/actions/workflows/tests.yaml/badge.svg)](https://github.com/jaredwray/keyv/actions/workflows/tests.yaml) [![codecov](https://codecov.io/gh/jaredwray/keyv/branch/main/graph/badge.svg?token=bRzR3RyOXZ)](https://codecov.io/gh/jaredwray/keyv) [![GitHub license](https://img.shields.io/github/license/jaredwray/keyv)](https://github.com/jaredwray/keyv/blob/main/LICENSE) [![npm](https://img.shields.io/npm/dm/@keyv/serialize-superjson)](https://npmjs.com/package/@keyv/serialize-superjson) `@keyv/serialize-superjson` is a serialization adapter for [Keyv](https://github.com/jaredwray/keyv/tree/main/core/keyv) powered by [SuperJSON](https://github.com/flightcontrolhq/superjson). It preserves JavaScript types that standard JSON does not support. ## Supported Types In addition to all standard JSON types, SuperJSON supports: - `Date` - `RegExp` - `Map` - `Set` - `BigInt` - `undefined` - `Error` - `URL` ## Installation ```bash npm install @keyv/serialize-superjson ``` > **Note:** `keyv` is a peer dependency and must be installed alongside this package. ## Usage ```js import Keyv from 'keyv'; import { superJsonSerializer } from '@keyv/serialize-superjson'; const keyv = new Keyv({ serialization: superJsonSerializer }); // Store a Date — it comes back as a Date, not a string await keyv.set('date', new Date('2024-01-15')); const date = await keyv.get('date'); console.log(date instanceof Date); // true // Store a Map await keyv.set('map', new Map([['a', 1], ['b', 2]])); const map = await keyv.get('map'); console.log(map instanceof Map); // true console.log(map.get('a')); // 1 // Store a Set await keyv.set('set', new Set([1, 2, 3])); const set = await keyv.get('set'); console.log(set instanceof Set); // true ``` ## API ### `KeyvSuperJsonSerializer` A class that implements the `KeyvSerializationAdapter` interface from `keyv`. ```js import { KeyvSuperJsonSerializer } from '@keyv/serialize-superjson'; const serializer = new KeyvSuperJsonSerializer(); ``` #### `stringify(object: unknown): string` Serializes a value to a JSON string using SuperJSON, preserving type information. #### `parse(data: string): T` Deserializes a SuperJSON string back to its original value with all types restored. ### `superJsonSerializer` A default `KeyvSuperJsonSerializer` instance, ready to use. ```js import { superJsonSerializer } from '@keyv/serialize-superjson'; ``` ## License [MIT © Jared Wray](LICENSE) ### @keyv/serialize-msgpackr URL: https://keyv.org/docs/serialization/msgpackr/ # @keyv/serialize-msgpackr [keyv](https://github.com/jaredwray/keyv) > High-performance MessagePack serializer for [Keyv](https://github.com/jaredwray/keyv) using [msgpackr](https://github.com/kriszyp/msgpackr) [![build](https://github.com/jaredwray/keyv/actions/workflows/tests.yaml/badge.svg)](https://github.com/jaredwray/keyv/actions/workflows/tests.yaml) [![codecov](https://codecov.io/gh/jaredwray/keyv/branch/main/graph/badge.svg?token=bRzR3RyOXZ)](https://codecov.io/gh/jaredwray/keyv) [![GitHub license](https://img.shields.io/github/license/jaredwray/keyv)](https://github.com/jaredwray/keyv/blob/main/LICENSE) [![npm](https://img.shields.io/npm/dm/@keyv/serialize-msgpackr)](https://npmjs.com/package/@keyv/serialize-msgpackr) `@keyv/serialize-msgpackr` is a serialization adapter for [Keyv](https://github.com/jaredwray/keyv/tree/main/core/keyv) powered by [msgpackr](https://github.com/kriszyp/msgpackr). It uses the MessagePack binary format for high-performance serialization with rich type support. ## Supported Types In addition to all standard JSON types, msgpackr supports: - `Date` - `RegExp` - `Map` - `Set` - `Error` - `undefined` - `NaN`, `Infinity`, `-Infinity` Binary data is base64-encoded for compatibility with string-based storage adapters. ## Installation ```bash npm install @keyv/serialize-msgpackr ``` > **Note:** `keyv` is a peer dependency and must be installed alongside this package. ## Usage ```js import Keyv from 'keyv'; import { msgpackrSerializer } from '@keyv/serialize-msgpackr'; const keyv = new Keyv({ serialization: msgpackrSerializer }); // Store a Date — it comes back as a Date, not a string await keyv.set('date', new Date('2024-01-15')); const date = await keyv.get('date'); console.log(date instanceof Date); // true // Store a Map await keyv.set('map', new Map([['a', 1], ['b', 2]])); const map = await keyv.get('map'); console.log(map instanceof Map); // true console.log(map.get('a')); // 1 // Store a Set await keyv.set('set', new Set([1, 2, 3])); const set = await keyv.get('set'); console.log(set instanceof Set); // true ``` ## API ### `KeyvMsgpackrSerializer` A class that implements the `KeyvSerializationAdapter` interface from `keyv`. ```js import { KeyvMsgpackrSerializer } from '@keyv/serialize-msgpackr'; const serializer = new KeyvMsgpackrSerializer(); ``` #### `stringify(object: unknown): string` Serializes a value to a base64-encoded MessagePack string using msgpackr. #### `parse(data: string): T` Deserializes a base64-encoded MessagePack string back to its original value with all types restored. ### `msgpackrSerializer` A default `KeyvMsgpackrSerializer` instance, ready to use. ```js import { msgpackrSerializer } from '@keyv/serialize-msgpackr'; ``` ## License [MIT © Jared Wray](LICENSE) ### Compression URL: https://keyv.org/docs/compression/overview/ Description: Gzip, Brotli, and LZ4 compression adapters for Keyv. # Compression Compression runs on the **serialized string**, after JSON/SuperJSON/msgpackr and before optional encryption. ```js import Keyv from "keyv"; import KeyvGzip from "@keyv/compress-gzip"; const keyv = new Keyv({ compression: new KeyvGzip() }); ``` ## Official adapters | Package | Algorithm | | --- | --- | | [@keyv/compress-gzip](/docs/compression/compress-gzip/) | Gzip (pako) | | [@keyv/compress-brotli](/docs/compression/compress-brotli/) | Brotli | | [@keyv/compress-lz4](/docs/compression/compress-lz4/) | LZ4 | Pick gzip for portability, brotli for smaller payloads at higher CPU, lz4 when you want faster (de)compress. ## Custom adapter ```ts interface KeyvCompressionAdapter { compress(value: string): Promise; decompress(value: string): Promise; } ``` Test with `@keyv/test-suite`: ```js import { compressionTestSuite } from "@keyv/test-suite"; import { it } from "vitest"; import KeyvGzip from "@keyv/compress-gzip"; compressionTestSuite(it, new KeyvGzip()); ``` Serialization must stay enabled (the default). Disabling serialization bypasses compression regardless of the original value type. ### @keyv/compress-gzip URL: https://keyv.org/docs/compression/compress-gzip/ # @keyv/compress-gzip [keyv](https://github.com/jaredwray/keyv) > Gzip compression for Keyv [![build](https://github.com/jaredwray/keyv/actions/workflows/tests.yaml/badge.svg)](https://github.com/jaredwray/keyv/actions/workflows/tests.yaml) [![codecov](https://codecov.io/gh/jaredwray/keyv/branch/main/graph/badge.svg?token=bRzR3RyOXZ)](https://codecov.io/gh/jaredwray/keyv) [![npm](https://img.shields.io/npm/v/@keyv/compress-gzip.svg)](https://www.npmjs.com/package/@keyv/compress-gzip) [![npm](https://img.shields.io/npm/dm/@keyv/compress-gzip)](https://npmjs.com/package/@keyv/compress-gzip) Gzip compression for [Keyv](https://github.com/jaredwray/keyv). ## Install ```shell npm install --save keyv @keyv/compress-gzip ``` ## Usage ```javascript import Keyv from 'keyv'; import KeyvGzip from '@keyv/compress-gzip'; const keyv = new Keyv({store: new Map(), compression: new KeyvGzip()}); ``` ## API ### @keyv/compress-gzip(\[options]) #### options Options are [pako](https://github.com/nodeca/pako#readme) v3 options, such as `level`, `windowBits` or `dictionary`. The same object is passed to pako's `deflate` in `compress` and to its `inflate` in `decompress`. ```javascript const keyv = new Keyv({ compression: new KeyvGzip({ level: 9 }) }); ``` ## Migrating to v6 - `KeyvGzip` implements the v6 `KeyvCompressionAdapter` interface: `compress(value: string): Promise` and `decompress(value: string): Promise`. Keyv passes it the whole serialized entry, and `compress` returns a base64 string. - The v5 `serialize` and `deserialize` methods, the public `opts` property and the per-call `options` argument of `compress` and `decompress` were removed. Pass options to the constructor instead. - pako was upgraded from v2 to v3. The v2 `to: 'string'` option is no longer used; `decompress` always returns a string. - Values that Keyv v5 wrote with `@keyv/compress-gzip` can't be read by v6. v5 compressed only the `value` field inside the JSON envelope, so reading an old entry fails with `incorrect header check`. Keyv emits `error`, and `get` returns `undefined` when an `error` listener is attached or rejects when none is. Treat a compressed store as a cache that v6 repopulates, or read the old entries with v5 and write them again with v6. See the [v5 to v6 migration guide](https://keyv.org/docs/migration/v5-to-v6/#compression-adapter-interface-change). - Compression needs serialization, which is on by default. With `serialization: false`, Keyv stores values without compressing them. ## License [MIT © Jared Wray](LICENSE) ### @keyv/compress-brotli URL: https://keyv.org/docs/compression/compress-brotli/ # @keyv/compress-brotli [keyv](https://github.com/jaredwray/keyv) > Brotli compression for Keyv [![build](https://github.com/jaredwray/keyv/actions/workflows/tests.yaml/badge.svg)](https://github.com/jaredwray/keyv/actions/workflows/tests.yaml) [![codecov](https://codecov.io/gh/jaredwray/keyv/branch/main/graph/badge.svg?token=bRzR3RyOXZ)](https://codecov.io/gh/jaredwray/keyv) [![npm](https://img.shields.io/npm/v/@keyv/compress-brotli.svg)](https://www.npmjs.com/package/@keyv/compress-brotli) [![npm](https://img.shields.io/npm/dm/@keyv/compress-brotli)](https://npmjs.com/package/@keyv/compress-brotli) Brotli compression for [Keyv](https://github.com/jaredwray/keyv). Brotli is a data compression algorithm that is designed to be fast and efficient. ## Install ```shell npm install --save keyv @keyv/compress-brotli ``` ## Usage ```javascript import Keyv from 'keyv'; import KeyvBrotli from '@keyv/compress-brotli'; const keyv = new Keyv({store: new Map(), compression: new KeyvBrotli()}); ``` ## API ### @keyv/compress-brotli(\[options]) #### options `@keyv/compress-brotli` uses Node's built-in [`node:zlib`](https://nodejs.org/api/zlib.html) Brotli functions. Both options are optional: - `compressOptions` - [`BrotliOptions`](https://nodejs.org/api/zlib.html#class-brotlioptions) passed to `zlib.brotliCompress`. - `decompressOptions` - `BrotliOptions` passed to `zlib.brotliDecompress`. ```javascript import { constants } from 'node:zlib'; const brotli = new KeyvBrotli({ compressOptions: { params: { [constants.BROTLI_PARAM_QUALITY]: 5 } }, }); ``` ## Migrating to v6 - `KeyvBrotli` implements the v6 `KeyvCompressionAdapter` interface: `compress(value: string): Promise` and `decompress(value: string): Promise`. Keyv passes it the whole serialized entry, and `compress` returns a base64 string. - The v5 `serialize` and `deserialize` methods and the per-call `options` argument of `compress` and `decompress` were removed. Pass options to the constructor instead. - The [`compress-brotli`](https://github.com/Kikobeats/compress-brotli) dependency was dropped in favor of `node:zlib`. The only options are `compressOptions` and `decompressOptions`; the old `enable`, `serialize`, `deserialize` and `iltorb` options are gone. - Values that Keyv v5 wrote with `@keyv/compress-brotli` can't be read by v6. v5 compressed only the `value` field inside the JSON envelope, so reading an old entry fails with a decompression error. Keyv emits `error`, and `get` returns `undefined` when an `error` listener is attached or rejects when none is. Treat a compressed store as a cache that v6 repopulates, or read the old entries with v5 and write them again with v6. See the [v5 to v6 migration guide](https://keyv.org/docs/migration/v5-to-v6/#compression-adapter-interface-change). - Compression needs serialization, which is on by default. With `serialization: false`, Keyv stores values without compressing them. ## License [MIT © Jared Wray](LICENSE) ### @keyv/compress-lz4 URL: https://keyv.org/docs/compression/compress-lz4/ # @keyv/compress-lz4 [keyv](https://github.com/jaredwray/keyv) > lz4 compression for Keyv [![build](https://github.com/jaredwray/keyv/actions/workflows/tests.yaml/badge.svg)](https://github.com/jaredwray/keyv/actions/workflows/tests.yaml) [![codecov](https://codecov.io/gh/jaredwray/keyv/branch/main/graph/badge.svg?token=bRzR3RyOXZ)](https://codecov.io/gh/jaredwray/keyv) [![npm](https://img.shields.io/npm/v/@keyv/compress-lz4.svg)](https://www.npmjs.com/package/@keyv/compress-lz4) [![npm](https://img.shields.io/npm/dm/@keyv/compress-lz4)](https://npmjs.com/package/@keyv/compress-lz4) lz4 compression for [Keyv](https://github.com/jaredwray/keyv). `lz4` is a data compression algorithm that is designed to be fast and efficient and is provided by the package [lz4-napi](https://npmjs.com/package/lz4-napi). ## Install ```shell npm install --save keyv @keyv/compress-lz4 ``` ## Usage ```javascript import Keyv from 'keyv'; import KeyvLz4 from '@keyv/compress-lz4'; const keyv = new Keyv({store: new Map(), compression: new KeyvLz4()}); ``` ## API ### @keyv/compress-lz4(\[dictionary]) #### dictionary An optional string that [lz4-napi](https://npmjs.com/package/lz4-napi) uses as the dictionary for both compression and decompression. Use the same dictionary to read values that were written with it. ```javascript const keyv = new Keyv({ compression: new KeyvLz4('my-dictionary') }); ``` ## Migrating to v6 - `KeyvLz4` implements the v6 `KeyvCompressionAdapter` interface: `compress(value: string): Promise` and `decompress(value: string): Promise`. Keyv passes it the whole serialized entry, and `compress` returns a base64 string instead of a `Uint8Array`. - The v5 `serialize` and `deserialize` methods were removed. The constructor still takes an optional dictionary string. - Values that Keyv v5 wrote with `@keyv/compress-lz4` can't be read by v6. v5 compressed only the `value` field inside the JSON envelope, so an old entry doesn't decode. Keyv emits `error`, and `get` returns `undefined` when an `error` listener is attached or rejects when none is. Treat a compressed store as a cache that v6 repopulates, or read the old entries with v5 and write them again with v6. See the [v5 to v6 migration guide](https://keyv.org/docs/migration/v5-to-v6/#compression-adapter-interface-change). - Compression needs serialization, which is on by default. With `serialization: false`, Keyv stores values without compressing them. ## License [MIT © Jared Wray](LICENSE) ### Encryption URL: https://keyv.org/docs/encryption/overview/ Description: Encrypt values at rest with Node.js crypto or the Web Crypto API. # Encryption Encryption runs last on write (after serialize and optional compress) and first on read. It requires a serializer — the built-in JSON serializer is enough. With `serialization: false`, writes fail with an error instead of storing values unencrypted. ```js import Keyv from "keyv"; import KeyvEncryptNode from "@keyv/encrypt-node"; const keyv = new Keyv({ encryption: new KeyvEncryptNode({ key: process.env.KEYV_SECRET }), }); await keyv.set("secret", { token: "…" }); await keyv.get("secret"); // decrypted automatically ``` Use a random secret as the key, such as the output of `openssl rand -base64 32`, kept out of source control. Both adapters hash a string key once with SHA-256, with no salt or key stretching, so a password or passphrase can be guessed offline from a single stored value. You can also pass the raw key bytes (`Buffer` or `Uint8Array`) at the algorithm's key length. If the key has to come from a password or passphrase, derive those bytes with PBKDF2 first: the [encrypt-node](/docs/encryption/encrypt-node/) and [encrypt-web](/docs/encryption/encrypt-web/) pages show how. ## Official adapters | Package | Runtime | Default cipher | | --- | --- | --- | | [@keyv/encrypt-node](/docs/encryption/encrypt-node/) | Node.js `crypto` | AES-256-GCM (AES-CCM, ChaCha20-Poly1305) | | [@keyv/encrypt-web](/docs/encryption/encrypt-web/) | Web Crypto (`crypto.subtle`) | AES-256-GCM (AES-128-GCM, AES-192-GCM) | Use encrypt-web in browsers, Deno, and Cloudflare Workers. Use encrypt-node when you want Node-only ciphers. ## Custom adapter ```ts interface KeyvEncryptionAdapter { encrypt: (data: string) => string | Promise; decrypt: (data: string) => string | Promise; } ``` ```js const encryption = { encrypt: async (data) => Buffer.from(data).toString("base64"), decrypt: async (data) => Buffer.from(data, "base64").toString("utf8"), }; const keyv = new Keyv({ encryption }); ``` Detect adapters with `detectKeyvEncryption`. See [Encode and Decode](/docs/encode-and-decode/) and [Detect Capabilities](/docs/detect-capabilities/). ### @keyv/encrypt-node URL: https://keyv.org/docs/encryption/encrypt-node/ # @keyv/encrypt-node [keyv](https://github.com/jaredwray/keyv) > Node.js crypto encryption for Keyv [![build](https://github.com/jaredwray/keyv/actions/workflows/tests.yaml/badge.svg)](https://github.com/jaredwray/keyv/actions/workflows/tests.yaml) [![codecov](https://codecov.io/gh/jaredwray/keyv/branch/main/graph/badge.svg?token=bRzR3RyOXZ)](https://codecov.io/gh/jaredwray/keyv) [![npm](https://img.shields.io/npm/v/@keyv/encrypt-node.svg)](https://www.npmjs.com/package/@keyv/encrypt-node) [![npm](https://img.shields.io/npm/dm/@keyv/encrypt-node)](https://npmjs.com/package/@keyv/encrypt-node) Encrypt and decrypt values stored in [Keyv](https://github.com/jaredwray/keyv) using the Node.js `crypto` module. Supports the authenticated ciphers AES-GCM (default), AES-CCM, and ChaCha20-Poly1305, so a value changed in the store fails to decrypt instead of decrypting to altered data. ## Install ```shell npm install --save keyv @keyv/encrypt-node ``` ## Usage ```javascript import Keyv from 'keyv'; import KeyvEncryptNode from '@keyv/encrypt-node'; // A random secret, such as the output of `openssl rand -base64 32` (see options.key) const encryption = new KeyvEncryptNode({ key: process.env.KEYV_SECRET }); const keyv = new Keyv({ encryption }); await keyv.set('foo', 'bar'); const value = await keyv.get('foo'); // 'bar' (decrypted automatically) ``` Encryption runs on the serialized value, so it needs serialization, which is on by default. With `serialization: false`, Keyv doesn't store values unencrypted: writes fail, Keyv emits `error`, and `set()` returns `false` when a listener is attached or rejects when none is. ## API ### new KeyvEncryptNode(options) #### options.key Type: `string | Buffer`\ **Required** The encryption key. A string key is hashed once with SHA-256, with no salt or key stretching, and truncated to the length the algorithm needs. That's safe for a random secret but not for a password or passphrase: anyone who reads one stored value can test guesses offline at full speed. Use a random secret, such as the output of `openssl rand -base64 32`, and keep it out of source control. Buffer keys are used directly and must match the expected key length. To use a password or passphrase, derive the key with PBKDF2 first; see [Using a password or passphrase](#using-a-password-or-passphrase). #### options.algorithm Type: `NodeAlgorithm`\ Default: `'aes-256-gcm'` The cipher algorithm to use. Supported values, all authenticated (AEAD): - `aes-256-gcm`, `aes-192-gcm`, `aes-128-gcm` - `aes-256-ccm`, `aes-192-ccm`, `aes-128-ccm` - `chacha20-poly1305` Any other algorithm throws when the adapter is created. AES-CCM can't encrypt a serialized value of 16 MiB or more; writing one fails. #### options.encoding Type: `NodeEncoding`\ Default: `'base64'` The encoding used for the encrypted output string: `'base64'`, `'base64url'`, or `'hex'`. Other encodings can't hold arbitrary bytes, so they throw when the adapter is created. ## Using a password or passphrase If the key has to come from something a person chooses, derive the key bytes with PBKDF2 and pass those instead of the string. PBKDF2 repeats the hash many times, so every guess costs an attacker the same work: ```javascript import { pbkdf2Sync } from 'node:crypto'; import KeyvEncryptNode from '@keyv/encrypt-node'; // Derive the key once at startup: 600,000 iterations of PBKDF2-HMAC-SHA256 take on the order of 100 ms. // The salt is a random value you generate once (`openssl rand -base64 16`) and keep with your // configuration. It isn't secret, but reading values back needs the same passphrase and salt. const key = pbkdf2Sync(process.env.KEYV_PASSPHRASE, process.env.KEYV_SALT, 600_000, 32, 'sha256'); const encryption = new KeyvEncryptNode({ key }); ``` The key length must match the algorithm: 32 bytes for `aes-256-gcm`, `aes-256-ccm`, and `chacha20-poly1305`, 24 for the `aes-192` algorithms, and 16 for the `aes-128` ones. ## License [MIT © Jared Wray](LICENSE) ### @keyv/encrypt-web URL: https://keyv.org/docs/encryption/encrypt-web/ # @keyv/encrypt-web [keyv](https://github.com/jaredwray/keyv) > Web Crypto API encryption for Keyv [![build](https://github.com/jaredwray/keyv/actions/workflows/tests.yaml/badge.svg)](https://github.com/jaredwray/keyv/actions/workflows/tests.yaml) [![codecov](https://codecov.io/gh/jaredwray/keyv/branch/main/graph/badge.svg?token=bRzR3RyOXZ)](https://codecov.io/gh/jaredwray/keyv) [![npm](https://img.shields.io/npm/v/@keyv/encrypt-web.svg)](https://www.npmjs.com/package/@keyv/encrypt-web) [![npm](https://img.shields.io/npm/dm/@keyv/encrypt-web)](https://npmjs.com/package/@keyv/encrypt-web) Encrypt and decrypt values stored in [Keyv](https://github.com/jaredwray/keyv) using the Web Crypto API (`crypto.subtle`). Works in browsers, Deno, Cloudflare Workers, and Node.js 18+. No Node.js-specific dependencies. ## Install ```shell npm install --save keyv @keyv/encrypt-web ``` ## Usage ```javascript import Keyv from 'keyv'; import KeyvEncryptWeb from '@keyv/encrypt-web'; // Placeholder: use a random secret, such as the output of `openssl rand -base64 32` (see options.key), // loaded from your runtime's secrets (an environment variable, a Workers secret) rather than written here. const secret = 'replace-with-a-random-secret'; const encryption = new KeyvEncryptWeb({ key: secret }); const keyv = new Keyv({ encryption }); await keyv.set('foo', 'bar'); const value = await keyv.get('foo'); // 'bar' (decrypted automatically) ``` Encryption runs on the serialized value, so it needs serialization, which is on by default. With `serialization: false`, Keyv doesn't store values unencrypted: writes fail, Keyv emits `error`, and `set()` returns `false` when a listener is attached or rejects when none is. ## API ### new KeyvEncryptWeb(options) #### options.key Type: `string | Uint8Array`\ **Required** The encryption key. A string key is hashed once with SHA-256, with no salt or key stretching, and truncated to the length the algorithm needs. That's safe for a random secret but not for a password or passphrase: anyone who reads one stored value can test guesses offline at full speed. Use a random secret, such as the output of `openssl rand -base64 32`, and keep it out of source control. Uint8Array keys are used directly and must match the expected key length. To use a password or passphrase, derive the key with PBKDF2 first; see [Using a password or passphrase](#using-a-password-or-passphrase). #### options.algorithm Type: `WebAlgorithm`\ Default: `'aes-256-gcm'` The cipher algorithm to use. Supported values, all AES-GCM, which is authenticated (AEAD): - `aes-256-gcm`, `aes-192-gcm`, `aes-128-gcm` Any other algorithm throws when the adapter is created. ## Using a password or passphrase If the key has to come from something a person chooses, derive the key bytes with PBKDF2 and pass those instead of the string. PBKDF2 repeats the hash many times, so every guess costs an attacker the same work: ```javascript import KeyvEncryptWeb from '@keyv/encrypt-web'; // Placeholders: load the passphrase from your runtime's secrets. The salt is a random value you // generate once (`openssl rand -base64 16`) and keep with your configuration. It isn't secret, but // reading values back needs the same passphrase and salt. const passphrase = 'replace-with-your-passphrase'; const salt = 'replace-with-your-salt'; // Derive the key once at startup: 600,000 iterations of PBKDF2-HMAC-SHA256 take on the order of 100 ms. const encoder = new TextEncoder(); const passphraseKey = await crypto.subtle.importKey('raw', encoder.encode(passphrase), 'PBKDF2', false, ['deriveBits']); const bits = await crypto.subtle.deriveBits( { name: 'PBKDF2', hash: 'SHA-256', salt: encoder.encode(salt), iterations: 600_000 }, passphraseKey, 256, ); const encryption = new KeyvEncryptWeb({ key: new Uint8Array(bits) }); ``` Derive 256 bits for `aes-256-gcm`, 192 for `aes-192-gcm`, and 128 for `aes-128-gcm`. ## License [MIT © Jared Wray](LICENSE) ### AI Agent Skill URL: https://keyv.org/docs/migration/ai-agent-skill/ Description: Upgrade from Keyv v4 or v5 to v6 with a coding agent. Point it at https://keyv.org/skills/migrate, or install the keyv-migrate Agent Skill. # Migrate with an AI Agent Keyv has an [Agent Skill](https://agentskills.io) that walks a coding agent through an upgrade from Keyv v4 or v5 to v6. It covers the same ground as the [v4 to v5](/docs/migration/v4-to-v5/) and [v5 to v6](/docs/migration/v5-to-v6/) guides, written as steps an agent can follow. It works with Claude Code, Cursor, Codex, GitHub Copilot, and other agents that follow Markdown instructions. ## Point your agent at the skill You don't have to install anything. Give your agent this prompt: > Upgrade this project to Keyv v6 using the skill at https://keyv.org/skills/migrate. Fetch it with `curl -sL https://keyv.org/skills/migrate` and follow it. `https://keyv.org/skills/migrate` returns the skill's `SKILL.md` as plain Markdown. The skill links to reference files and lists their full URLs, so an agent reading it over the web can fetch those too. Asking for `curl` helps with agents whose web tools summarize a page instead of returning it as written. ## Install the skill When the skill is installed, your agent can load it on its own whenever you ask for a Keyv upgrade, and the reference files are on disk. With the [`skills` CLI](https://github.com/vercel-labs/skills), which installs skills for Claude Code, Cursor, Codex, GitHub Copilot, and many other agents: ```bash npx skills add https://keyv.org # or from GitHub npx skills add jaredwray/keyv --skill keyv-migrate ``` Or copy the [`skills/keyv-migrate`](https://github.com/jaredwray/keyv/tree/main/skills/keyv-migrate) folder into your agent's skills folder, such as `.claude/skills/` for Claude Code. Then ask: *"Upgrade this project to Keyv v6."* ## What the skill does 1. **Takes inventory.** It finds every package that uses Keyv and the versions in use, every Keyv instance and its store, custom storage adapters, and libraries such as `cache-manager` that still depend on Keyv v5. 2. **Decides what happens to stored data.** v6 removed the default `keyv` namespace, so data written by v4 or v5 reads as missing unless you use the right settings. The skill works out those settings for each adapter, or confirms with you that the data is a cache that can be rebuilt. 3. **Upgrades dependencies.** It pins `keyv` and every `@keyv/*` package to the same v6 version and removes the packages v6 dropped. 4. **Rewrites the code.** Connection strings, `opts`, serialization options, hooks, error handling, raw reads, return values, the iterator, and custom storage adapters. 5. **Verifies.** It runs your typecheck, lint, and tests, and searches again for code that compiles but behaves differently in v6. 6. **Reports.** It lists what changed, the decision for each store, and the steps left for you. ## What it won't do without asking - Run a migration script or change stored data. It proposes the command and asks you to back up first. SQLite converts its table the first time v6 connects, so the skill also won't point v6 at a real SQLite database on its own. - Change your Node.js version, your CI configuration, or unrelated dependencies. - Force Keyv v6 onto a library that depends on v5. ## Links - Skill source: [skills/keyv-migrate](https://github.com/jaredwray/keyv/tree/main/skills/keyv-migrate) on GitHub - Raw files: [SKILL.md](https://keyv.org/skills/keyv-migrate/SKILL.md) and the [discovery index](https://keyv.org/.well-known/skills/index.json) - The Agent Skills format: [agentskills.io](https://agentskills.io) ### v4 to v5 Migration URL: https://keyv.org/docs/migration/v4-to-v5/ # v4 to v5 Migration Keyv v5 is a major release with breaking changes. The biggest one is that Keyv no longer loads storage adapters from a connection string. This page covers what changed from v4 to v5. **Still on v4? Go straight to v6.** Apply this page, then the [v5 to v6 guide](/docs/migration/v5-to-v6/). See [Going Straight from v4 to v6](#going-straight-from-v4-to-v6) for the parts that differ for v4 data. > **Using an AI coding agent?** Tell it: *"Upgrade this project to Keyv v6 using https://keyv.org/skills/migrate"*. The skill handles v4 projects too. See [Migrate with an AI Agent](/docs/migration/ai-agent-skill/). ## Pass a Storage Adapter Instead of a Connection String ### Before with v4 ```js import Keyv from 'keyv'; import KeyvRedis from '@keyv/redis'; const keyv = new Keyv('redis://user:pass@localhost:6379'); ``` v4 read the scheme from the string, or from the `adapter` option, and loaded the matching `@keyv/*` package for you. Now you pass the store either directly to the constructor, as below, or in the `store` option. The constructor takes the storage adapter or the options as the first parameter. **Watch out:** v5 and v6 don't reject a connection string. `new Keyv('redis://...')` and `new Keyv({ uri: 'redis://...' })` silently fall back to an in-memory store, and TypeScript accepts both forms. Search your code for every place that builds a Keyv from a string. ### Now with v5 ```js import Keyv from 'keyv'; import KeyvRedis from '@keyv/redis'; const keyv = new Keyv(new KeyvRedis('redis://user:pass@localhost:6379')); ``` ## An example with options When passing in options you can do the following using the `store` parameter: ```js import Keyv from 'keyv'; import KeyvRedis from '@keyv/redis'; const keyv = new Keyv(new KeyvRedis('redis://user:pass@localhost:6379',{ namespace: 'my-namespace' })); ``` v4 also passed any extra Keyv options through to the adapter, as in `new Keyv({ uri: 'sqlite://cache.sqlite', table: 'cache' })`. Give adapter options to the adapter instead: ```js import Keyv from 'keyv'; import KeyvSqlite from '@keyv/sqlite'; const keyv = new Keyv(new KeyvSqlite({ uri: 'sqlite://cache.sqlite', table: 'cache' })); ``` ## CommonJS Imports Changed v4 exported the class as the module itself (`module.exports = Keyv`). From v5 on, `keyv` exports `Keyv` as a named export and as `default`, so the v4 form fails with `Keyv is not a constructor`: ```js // v4 const Keyv = require('keyv'); // v5 and later const { Keyv } = require('keyv'); // or const Keyv = require('keyv').default; ``` Adapters changed the same way. In v6 most adapters also export their class by name, such as `const { KeyvSqlite } = require('@keyv/sqlite')`. `@keyv/redis` has only a default export, so use `const KeyvRedis = require('@keyv/redis').default`. ## `@keyv/offline` and `@keyv/tiered` Were Removed `@keyv/offline` and `@keyv/tiered` are gone, along with the `offline:` and `tiered:` connection strings. For a fast in-memory layer in front of a remote store, or for offline fallbacks, use [Cacheable](https://cacheable.org). ## `@keyv/redis` Uses the Official Redis Client The v4-era `@keyv/redis` 2.x was built on `ioredis`. Since Keyv v5, `@keyv/redis` uses the official `redis` client (`@redis/client`). You can't pass an `ioredis` instance or `ioredis`-only options anymore. Pass a connection string or `redis` client options, or create a client with the `createClient`, `createCluster`, or `createSentinel` functions that `@keyv/redis` exports. See [@keyv/redis](/docs/storage-adapters/redis/). ## Other Changes - **TypeScript and ESM.** v5 is written in TypeScript and ships ESM and CommonJS builds with its own types. v4's `Keyv` type took an options parameter; v5 and v6 take only the value type, as in `Keyv`. - **Return values.** v4's `set` always resolved `true`. Now a failed write is reported; v6 [returns `false` or rejects](/docs/migration/v5-to-v6/#error-handling-changed-and-throwonerrors-was-removed) depending on whether an `error` listener is attached. `has` also accepts an array of keys, and `hasMany` was added. v4's `delete([...])` with an array resolved one boolean: with a `Map`, Memcache, or Etcd it was `true` only when every key was deleted, and with SQLite, PostgreSQL, MySQL, or MongoDB when any key was. With Redis it depended on the `@keyv/redis` version: 2.7 through 3.0 meant every key, and earlier and later versions any key. v6 returns one boolean per key. - **Raw values.** v4 stored `expires: null` for entries without a TTL. v5 and v6 leave `expires` out, so check `expires === undefined` rather than `=== null`. - **Serialization.** v4 serialized with `json-buffer`. v5 used `@keyv/serialize`, and v6 has a built-in serializer. All three write the same format, so data v4 wrote without compression can still be read. - **Compression.** In v4, a compression adapter replaced `serialize` and `deserialize` entirely. v6 can't read values that v4 compressed. - **Events.** v4 extended Node.js's `EventEmitter`. v5 has its own event emitter, and v6 uses [Hookified](https://hookified.org). In v4, `emitErrors` could only be set in the constructor; v6 removed it. - **Errors.** In v4, a call rejected whenever the store failed, even with an `error` listener attached; the listener only received errors the store emitted on its own, such as a dropped connection. In v6, attaching a listener makes failed calls return fallback values instead of rejecting. A v4 app that added `keyv.on('error', ...)` for connection errors, and still relies on calls rejecting, changes behavior silently. See [Error Handling Changed](/docs/migration/v5-to-v6/#error-handling-changed-and-throwonerrors-was-removed). - **Iterator.** v4 attached `iterator` only for a `Map` and some adapters, and you passed it the namespace: `keyv.iterator(keyv.opts.namespace)`. In v6, `keyv.iterator()` always exists and takes no arguments. ## Removing support for Nodejs 18 and below We have stopped testing on Nodejs 18 and below and while we do not force or require you to use Nodejs 20+ we do recommend it. Keyv v6 requires Node.js 22.19 or later. ## Going Straight from v4 to v6 Apply this page first, then the [v5 to v6 guide](/docs/migration/v5-to-v6/). Most of that guide applies to v4 projects as written, including the table for [keeping existing data readable](/docs/migration/v5-to-v6/#the-default-keyv-namespace-was-removed). v4 stored keys the same way v5 did for SQLite, PostgreSQL, MySQL, MongoDB, Etcd, and Memcache, so use the "default" rows of that table. Redis is different. `@keyv/redis` 2.x, the version used with Keyv v4, stored Keyv's key without adding a prefix of its own. In this table, `ns` is the namespace your v4 instance used, which is `keyv` unless you set one: | v4 setup | Key v4 stored for `foo` | v6 setting that reads it | | --- | --- | --- | | default | `ns:foo` | `namespace: 'ns'` with `new KeyvRedis(uri, { keyPrefixSeparator: ':' })` | | `useRedisSets: false` | `sets:namespace:ns:ns:foo` | `namespace: 'sets:namespace:ns:ns'` with `new KeyvRedis(uri, { keyPrefixSeparator: ':' })` | v4's Redis adapter also kept a Redis set named `namespace:ns` that listed its keys. v6 doesn't use it, so you can delete it once nothing runs v4. Values that v4 wrote with compression can't be read by v6. Treat them as a cache to repopulate. # New Features Here are a list of new features in Keyv v5: - **Typescript Support**: Keyv v5 is written in Typescript and has full typescript support. - **ESM Support**: Keyv v5 is written in ESM and has full ESM support. - **Event Emitter**: Keyv v5 is now an event emitter and emits events for `set`, `delete`, `clear`, and `error` with no reliance on third party libraries. - **Built in Statistics**: Keyv v5 has built in statistics for `hits`, `misses`, `sets`, `deletes`, and `errors`. - **Hooks**: Keyv v5 has hooks for pre and post processing on `set()`, `get()`, `getMany()`, and `delete()`. You can learn about any of these features in the Keyv API documentation. ### v5 to v6 Migration URL: https://keyv.org/docs/migration/v5-to-v6/ # Keyv v6 We are pleased to announce Keyv v6 with major enhancements and some breaking changes. This guide will help you understand how to migrate from v5 to v6. For most users, the transition will be straightforward. **Important:** With the release of v6, Keyv v5 is in maintenance mode. v5 only receives security fixes and minor maintenance updates. The previous documentation site is archived at [keyv.org/v5](/v5/). The `v5` branch remains in the monorepo. > **Using an AI coding agent?** Tell it: *"Upgrade this project to Keyv v6 using https://keyv.org/skills/migrate"*. The skill covers everything on this page and asks before it touches stored data. See [Migrate with an AI Agent](/docs/migration/ai-agent-skill/). ## Table of Contents - [Roadmap & Progress](#roadmap--progress) - [Quick Migration Guide](#quick-migration-guide) - [Breaking Changes](#breaking-changes) - [Node.js 22.19 or Later Is Required](#nodejs-2219-or-later-is-required) - [Namespace Overhaul](#namespace-overhaul) - [The Default `keyv` Namespace Was Removed](#the-default-keyv-namespace-was-removed) - [`clear()` Without a Namespace Clears More](#clear-without-a-namespace-clears-more) - [A Namespaced `clear()` Fails When the Store Can't List Its Keys](#a-namespaced-clear-fails-when-the-store-cant-list-its-keys) - [`opts` Property Removed](#opts-property-removed) - [Serialization Replaces `serialize` and `deserialize`](#serialization-replaces-serialize-and-deserialize) - [Hookified for Events and Hooks](#hookified-for-events-and-hooks) - [Error Handling Changed and `throwOnErrors` Was Removed](#error-handling-changed-and-throwonerrors-was-removed) - [`deleteMany` Returns `boolean[]`](#deletemany-returns-boolean) - [`setMany` Uses `KeyvEntry[]` and Returns `boolean[]`](#setmany-uses-keyventry-and-returns-boolean) - [`get` and `getMany` No Longer Support Raw](#get-and-getmany-no-longer-support-raw) - [Iterator Changes](#iterator-changes) - [Removed `.ttlSupport` from Storage Adapters](#removed-ttlsupport-from-storage-adapters) - [Storage Adapters Receive Absolute `expires` Instead of Relative `ttl`](#storage-adapters-receive-absolute-expires-instead-of-relative-ttl) - [Returns `undefined` Instead of `null`](#returns-undefined-instead-of-null) - [Compression Adapter Interface Change](#compression-adapter-interface-change) - [Other Silent Behavior Changes](#other-silent-behavior-changes) - [`@keyv/test-suite` API Changes](#keyvtest-suite-api-changes) - [Libraries That Embed Keyv v5](#libraries-that-embed-keyv-v5) - [`@keyv/memcache` Moves from `memjs` to `memcache`](#keyvmemcache-moves-from-memjs-to-memcache) - [`@keyv/memcache` `clear()` Only Removes the Store's Own Entries](#keyvmemcache-clear-only-removes-the-stores-own-entries) - [`@keyv/etcd` Default `ttl` Applies Per Key](#keyvetcd-default-ttl-applies-per-key) - [`@keyv/etcd` Without a Namespace Only Clears Its Own Entries](#keyvetcd-without-a-namespace-only-clears-its-own-entries) - [`@keyv/dynamo` Keys Without a TTL No Longer Expire](#keyvdynamo-keys-without-a-ttl-no-longer-expire) - [`@keyv/bigmap` Keeps Entries When `storeSize` or `storeHashFunction` Changes](#keyvbigmap-keeps-entries-when-storesize-or-storehashfunction-changes) - [`@keyv/redis` `keyPrefixSeparator` Is Now `namespaceSeparator`](#keyvredis-keyprefixseparator-is-now-namespaceseparator) - [`@keyv/redis` Matches the Namespace Literally](#keyvredis-matches-the-namespace-literally) - [New Features](#new-features) - [Keyv v6 Versioning](#keyv-v6-versioning) - [Keyv v5 Maintenance Mode](#keyv-v5-maintenance-mode) - [Browser Compatibility](#browser-compatibility) - [Serialization Adapters](#serialization-adapters) - [Encryption Adapters](#encryption-adapters) - [New Identification Functions](#new-identification-functions) - [Memory Adapter](#memory-adapter) --- ## Roadmap & Progress | Task | Status | |------|--------| | Remove `opts` property in Keyv and Storage Adapters | COMPLETED | | Add encryption adapters | COMPLETED | | Browser compatibility | COMPLETED | | Stats System to be Event Driven | COMPLETED | | Test Suite Overhaul | COMPLETED | | Refactor iterator implementation | COMPLETED | | Update `deleteMany` return type | COMPLETED | | Update `setMany` signature and return type | COMPLETED | | Add compression interface standardization | COMPLETED | | Integrate Hookified library in Keyv | COMPLETE | | Keyv core does not do keyPrefixing | COMPLETED | | Update `@keyv/sqlite` | COMPLETE | | Update `@keyv/dynamo` | COMPLETE | | Update `@keyv/etcd` | COMPLETE | | Update `@keyv/valkey` | COMPLETE | | Finalize namespace handling in storage adapters | COMPLETE | | Add `getRaw` and `getManyRaw` methods | COMPLETE | | Implement `KeyvMemoryAdapter` | COMPLETE | | Add serialization adapters | COMPLETE | | Migrate `@keyv/memcache` from `memjs` to `memcache` | COMPLETE | | Update `@keyv/bigmap` | COMPLETE | | Update `@keyv/mongo` | COMPLETE | | Update `@keyv/mysql` | COMPLETE | | Update `@keyv/postgres` | COMPLETE | | Update `@keyv/redis` | COMPLETE | | Add GitHub Actions release workflow | COMPLETE | | Storage adapters receive absolute `expires` instead of relative `ttl` | COMPLETE | --- ## Quick Migration Guide For most users, migrating from v5 to v6 involves a few key changes: 1. **Upgrade Node.js and pin one version** - v6 requires Node.js 22.19 or later. Install `keyv` and every `@keyv/*` package at the same exact v6 version; see [Versioning & Release Tags](/docs/migration/versioning/). 2. **Keep reading data written by v5** - v5 stored keys under a default `keyv` namespace, and v6 has no default. Without `namespace: 'keyv'`, or the namespace you already used, data written by v5 reads as missing. Redis, Valkey, Etcd, DynamoDB, and MongoDB need more than that; see [The Default `keyv` Namespace Was Removed](#the-default-keyv-namespace-was-removed). v6 can't read Memcache entries v5 wrote, so a Memcache cache fills again. SQLite converts its table the first time v6 connects, and PostgreSQL, MySQL, and MongoDB have migration scripts. These changes are one-way, so back up first. 3. **Update property access** - The `opts` property has been removed. Use direct property access instead (`keyv.namespace` instead of the old `keyv.opts.namespace`) 4. **Update serialization** - Replace `serialize`/`deserialize` options with the `serialization` adapter. v6 ships a built-in `KeyvJsonSerializer` (no extra package). For SuperJSON or MessagePack, install those packages: ```javascript // v5 const keyv = new Keyv({ serialize: JSON.stringify, deserialize: JSON.parse }); // v6 (default JSON serializer — Buffer + BigInt) const keyv = new Keyv(); // v6 custom import { superJsonSerializer } from '@keyv/serialize-superjson'; const keyv = new Keyv({ serialization: superJsonSerializer }); ``` 5. **Update raw value access** - Replace `get(key, { raw: true })` with `getRaw(key)` and `getMany(keys, { raw: true })` with `getManyRaw(keys)` 6. **Handle new return types** - `deleteMany` and `setMany` now return `boolean[]` instead of a single `boolean` 7. **Attach an `error` listener** - A failed operation now rejects unless an `error` listener is attached, and the `throwOnErrors` option was removed. To get failures back as fallback values, as many v5 methods returned them, add `keyv.on('error', ...)`. See [Error Handling Changed and `throwOnErrors` Was Removed](#error-handling-changed-and-throwonerrors-was-removed). 8. **Check compressed data and libraries built on Keyv v5** - Values that v5 wrote with compression can't be read by v6. Libraries such as `cache-manager` and `cacheable` depend on Keyv v5, so don't hand them a v6 `Keyv` or v6 adapters until they support v6. See [Compression Adapter Interface Change](#compression-adapter-interface-change) and [Libraries That Embed Keyv v5](#libraries-that-embed-keyv-v5). Many v6 changes don't fail at compile time. In plain JavaScript, removed options are ignored, and `new Keyv('redis://...')` quietly uses an in-memory store. Read [Other Silent Behavior Changes](#other-silent-behavior-changes) before you ship. For detailed information on each change, see the sections below. --- ## Breaking Changes ### Node.js 22.19 or Later Is Required Every v6 package declares `"engines": { "node": ">= 22.19.0" }`. v5 had no Node.js floor for `keyv` itself, and most v5 adapters accepted Node.js 18. Update your runtime, your CI matrix, and any `engines`, `.nvmrc`, or Docker base image that pins an older version. See [Browser, Node.js, and Bun](/docs/browser-node-and-bun/) for other runtimes. --- ### Namespace Overhaul We have finalized the transition (started in v5) to move all namespace handling to the storage adapters themselves. When you set the namespace on Keyv, it passes it directly to the storage adapter. **What changed:** - The `useKeyPrefix` option and property have been removed - Key prefixing is no longer done at the Keyv layer - A namespace set on the storage adapter is kept when Keyv has none. v5 replaced it with Keyv's namespace, `keyv` by default. A namespace passed to Keyv still wins. - Adapters that join the namespace and key into one string, including the memory and bridge adapters, put `::` between them by default. v5's Keyv used `:`. Every such adapter takes a `namespaceSeparator` option to change it; see [The Default `keyv` Namespace Was Removed](#the-default-keyv-namespace-was-removed) for reading keys v5 wrote. **v5 (before):** ```javascript import Keyv from 'keyv'; const keyv = new Keyv({ namespace: 'myapp', useKeyPrefix: true }); ``` **v6 (after):** ```javascript import Keyv from 'keyv'; const keyv = new Keyv({ namespace: 'myapp' }); // Namespace is handled directly by the storage adapter ``` For legacy storage adapters or `Map`-compatible stores, we have added `KeyvMemoryAdapter` which handles advanced features without overloading the main Keyv codebase. See [Memory Adapter](#memory-adapter) for more details. --- ### The Default `keyv` Namespace Was Removed In v5, a Keyv instance created without a `namespace` used the namespace `keyv`, and Keyv prefixed every key with it. `keyv.set('foo', 'bar')` handed the storage adapter the key `keyv:foo`. v6 has no default namespace and never prefixes keys, so after upgrading, `keyv.get('foo')` looks for `foo` and data written by a default v5 setup reads as missing. The v5 entries are still in your store. v6 just no longer looks for them. To keep reading v5 data, configure v6 to build the same storage keys v5 did. That starts with the namespace v5 used, which is `keyv` if you never set one: ```javascript // v5: no namespace set, so `foo` was stored as `keyv:foo` const keyv = new Keyv(store); // v6: read the same keys const keyv = new Keyv(store, { namespace: 'keyv' }); ``` Adapters that join the namespace and key into one string, such as Etcd and DynamoDB, also need v5's separator. v5 joined them with `:`, and v6 adapters use `::` by default, so set the adapter's `namespaceSeparator` option as the table shows. If your v5 code passed a namespace to Keyv, use that value instead of `keyv`. Pass it in Keyv's options as shown, where it takes precedence over any namespace on the adapter. v5 replaced a namespace set on the adapter with Keyv's, so the adapter's namespace was never the one v5 used. Some v5 adapters added their own prefix on top of Keyv's, and some v5 `createKeyv` helpers turned Keyv's prefix off, so the stored key depends on the adapter and how you created it. In this table, `ns` is the namespace your v5 instance used, which is `keyv` unless you set one. "Default" means `new Keyv(store)` or `new Keyv(store, { namespace })`. | Adapter | v5 setup | Key v5 stored for `foo` | v6 setting that reads it | | --- | --- | --- | --- | | SQLite, PostgreSQL, MySQL | default | `ns:foo` | Migrate the table, then `namespace: 'ns'`. SQLite migrates on connect. PostgreSQL and MySQL need their migration script. | | Etcd | default | `ns:foo` | `namespace: 'ns'` with `new KeyvEtcd(uri, { namespaceSeparator: ':' })` | | DynamoDB | default | `ns:foo` | `namespace: 'ns'` with `new KeyvDynamo({ namespaceSeparator: ':' })` | | DynamoDB | `createKeyv()` | `foo` | No namespace | | Redis | default | `ns::ns:foo` | `namespace: 'ns'` with `new KeyvRedis(uri, { namespaceSeparator: '::ns:' })` | | Redis | `useKeyPrefix: false`, or `createKeyv()` with a namespace | `ns::foo` | `namespace: 'ns'` | | Redis | `createKeyv()` without a namespace | `foo` | No namespace | | Memcache | any | `ns:ns:foo`, or `ns:foo` with `useKeyPrefix: false` | None. v6 stores each value after a generation token and reads a value without one as missing, so let the cache fill again. See [below](#keyvmemcache-clear-only-removes-the-stores-own-entries). | | Valkey | default, or `createKeyv()` | `ns:foo` | None. v6 cannot build this key, so let the entries repopulate or rename them to the v6 layout. | | Valkey | `useRedisSets: false` | `namespace:ns:ns:foo` | `namespace: 'ns:ns'` with `new KeyvValkey(uri, { namespaceSeparator: ':' })` | | MongoDB | default | `ns:foo`, with no `namespace` field | Run the `@keyv/mongo` migration script, then `namespace: 'ns'`. | With `useKeyPrefix: false`, the SQL, Etcd, DynamoDB, and MongoDB adapters stored plain `foo`. v6 reads it with no namespace, after the table or collection migration where the adapter has one. If you are unsure which layout you have, look at one key in your store and choose the v6 settings that produce the same string. v6 builds storage keys like this: - **SQLite, PostgreSQL, MySQL:** a `namespace` column and a key column. - **MongoDB:** a `namespace` field and a `key` field, or `metadata.namespace` and `filename` with GridFS. - **Etcd, DynamoDB, Memcache, Redis:** ``, where the separator defaults to `::`. - **Valkey:** `namespace:`, or `sets:` with `useSets: true`, where the separator defaults to `::`. If the data is a cache you can rebuild, you can skip all of this. The v5 entries stay in the store until they expire or you remove them. On a shared backend, keep a namespace anyway; see [`clear()` Without a Namespace Clears More](#clear-without-a-namespace-clears-more). **Before you migrate a table or collection:** - **Back up first.** The SQLite conversion and the PostgreSQL, MySQL, and MongoDB migration scripts rewrite your data in place. None of them can be undone. - **SQLite converts as soon as the adapter is created.** `new KeyvSqlite(...)` opens the database and rebuilds a v5 table right away, before any read. Importing a module that creates one is enough, and so is a test run or a one-off script. Copy the database file before you point v6 at it. - **Stop v5 writers.** v5 and v6 can't share a store. Don't run a rolling deploy where v5 and v6 instances write to the same database at the same time. - **Keep `checkExpired` on for converted SQLite rows.** The conversion moves each row's namespace into its own column but doesn't fill the new `expires` column. Converted rows still expire, because Keyv reads the expiry stored inside each value (`checkExpired` defaults to `true`). With `checkExpired: false`, converted rows that had a TTL never expire, and `clearExpired()` skips them until they are written again. --- ### `clear()` Without a Namespace Clears More In v5 every Keyv instance had a namespace, `keyv` by default, so `clear()` removed only the keys that Keyv wrote. In v6 an instance with no namespace calls the adapter's `clear()` with no namespace, and some adapters then remove much more: | Adapter | `clear()` with no namespace | | --- | --- | | Redis | Deletes every string key whose name doesn't contain the separator (`::` by default). With `noNamespaceAffectsAll: true`, runs `FLUSHDB`. | | Valkey | Deletes every key in the database. | | Etcd | Deletes only the entries v6 wrote with no namespace, and leaves v5's entries. With `noNamespaceAffectsAll: true`, deletes every key. See [below](#keyvetcd-without-a-namespace-only-clears-its-own-entries). | | DynamoDB | Deletes every item in the table. | | Cloudflare KV | Deletes every key in the KV namespace. | | Memcache | Removes only the entries v6 wrote with no namespace. With `noNamespaceAffectsAll: true`, flushes the whole server, as v5 did with or without a namespace. See [below](#keyvmemcache-clear-only-removes-the-stores-own-entries). | | SQLite, PostgreSQL, MySQL, MongoDB | Deletes only the rows or documents that have no namespace. | If other data or other apps share the backend, set a namespace on every Keyv instance that calls `clear()`. --- ### A Namespaced `clear()` Fails When the Store Can't List Its Keys In v5, `clear()` called the store's own `clear()`. With a `Map`, another `Map`-like store, or an adapter that doesn't manage namespaces, that deleted every entry, whatever the namespace. In v6, Keyv wraps such a store in `KeyvMemoryAdapter` or `KeyvBridgeAdapter`, which prefix its keys with the namespace, and a namespaced `clear()` deletes only that namespace's entries. To find them it needs the store's `keys()` (a synchronous `Map`-like store) or `iterator()` (an async one). A store without them can't tell namespaces apart, so `clear()` deletes nothing and fails: Keyv emits `error`, and with no `error` listener attached the call rejects. **What this means for you:** - A `Map`, `quick-lru`, `lru.min`, every v6 adapter, and older adapters that manage their own namespace aren't affected - For any other custom store, add `keys()` (synchronous) or `iterator()` (async), or move it to the v6 adapter contract - To empty such a store on purpose, as v5 did, call `clear()` on a Keyv instance without a namespace --- ### `opts` Property Removed In Keyv v5, we began removing `opts` as a passed-around value. In v6, `opts` has been removed from the Keyv class and from the `KeyvStorageAdapter` interface. The `dialect` property has also been removed. Settings are now properties on the Keyv class and on each storage adapter. `@keyv/sqlite` still has a deprecated `opts` getter for backward compatibility; don't write new code against it. **v5 (before):** ```javascript const keyv = new Keyv(); console.log(keyv.opts.namespace); ``` **v6 (after):** ```javascript const keyv = new Keyv(); console.log(keyv.namespace); ``` --- ### Serialization Replaces `serialize` and `deserialize` The `serialize` and `deserialize` options have been replaced with the `serialization` option. It takes a serialization adapter: an object with `stringify` and `parse` methods. A v5 `serialize` function becomes `stringify`, and `deserialize` becomes `parse`. Both still work on the `{ value, expires }` envelope. To turn serialization off, as v5 did with `keyv.serialize = undefined`, pass `serialization: false`. In plain JavaScript, v6 ignores `serialize` and `deserialize`, so custom functions silently stop running and values are written as JSON. The built-in `KeyvJsonSerializer` writes the same format as v5's `@keyv/serialize` and v4's `json-buffer`, so the switch itself doesn't require rewriting stored data. The `@keyv/serialize` package is not part of v6; remove it from your dependencies. **v5 (before):** ```javascript import Keyv from 'keyv'; const keyv = new Keyv({ serialize: JSON.stringify, deserialize: JSON.parse }); ``` **v6 (after):** ```javascript import Keyv from 'keyv'; const keyv = new Keyv(); // KeyvJsonSerializer is the default // or import { superJsonSerializer } from '@keyv/serialize-superjson'; const keyv = new Keyv({ serialization: superJsonSerializer }); // or keep your own functions const keyv = new Keyv({ serialization: { stringify: mySerialize, parse: myDeserialize } }); ``` See [Serialization Adapters](#serialization-adapters) for more details. --- ### Hookified for Events and Hooks Keyv now extends [Hookified](https://hookified.org) directly, replacing the custom `EventManager` and `HooksManager` classes. This unifies the event/hook system across Keyv and all storage adapters. **Breaking Changes:** - `keyv.hooks.addHandler(event, fn)` is replaced by `keyv.onHook(event, fn)` or its alias `keyv.addHook(event, fn)` - `keyv.hooks.removeHandler(event, fn)` is replaced by `keyv.removeHook({ event, handler: fn })` - `keyv.hooks.handlers` is replaced by `keyv.hooks` (a `Map`) - Hook names changed from `pre`/`post` to `before:`/`after:` convention - Hook payloads carry the key you passed (`foo`). v5 passed the prefixed key (`keyv:foo`), so code that stripped the prefix must stop - Hooks are awaited, so a slow async hook delays the operation it belongs to - A hook that throws now emits `error` on Keyv, so the call rejects when no `error` listener is attached. v5 emitted it on `keyv.hooks`, where it was usually ignored - The `emitErrors` option has been removed - Error handling changed, and the `throwOnErrors` option was removed. See [Error Handling Changed and `throwOnErrors` Was Removed](#error-handling-changed-and-throwonerrors-was-removed). **Hook Name Migration:** | v5 Hook | v6 Hook | |---------|---------| | `KeyvHooks.PRE_SET` (`"preSet"`) | `KeyvHooks.BEFORE_SET` (`"before:set"`) | | `KeyvHooks.POST_SET` (`"postSet"`) | `KeyvHooks.AFTER_SET` (`"after:set"`) | | `KeyvHooks.PRE_GET` (`"preGet"`) | `KeyvHooks.BEFORE_GET` (`"before:get"`) | | `KeyvHooks.POST_GET` (`"postGet"`) | `KeyvHooks.AFTER_GET` (`"after:get"`) | | `KeyvHooks.PRE_DELETE` (`"preDelete"`) | `KeyvHooks.BEFORE_DELETE` (`"before:delete"`) | | `KeyvHooks.POST_DELETE` (`"postDelete"`) | `KeyvHooks.AFTER_DELETE` (`"after:delete"`) | The same pattern applies for `GET_MANY`, `GET_RAW`, `GET_MANY_RAW`, `SET_RAW`, `SET_MANY_RAW` hooks. The old `PRE_`/`POST_` enum values are deprecated but still work. When one of them fires, Keyv emits a `warn` event such as `Hook "preSet" is deprecated: Use KeyvHooks.BEFORE_SET ('before:set') instead`. Rename them to silence the warning. **v5 (before):** ```javascript import Keyv, { KeyvHooks } from 'keyv'; const keyv = new Keyv(); keyv.hooks.addHandler(KeyvHooks.PRE_SET, (data) => { console.log(`Setting ${data.key}`); }); ``` **v6 (after):** ```javascript import Keyv, { KeyvHooks } from 'keyv'; const keyv = new Keyv(); keyv.addHook(KeyvHooks.BEFORE_SET, (data) => { console.log(`Setting ${data.key}`); }); ``` **Events:** Events work the same as before, but now use Hookified internally: ```javascript import Keyv from 'keyv'; const keyv = new Keyv(); keyv.on('error', (err) => { console.error('Keyv error:', err); }); keyv.on('disconnect', () => { console.log('Disconnected'); }); ``` For more about Hookified, visit [https://hookified.org](https://hookified.org). --- ### Error Handling Changed and `throwOnErrors` Was Removed v6 handles errors the way a Node.js `EventEmitter` does. When an operation fails, Keyv emits an `error` event: - **With an `error` listener attached**, the listener receives the error and the operation returns a fallback value, such as `undefined` from `get` or `false` from `set`. - **With no `error` listener attached**, the operation rejects with the error. Every method follows this rule. The `throwOnErrors` and `emitErrors` options were removed. Keyv also re-emits every `error` event its storage adapter emits, so a listener attached only to the adapter doesn't help: Keyv emits the error again, and with no listener on Keyv, it is thrown. **How v5 behaved:** v5's event emitter never threw, even with no listener attached, so a listener did not change what a call returned. What happened on a failure depended on the method, and for some methods on whether the storage adapter had its own version of that method: | v5 method | On failure | | --- | --- | | `set`, `setMany`, `delete`, `deleteMany`, `clear` | Emitted `error` and returned a fallback value | | `has` | Rejected if the adapter had its own `has`. Otherwise, for example with a `Map`, emitted `error` and returned `false` | | `hasMany` | Rejected if the adapter had its own `hasMany`. Otherwise ran `has` for each key | | `get` | Returned `undefined` without emitting `error` | | `getMany`, `getManyRaw` | Rejected if the adapter had its own `getMany`. Otherwise returned `undefined` for each key that failed, without emitting `error` | | `getRaw`, `disconnect`, `iterator` | Rejected | With `throwOnErrors: true`, `get` and the calls that emitted `error` rejected instead of returning a fallback value. `emitErrors: false` turned the `error` events off. **What to change:** - **To get failures back as fallback values**, as many v5 methods returned them, attach an `error` listener: ```javascript keyv.on('error', (error) => console.error('Keyv error:', error)); ``` A no-op listener, `keyv.on('error', () => {})`, discards errors the way `emitErrors: false` did. - **If you used `throwOnErrors: true`**, remove it. With no `error` listener attached, failed calls reject. But errors that a storage adapter emits on its own, outside any call, are then thrown too, and nothing catches them. Redis and Memcache, for example, emit them when a connection drops. With those adapters you need a listener, and failed calls then return fallback values. v6 has no option that makes calls reject while a listener is attached. - **Calls that rejected in v5 now return fallback values when a listener is attached.** This covers `getRaw`, `disconnect`, and `iterator`, which stops iterating, and `has`, `hasMany`, `getMany`, and `getManyRaw` on adapters that had their own versions of those methods. - **`@keyv/redis` keeps its own `throwOnErrors` and `throwOnConnectError` options.** They are adapter options, as in `new KeyvRedis(uri, { throwOnConnectError: true })`, and are unrelated to the removed Keyv option. Keep them if you rely on them. When the adapter rejects because of one of them, it no longer also emits `error`. See [Events and Errors](/docs/events-and-errors/) for the fallback value each method returns. --- ### `deleteMany` Returns `boolean[]` `deleteMany` now returns a `boolean[]` indicating the success of each deletion. The `StorageAdapter` interface has been updated accordingly. **v5 (before):** ```javascript import Keyv from 'keyv'; const keyv = new Keyv(); await keyv.set('key1', 'value1'); await keyv.set('key2', 'value2'); const result = await keyv.deleteMany(['key1', 'key2']); // result was: boolean (true if all deleted) ``` **v6 (after):** ```javascript import Keyv from 'keyv'; const keyv = new Keyv(); await keyv.set('key1', 'value1'); await keyv.set('key2', 'value2'); const results = await keyv.deleteMany(['key1', 'key2']); // results: [true, true] - boolean for each key console.log(results[0]); // true - key1 was deleted console.log(results[1]); // true - key2 was deleted ``` An array is always truthy, so `if (await keyv.deleteMany(keys))` no longer tells you anything. What the old single boolean meant depended on the store. With a `Map`, Memcache, or Etcd it was `true` only when every key was deleted, as in the example above. With SQLite, PostgreSQL, MySQL, and MongoDB it was `true` when any key was deleted. With Redis it depended on the `@keyv/redis` version: 2.7 through 3.0 meant every key, and earlier and later versions any key. Replace it with `.every(Boolean)` or `.some(Boolean)`, whichever matches what your code meant. `delete(key)` with a single key still returns one boolean, and `delete([...])` with an array now returns `boolean[]` like `deleteMany`. --- ### `setMany` Uses `KeyvEntry[]` and Returns `boolean[]` `setMany` now uses the `KeyvEntry[]` type for input and returns `boolean[]` to indicate success for each entry. **v5 (before):** ```javascript import Keyv from 'keyv'; const keyv = new Keyv(); await keyv.setMany([ { key: 'key1', value: 'value1' }, { key: 'key2', value: 'value2' } ]); ``` **v6 (after):** ```javascript import Keyv from 'keyv'; const keyv = new Keyv(); // Using KeyvEntry[] type const entries = [ { key: 'key1', value: 'value1', ttl: 1000 }, { key: 'key2', value: 'value2' } ]; const results = await keyv.setMany(entries); // results: [true, true] - boolean for each entry console.log(results[0]); // true - key1 was set console.log(results[1]); // true - key2 was set ``` --- ### `get` and `getMany` No Longer Support Raw Since Keyv v5.5, we added `getRaw` and `getManyRaw` methods. In v6, raw support has been removed from `get` and `getMany`. **v5 (before):** ```javascript import Keyv from 'keyv'; const keyv = new Keyv(); await keyv.set('key', 'value', 1000); const value = await keyv.get('key'); const rawValue = await keyv.get('key', { raw: true }); // rawValue: { value: 'value', expires: 1234567890 } ``` **v6 (after):** ```javascript import Keyv from 'keyv'; const keyv = new Keyv(); await keyv.set('key', 'value', 1000); // Use get for the value const value = await keyv.get('key'); // value: 'value' // Use getRaw for the raw format const rawValue = await keyv.getRaw('key'); // rawValue: { value: 'value', expires: 1234567890 } // For multiple keys const values = await keyv.getMany(['key1', 'key2']); const rawValues = await keyv.getManyRaw(['key1', 'key2']); ``` In plain JavaScript, `get(key, { raw: true })` doesn't fail. v6 ignores the option and returns the plain value, so code that reads `.expires` from the result gets `undefined`. In TypeScript, `getRaw` is typed `KeyvValue | string | undefined`. Narrow the result before you read `.value` or `.expires` instead of casting it: ```typescript const raw = await keyv.getRaw('key'); if (raw && typeof raw === 'object') { console.log(raw.value, raw.expires); } ``` --- ### Iterator Changes The iterator is now a proper class method instead of a dynamically assigned property. It no longer requires any arguments — namespace handling is automatic. Key changes: - `iterator()` is now a built-in async generator method, not an assignable property - No arguments required (previously required `keyv.namespace`) - Automatically handles Map stores, storage adapters with `iterator()`, and unsupported stores - Expired entries are automatically filtered and deleted during iteration - The `IteratorFunction` type has been removed - If the store does not support iteration, the generator finishes immediately without emitting an error **v5 (before):** ```javascript import Keyv from 'keyv'; const keyv = new Keyv(); await keyv.set('key1', 'value1'); await keyv.set('key2', 'value2'); for await (const [key, value] of keyv.iterator(keyv.namespace)) { console.log(key, value); } ``` **v6 (after):** ```javascript import Keyv from 'keyv'; const keyv = new Keyv(); await keyv.set('key1', 'value1'); await keyv.set('key2', 'value2'); for await (const [key, value] of keyv.iterator()) { console.log(key, value); } ``` --- ### Removed `.ttlSupport` from Storage Adapters The `ttlSupport` property has been removed from storage adapters. Keyv now detects what kind of store it was given. It uses a v6 adapter as-is, wraps an older async adapter in `KeyvBridgeAdapter`, and wraps a `Map` or another synchronous Map-like store in `KeyvMemoryAdapter`, which enforces TTLs itself. See [Legacy Storage Adapters](/docs/legacy-storage-adapters/). **v5 (before):** ```javascript class MyAdapter { ttlSupport = false; // ... } ``` **v6 (after):** ```javascript // No need to specify ttlSupport // Keyv wraps adapters that don't declare the v6 contract in KeyvBridgeAdapter class MyAdapter { // ... } ``` --- ### Storage Adapters Receive Absolute `expires` Instead of Relative `ttl` > **Most users do not need to do anything.** The public Keyv API is unchanged — you still call `keyv.set(key, value, ttl)` with a **relative** TTL in milliseconds, and `KeyvOptions.ttl` is still relative. This change only affects authors of **custom or third-party storage adapters**. In v5, Keyv passed each storage adapter a **relative** `ttl` (milliseconds from now) on `set`/`setMany`, and adapters re-derived the absolute deadline themselves. Some adapters even recovered the expiry by parsing the already-encoded value (`JSON.parse`), which **silently failed** under compression, encryption, or a non-JSON serializer (`@keyv/serialize-msgpackr`, `@keyv/serialize-superjson`) — leaving the expiry unset so the entry never expired. In v6, Keyv computes the **absolute** expiry once and passes it across the storage boundary as `expires` (a Unix timestamp in milliseconds). Adapters store it directly and never parse the value to recover it. **The v6 storage-adapter contract:** - **`set(key, value, expires?)`** — `expires` is an absolute Unix timestamp in milliseconds. `undefined` means no expiry; a value `<= Date.now()` is already expired. - **`setMany(entries)`** — each entry is a `KeyvStorageEntry` (`{ key, value, expires? }`) rather than the public `KeyvEntry` (`{ key, value, ttl? }`). - **Declare support** by exposing `capabilities.expires === true`. The `keyvStorageCapability(this)` helper builds the full capability descriptor for you. **v5 (before):** ```typescript class MyAdapter { // ttl is relative milliseconds, or undefined async set(key: string, value: string, ttl?: number) { const expires = typeof ttl === 'number' ? Date.now() + ttl : undefined; // ...persist value with expires... } async setMany(entries: Array<{ key: string; value: string; ttl?: number }>) { // ...derive expires from each ttl... } } ``` **v6 (after):** ```typescript import { keyvStorageCapability, type KeyvStorageAdapter, type KeyvStorageEntry } from 'keyv'; class MyAdapter implements KeyvStorageAdapter { // Advertise the v6 absolute-expires contract. get capabilities() { return keyvStorageCapability(this); } // expires is an absolute Unix ms timestamp, or undefined async set(key: string, value: string, expires?: number) { // ...persist value with expires directly — no Date.now() math, no parsing... } async setMany(entries: KeyvStorageEntry[]) { // each entry already carries an absolute `expires` } } ``` **Backward compatibility — legacy adapters keep working.** If an adapter does **not** advertise `capabilities.expires`, Keyv treats it as a v5-style adapter and automatically wraps it in `KeyvBridgeAdapter`, which converts the absolute `expires` back to a relative `ttl` before delegating to your `set`/`setMany`. So existing third-party adapters continue to function without code changes. That includes adapters whose methods return promises without being `async` functions, such as ones compiled to an older target: Keyv calls `has` once to tell them apart from a synchronous `Map`. Upgrading to the v6 contract is still recommended: it removes the bridge conversion and eliminates the silent-expiry bug described above. **Adapters should still enforce expiry — and Keyv double-checks by default.** A v6 adapter should enforce expiry via a native server-side mechanism (e.g. Redis `PXAT`, a SQL `expires` column swept on read, a Mongo TTL index) so the backend reclaims space, and/or a client-side check on `get`. On top of that, Keyv core now filters expired reads itself by default (`checkExpired` defaults to `true`), using the absolute `expires` embedded in the serialized envelope. This is the safety net for backends whose native expiry is coarse or lazily swept — Memcached's second-granular `exptime`, or DynamoDB's background TTL sweep that can lag for hours — which would otherwise return logically-expired items. Users who want to trust the backend alone (and skip the extra decode on reads) can opt out with `checkExpired: false`. > **Why this is better:** the absolute `expires` is computed once on the Keyv host, so it is immune to clock skew and to latency between Keyv and the store; adapters never re-parse encoded values; and the silent-expiry bug under compression/encryption/alternate serializers is gone. See the per-adapter "Expiration and TTL" notes (for example, [`@keyv/redis`](https://github.com/jaredwray/keyv/tree/main/storage/redis#expiration-and-ttl)) for backend-specific details. --- ### Returns `undefined` Instead of `null` Keyv now consistently returns `undefined` instead of `null` for missing values. Previously, some storage adapters returned `null`, which was passed through. Now we normalize to `undefined`. **v5 (before):** ```javascript const value = await keyv.get('nonexistent'); // value could be null or undefined depending on the adapter ``` **v6 (after):** ```javascript const value = await keyv.get('nonexistent'); // value is always undefined ``` --- ### Compression Adapter Interface Change Compression adapters now implement the `KeyvCompressionAdapter` interface. Both methods take a string and resolve to a string: ```typescript type KeyvCompressionAdapter = { compress(value: string): Promise; decompress(value: string): Promise; }; ``` v6 compresses the whole serialized entry, `expires` included, and stores the result as base64. The v5 adapters' `serialize`, `deserialize`, and `opts` members are gone. **Data compressed by v5 can't be read by v6.** v5 compressed only the `value` field inside a JSON envelope, and v6 expects the whole entry to be compressed. Reading a v5 entry fails with a decompression error, such as `incorrect header check` from `@keyv/compress-gzip`. Keyv emits `error`, and the call returns `undefined` when a listener is attached or rejects when none is. Treat a compressed v5 store as a cache that v6 repopulates, or read the old entries with v5 and write them again with v6. **Important:** Compression and encryption only run when serialization is enabled, which is the default. With `serialization: false`, Keyv stores values as they are, without compressing them, and with an encryption adapter set, writes fail with an error instead of storing values unencrypted. **v6 usage:** ```javascript import Keyv from 'keyv'; import KeyvGzip from '@keyv/compress-gzip'; const compression = new KeyvGzip(); const keyv = new Keyv({ compression }); // Serialization is enabled by default (built-in KeyvJsonSerializer) await keyv.set('key', { foo: 'bar' }); ``` --- ### Other Silent Behavior Changes These changes don't cause compile errors, and most of them don't throw. Check your code for each one: - **A connection string is ignored.** `new Keyv('redis://localhost:6379')` and `new Keyv({ uri: 'redis://localhost:6379' })` don't load an adapter. v6 quietly uses an in-memory store, and TypeScript accepts both forms. Pass an adapter instead: `new Keyv(new KeyvRedis('redis://localhost:6379'))`. - **Removed options are ignored.** In plain JavaScript, `serialize`, `deserialize`, `useKeyPrefix`, `emitErrors`, and `throwOnErrors` have no effect, and neither does `@keyv/redis`'s `keyPrefixSeparator`, now `namespaceSeparator`. - **`keyv.store` returns the wrapper.** For a `Map` or an older adapter, `keyv.store` is the `KeyvMemoryAdapter` or `KeyvBridgeAdapter` that Keyv created, and the object you passed in is at `keyv.store.store`. v5 returned your object. - **A `Map` holds different entries.** A `Map` store now holds `{ value, expires }` objects under `namespace::key`, or under the bare key when there is no namespace. v5 stored serialized strings under `keyv:key`. Code that reads the `Map` directly must change. - **Array results are always truthy.** `deleteMany` and `delete([...])` return `boolean[]`, so `if (await keyv.deleteMany(keys))` is always true. Check `results.every(Boolean)` instead. - **A TTL of zero or less means no TTL.** v5 treated only `0` that way. Fractional TTLs are rounded up to the next millisecond. - **Empty-string keys are rejected.** `set('', value)` and `delete('')` return `false`, and `get('')` returns `undefined`. - **Symbols can't be stored.** `set(key, Symbol())` emits `error`, so it rejects when no listener is attached and returns `false` when one is. - **`has()` reads the value.** With `checkExpired` on, which is the default, `has` reads and decodes the entry so it can skip expired values. - **Stats count per key.** `getMany(['a', 'b'])` now records a hit or miss for each key, not one for the call. A failed read counts as an error, not a miss. The v5 `StatsManager` methods `hit()`, `miss()`, `set()`, `delete()`, and `hitsOrMisses()` were removed. - **Some exports were removed.** `CompressionAdapter`, `Serialize`, `Deserialize`, `StoredData`, `StoredDataNoRaw`, and `StoredDataRaw` are gone, and `IEventEmitter` now comes from `hookified`. `KeyvStoreAdapter`, `DeserializedData`, and `KeyvCompression` remain as deprecated aliases of `KeyvStorageAdapter`, `KeyvValue`, and `KeyvCompressionAdapter`. --- ### `@keyv/test-suite` API Changes If you maintain a storage adapter, update its tests: - The package has no default export. Import the suites by name. - The first argument is Vitest's `test` (or `it`) function. v5 took the whole `vitest` module. - `keyvNamespaceTest` is now `keyvNamespaceTests`, and `keyvCompresstionTests` is now `compressionTestSuite`. - New suites test the adapter directly, without Keyv: `storageTestSuite` runs `storageBasicTests`, `storageBatchTests`, `storageIteratorTests`, `storageTtlTests`, `storageNamespaceTests`, and `storageDisconnectTests`. ```javascript import { keyvTestSuite, storageTestSuite } from '@keyv/test-suite'; import { Keyv } from 'keyv'; import { test } from 'vitest'; import MyAdapter from './src/index.js'; const store = () => new MyAdapter(); keyvTestSuite(test, Keyv, store); storageTestSuite(test, store); ``` --- ### Libraries That Embed Keyv v5 Some libraries depend on Keyv v5 and take Keyv instances or adapters from your code. For example, `cache-manager` 7, `cacheable` 2, `@cacheable/memory`, and `cacheable-request` 13 all depend on `keyv` `^5.6.0`. Mixing them with v6 breaks quietly: - **A v6 `Keyv` passed to a v5 library.** `cache-manager` calls `store.get(key, { raw: true })` and reads `.expires`. v6 ignores `raw`, so `ttl()` and the refresh logic in `wrap()` stop working. - **A v6 adapter used by a v5 `Keyv`.** A v5 Keyv passes a relative `ttl` where a v6 adapter expects an absolute `expires` timestamp, so entries expire at the wrong time, usually at once. Check which Keyv version a library needs with `npm view dependencies.keyv peerDependencies.keyv`. Keep the Keyv instances and adapters you pass to such a library on v5 until it supports v6. If `keyv` appears in your project only as a dependency of another package, you have nothing to migrate. Don't force v6 onto that package with `overrides` or `resolutions`. --- ### `@keyv/memcache` Moves from `memjs` to `memcache` The `@keyv/memcache` package will switch its underlying Memcached client library from [`memjs`](https://www.npmjs.com/package/memjs) to [`memcache`](https://www.npmjs.com/package/memcache). **Why the change:** - `memjs` uses the binary protocol and has not been actively maintained - `memcache` is actively maintained with a promise-based API and support for features such as consistent hashing, connection pooling, and hooks/events **What this means for you:** - If you are using `@keyv/memcache` through Keyv with default settings, **no changes are needed** — the adapter API remains the same - If you are passing `memjs`-specific client options through to the underlying client, you will need to update them to match the `memcache` client API - The `memcache` client uses Memcached's text protocol, which doesn't take keys with whitespace or control characters. v6 stores those keys, and keys over 250 bytes, under a SHA-256 digest of the namespaced key instead of failing. So are keys that start with `keyv:sha256:`, the prefix of those digest keys. `memjs` used the binary protocol, which takes whitespace, and v5 trimmed namespaced keys, so an entry v5 wrote for a key with whitespace or control characters isn't found by v6 --- ### `@keyv/memcache` `clear()` Only Removes the Store's Own Entries In v5, `clear()` on a `@keyv/memcache` store flushed the whole Memcached server, with or without a namespace. That removed other namespaces' entries and keys other applications wrote. In v6, each namespace has a generation token stored in Memcached, and every value is stored after the token it was written under. `clear()` writes a new token, so the namespace's older values read as missing, and Memcached evicts them or lets them expire. Other namespaces and other applications' keys stay. Without a namespace, `clear()` does the same for the entries written with no namespace. **What this means for you:** - Entries v5 wrote have no token, so v6 reads them as missing. Let the cache fill again - To flush the whole server from a store without a namespace, as v5 did, set `noNamespaceAffectsAll: true`. That store then also writes values without a token - If Memcached loses a namespace's token, because it evicted it or the node holding it restarted, the adapter creates a new one and the namespace reads as empty. It never serves values from before a `clear()` --- ### `@keyv/etcd` Default `ttl` Applies Per Key In v5, the `ttl` option of `@keyv/etcd` created one etcd lease when the store was constructed, and every key written without an expiry was attached to it. The lease started counting at the first write and was never renewed, so every key on it was deleted when it expired, no matter when that key was written. After that, writes without an expiry failed because the lease no longer existed. In v6, `ttl` applies to each key written without an expiry, counted from that write, and each such key gets its own lease. `ttl` can also be changed on the store at any time. **What this means for you:** - If you set `ttl` on the store, keys now live for `ttl` from their own write, and writes keep working after the first `ttl` has passed - The `lease` property is removed. Remove any code that reads or assigns `store.lease` --- ### `@keyv/etcd` Without a Namespace Only Clears Its Own Entries In v5, `clear()` on a `@keyv/etcd` store with no namespace deleted every key in etcd, including other namespaces' entries and other applications' keys. `iterator()` returned every key too. In v6, with no namespace, both only touch entries v6 wrote without a namespace. Each value records the namespace it was written under, and entries written before that was recorded count when their key has no separator (`::` by default). Entries v5 wrote are left alone, since nothing sets their `{ value, expires }` JSON apart from another application's. **What this means for you:** - To have `clear()` delete every key in etcd and `iterator()` return every key, as in v5, set `noNamespaceAffectsAll: true` - A v5 entry stored under a namespace, such as `keyv:foo`, is cleared by a store with that namespace - A v5 entry stored with no namespace stays until it expires or v6 writes that key again. If the etcd holds only Keyv data, `clear()` with `noNamespaceAffectsAll: true` removes it --- ### `@keyv/dynamo` Keys Without a TTL No Longer Expire In v5, `@keyv/dynamo` gave every key written without a TTL an expiry six hours after the write, and DynamoDB's TTL process deleted the key some time after that. No other adapter expires keys that were written without a TTL. In v6, a key written without a TTL has no expiry and is kept until it is deleted. The `sixHoursInMilliseconds` property is removed. **What this means for you:** - To give keys a default expiry, set Keyv's `ttl` option, such as `new Keyv(store, { ttl: 6 * 60 * 60 * 1000 })` - Remove any code that reads or assigns `store.sixHoursInMilliseconds` - A key written by v5 keeps the expiry it was written with until it is written again --- ### `@keyv/bigmap` Keeps Entries When `storeSize` or `storeHashFunction` Changes In v5, setting `storeSize` on a `BigMap` removed every entry. Setting `storeHashFunction` left each entry in the internal `Map` the old function had picked, so `get()`, `has()` and `delete()` missed most of them, `size` still counted them, and `set()` on one of those keys added a second copy. In v6, both setters move every entry into the `Map` its key maps to under the new setting, so nothing is lost or duplicated. If a custom hash function throws while entries are moved, the setter rethrows and the map is left as it was. **What this means for you:** - If code sets `storeSize` to empty the map, call `clear()` as well - Moving entries takes one pass over the map, so for a large map set `storeSize` and `storeHashFunction` in the constructor --- ### `@keyv/redis` `keyPrefixSeparator` Is Now `namespaceSeparator` The option, getter, and setter for the separator between the namespace and the key are now called `namespaceSeparator`, the same name every other adapter that joins the namespace and key uses. The default is still `::`. **v5 (before):** ```javascript const store = new KeyvRedis('redis://localhost:6379', { keyPrefixSeparator: ':' }); ``` **v6 (after):** ```javascript const store = new KeyvRedis('redis://localhost:6379', { namespaceSeparator: ':' }); ``` **What this means for you:** - Rename `keyPrefixSeparator` to `namespaceSeparator` in your options and code - In plain JavaScript an old `keyPrefixSeparator` option is ignored and the store uses `::`. If you set another separator, keys written before the upgrade read as missing until you rename the option. TypeScript reports the old option as an error --- ### `@keyv/redis` Matches the Namespace Literally In v5, `clear()` and `iterator()` on a `@keyv/redis` store with a namespace passed `*` to `SCAN` without escaping it. A `*`, `?`, `[`, `]` or `\` in the namespace or separator was read as pattern syntax, so `clear()` on namespace `tenant*` also deleted the keys of namespace `tenant-prod`, and `iterator()` returned them. A namespace such as `t[12]` or `a\b` didn't match its own keys, so `clear()` left them in place. In v6, the namespace and separator are matched literally. `clear()` and `iterator()` only touch keys that start with ``. **What this means for you:** - Namespaces without those characters behave as before - If code used a wildcard namespace to clear or iterate several namespaces at once, call `clear()` or `iterator()` once for each namespace instead --- ## New Features ### Keyv v6 Versioning Starting with v6, all Keyv packages and adapters use **unified versioning**. Every package in the Keyv ecosystem shares the same version number and is released together. The first stable v6 release is 6.1.0; there is no 6.0.0 release. See [Versioning & Release Tags](/docs/migration/versioning/) for the npm dist-tags. **What this means for you:** - All `@keyv/*` packages have the same version (e.g., `keyv@6.1.0`, `@keyv/redis@6.1.0`, `@keyv/sqlite@6.1.0`) - When you upgrade Keyv, you can upgrade all adapters to the same version with confidence that they are compatible - No more wondering which adapter version works with which Keyv version **Example of unified versions:** ``` keyv: 6.1.0 @keyv/redis: 6.1.0 @keyv/sqlite: 6.1.0 @keyv/postgres: 6.1.0 @keyv/serialize-superjson: 6.1.0 @keyv/compress-gzip: 6.1.0 ``` This approach is used by many popular projects: - **[Vitest](https://vitest.dev)** - All packages in the Vitest monorepo share the same version - **[Babel](https://babeljs.io)** - All `@babel/*` packages are versioned together - **[Jest](https://jestjs.io)** - All Jest packages use unified versioning - **[Angular](https://angular.io)** - All `@angular/*` packages share the same version - **[Vue](https://vuejs.org)** - Vue and its companion packages are versioned together Unified versioning simplifies dependency management and ensures compatibility across the entire Keyv ecosystem. ### Keyv v5 Maintenance Mode With the release of Keyv v6, Keyv v5 is in maintenance mode. No major functionality will be added to Keyv v5. Only maintenance and security fixes will be applied going forward, and releases from the v5 line no longer move `latest` (see [Versioning & Release Tags](/docs/migration/versioning/)). We encourage all users to migrate to v6 to take advantage of the latest features and improvements. The `v5` branch will remain available in the mono repo for reference. --- ### Browser Compatibility Keyv v6 is now fully compatible with browser environments. You can use Keyv in frontend applications with appropriate storage adapters. ```javascript import Keyv from 'keyv'; // Works in the browser const keyv = new Keyv({ store: new Map() }); ``` --- ### Serialization Adapters The default serializer is the built-in `KeyvJsonSerializer`. The property is `serialization`. ```javascript import Keyv from 'keyv'; const keyv = new Keyv(); // default JSON serializer import { superJsonSerializer } from '@keyv/serialize-superjson'; keyv.serialization = superJsonSerializer; ``` **Available Serialization Adapters:** | Package | Description | |---------|-------------| | `KeyvJsonSerializer` (built-in) | **Default** — JSON plus `Buffer` and `BigInt` | | `@keyv/serialize-superjson` | `Date`, `Map`, `Set`, `RegExp`, `URL`, `Error`, `undefined` | | `@keyv/serialize-msgpackr` | High-performance binary MessagePack | #### Disabling Serialization For in-memory storage or when serialization isn't needed (and you're not using encryption/compression): ```javascript import Keyv from 'keyv'; const keyv = new Keyv({ store: new Map(), serialization: false }); // Or set via property keyv.serialization = undefined; ``` > **Note:** If you want to use encryption or compression, you must have serialization enabled. #### Custom Serialization Create your own serialization adapter with the `KeyvSerializationAdapter` type. Either method may return a promise: ```typescript type KeyvSerializationAdapter = { stringify: (object: unknown) => string | Promise; parse: (data: string) => T | Promise; }; ``` ```javascript import Keyv from 'keyv'; const customSerializer = { stringify: (value) => JSON.stringify(value), parse: (value) => JSON.parse(value) }; const keyv = new Keyv({ serialization: customSerializer }); ``` --- ### Encryption Adapters You can now add encryption to values with the following adapters: | Package | Description | |---------|-------------| | `@keyv/encrypt-node` | Node.js `crypto` (AES-GCM, AES-CCM, ChaCha20-Poly1305) | | `@keyv/encrypt-web` | Web Crypto API for browsers, Workers, and Deno | ```javascript import Keyv from 'keyv'; import KeyvEncryptNode from '@keyv/encrypt-node'; const encryption = new KeyvEncryptNode({ key: 'your_secret_key_here' }); const keyv = new Keyv({ encryption }); await keyv.set('sensitive', { password: 'secret' }); ``` #### Custom Encryption Create your own encryption adapter with the `KeyvEncryptionAdapter` type. Either method may return a promise: ```typescript type KeyvEncryptionAdapter = { encrypt: (data: string) => string | Promise; decrypt: (data: string) => string | Promise; }; ``` > **Note:** Encryption runs on the serialized string, so it only works while `serialization` is enabled, which is the default. With `serialization: false`, writes fail with an error instead of storing values unencrypted. --- ### New Identification Functions Keyv v6 provides `detect*` helpers (these replaced the earlier `isKeyv` / `isKeyvStorage` names). See [Detect Capabilities](/docs/detect-capabilities/). #### `detectKeyv` ```javascript import Keyv, { detectKeyv } from 'keyv'; detectKeyv(new Keyv()).compatible; // true detectKeyv(new Map()).compatible; // false ``` #### `detectKeyvStorage` ```javascript import { detectKeyvStorage } from 'keyv'; detectKeyvStorage(new Map()).store; // 'mapLike' ``` #### Compression, serialization, encryption ```javascript import { detectKeyvCompression, detectKeyvSerialization, detectKeyvEncryption } from 'keyv'; detectKeyvCompression(gzipAdapter).compatible; detectKeyvSerialization(JSON).compatible; detectKeyvEncryption(aesAdapter).compatible; ``` --- ### Memory Adapter Keyv v6 includes `KeyvMemoryAdapter`, a wrapper class for storage types that don't conform to v6 storage adapter requirements (such as `Map`-compatible or legacy adapters). **Features:** - Handles namespacing using key prefixing - Adds the v6 batch methods the store lacks: `getMany`, `setMany`, `hasMany`, and `deleteMany` - Attempts iteration using various strategies - Adds TTL support and handles expiration Older async adapters go through `KeyvBridgeAdapter` instead. See [Legacy Storage Adapters](/docs/legacy-storage-adapters/). ```javascript import Keyv, { detectKeyvStorage } from 'keyv'; // Map-compatible stores are automatically wrapped const yourStore = new Map(); const keyv = new Keyv({ store: yourStore }); // Check if your adapter will use KeyvMemoryAdapter const capabilities = detectKeyvStorage(yourStore); if (capabilities.store === 'mapLike') { console.log('This store will use KeyvMemoryAdapter'); } ``` --- ## Getting Help If you encounter issues during migration: 1. Check the [Keyv documentation](https://keyv.org) 2. Search [existing issues](https://github.com/jaredwray/keyv/issues) 3. Open a [new issue](https://github.com/jaredwray/keyv/issues/new) with details about your migration problem ### Versioning & Release Tags URL: https://keyv.org/docs/migration/versioning/ # Versioning & Release Tags Keyv supports more than one major version at a time, so the npm [dist-tags](https://docs.npmjs.com/cli/v11/commands/npm-dist-tag/) are managed deliberately. This page explains which tag points where and which install command to use. Since **v6**, all Keyv packages — the core `keyv` package and every official adapter (`@keyv/redis`, `@keyv/postgres`, …) — share a single version and are released together, so the tags below apply consistently across the whole family. (v5 and earlier versioned each package independently — see [Why all packages share one version](#why-all-packages-share-one-version) for the reasoning.) ## Which version do I get? ```bash pnpm add keyv # latest stable, currently v6 (recommended) pnpm add keyv@6 # the newest stable v6 release pnpm add keyv@5 # the newest stable v5 release pnpm add keyv@4 # the newest stable v4 release ``` From v6 on, an adapter shares Keyv's version, so `pnpm add @keyv/redis@6` lines up with `keyv@6`. (On v5 and earlier, adapters carried their own version numbers — see [Why all packages share one version](#why-all-packages-share-one-version).) ## Dist-tags | Tag | Points to | Use it for | | --- | --- | --- | | `latest` | Newest **stable** release of the current major (v6) | The default — `pnpm add keyv` | | `v5-lts` | Newest **stable v5** release. Set by the next v5 release; until then use `keyv@5` | Pinning the v5 line explicitly | | `alpha`, `beta`, `rc` | Newest **pre-release** of that kind | Trying a release before it ships | > Stable v6 starts at **6.1.0**; there is no 6.0.0 release. Since 6.1.0, `latest` points to v6 for `keyv` and the rest of the v6 family. Releases from the v5 line no longer move `latest`; they get a `v{major}-lts` tag such as `v5-lts` (see [How releases are tagged](#how-releases-are-tagged)). Each pre-release tag moves only when a pre-release of that kind is published, so it can point at a build older than `latest`: until the next pre-release, `alpha`, `beta`, and `rc` still point at 6.0.0 pre-releases. Keep `keyv` and every `@keyv/*` package on the same version, such as `6.1.0`. ## Why keyv@5 works without a special tag You may notice there is no `v5` or `v6` dist-tag. That is intentional: npm **rejects** dist-tag names that look like a semver version or range, so a tag literally named `v6` is not allowed. Instead, `keyv@5`, `keyv@v5`, and `keyv@6` are interpreted as **semver ranges** (`5.x`, `6.x`) and npm resolves them to the newest matching **stable** release automatically — no tag required. One consequence: a semver range only matches stable releases, so `keyv@6` resolves to the newest stable 6.x release and never to a pre-release. To try a pre-release, use its tag, such as `keyv@rc`, or an exact version. ## How releases are tagged Each release computes its tag from its version: - **Pre-release** → published under a tag named after its pre-release id: `6.0.0-beta.1` goes to `beta`, and `6.0.0-rc.1` goes to `rc`. Never touches `latest`. - **Stable, current major** → published under `latest`. - **Stable, older major** → published under `v{major}-lts` (e.g. `v5-lts`). An older major can never move `latest`. A safety guard refuses any release that would move `latest` backwards, so `pnpm add keyv` always installs a forward-moving stable line. ## How releases are published Both release lines publish through the same GitHub Actions workflow (`release.yaml`) using npm [staged publishing](https://docs.npmjs.com/staged-publishing/) with [trusted publishing](https://docs.npmjs.com/trusted-publishers/) and provenance: CI only *stages* a version, and a maintainer approves it with 2FA before it becomes installable. On `main` (v6) a GitHub Release triggers the workflow. On the `v5` branch a maintainer runs it manually from `v5`, and only the packages whose version is ahead of npm are staged, since v5 packages are versioned independently. A GitHub Release named `v5-YYYY-MM-DD` may accompany a v5 cut for release notes. It does not publish anything: a GitHub Release runs the workflow file at the tag's commit, the `v5` branch's workflow has no `release` trigger, and main's release workflow refuses any tag whose commit is not on `main`. ## Why all packages share one version Before v6, each Keyv package was versioned independently — a package only got a new version when its own code changed. That is the textbook semver approach, but for a family of packages designed to be used together it created friction: - **Compatibility was a guessing game.** Which `@keyv/redis` works with which `keyv`? You had to consult a compatibility matrix instead of reading it off the version number. - **Dist-tags didn't line up.** `keyv@beta` and `@keyv/redis@beta` could point at unrelated version numbers, and a range like `@keyv/redis@6` would not necessarily match `keyv@6`. - **Adapters looked stale.** A solid adapter that simply hadn't changed in a while would lag several majors behind core, reading as unmaintained when it was fine. - **Coordinated changes were awkward.** The v6 overhaul touched core, serialization, compression, and the adapters together; shipping that cleanly wants a single coordinated release, not a dozen independently-versioned ones. From v6 onward we version the whole family together: every package shares one version and is published at the same time. Now the version number *is* the compatibility statement — `keyv@6.2.0` is built and tested against `@keyv/redis@6.2.0` — and every dist-tag (`latest`, `beta`, `v5-lts`) means the same thing across every package. The trade-off is that a package can get a new version even when its own code didn't change, simply because the family moved. We accept that: the clarity of "install everything at the same version" is worth more than a per-package number that strictly reflects only that package's own diffs. These family-wide behaviors — shared versions, and a dist-tag meaning the same thing everywhere — describe **v6 onward**. The v5 and v4 lines keep the independent versions they shipped with, so on those lines you pin each adapter to its own compatible release. ## Maintenance & breaking changes on LTS **Our goal: an LTS line never changes its API landscape.** We aim for staying within a major (`keyv@6`) to mean `pnpm update` is safe — your code keeps compiling and behaving the same. "API landscape" here means the public types and method signatures, constructor options, events, runtime behavior, and the supported runtimes (Node.js versions, ESM/CJS). We work to keep all of these stable across an LTS line. Breaking changes — to Keyv's API or to its supported runtimes — only ever land on the **next major**. Since 6.1.0, v6 is an LTS line alongside v5, so the next breaking release is v7. ### When an underlying dependency releases a breaking major on LTS Keyv's core has a single dependency, `hookified`, but the storage adapters wrap third-party drivers (for example `@keyv/redis` over its Redis client, `@keyv/sqlite` over its SQLite driver). When one of those drivers ships a breaking major, the question is **not** "did the dependency have a major?" but "**does adopting it change Keyv's own contract?**": - **It can be absorbed** — the adapter handles the difference internally and nothing observable changes for you (same API, same behavior, same supported Node versions). → We ship it as a **minor** release on the LTS line. (A pure security or internal-only fix may be a **patch**.) A dependency major is significant enough that we signal it with a minor rather than a patch, even though your code needs no changes. - **It cannot be absorbed** — adopting it would change Keyv's API, alter a default you rely on, or drop a supported runtime (e.g. the driver drops an older Node version). → We **do not** take it on the LTS line. The LTS line stays on the last compatible driver major, and the upgrade lands only in the next major. So a major bump of an inner dependency never forces a major bump of Keyv, and it never forces a breaking change onto LTS. The dependency's version number doesn't drive Keyv's — Keyv's public contract does. That is what semver actually versions: *our* API, not our dependencies' APIs. > Because all Keyv packages share one version, a dependency change in a single adapter is released as a version bump across the whole family. That is expected — the family always moves together. (This is the v6 model; on the v5 line, which still uses independent versions, only the changed adapter bumps.) ### When a dependency raises its Node.js requirement Raising the minimum supported Node.js version is itself a **breaking change** — it is part of the runtime contract above, even when no code changes. A user on the dropped Node version who runs `pnpm update` would suddenly be unable to install or run Keyv. So we treat a dependency that raises its Node floor exactly like any other change we cannot absorb: - **On an LTS line (and on any already-released major):** we never raise the Node floor. If a driver's new version requires a newer Node than the line supports, the line stays on the last driver version compatible with its committed Node range. The newer driver is adopted only in the next Keyv major. - **Node floor increases happen only at a major boundary.** A new Keyv major may raise its minimum Node version — and is the place where we adopt drivers that did. While that major is still in pre-release the floor can still move; once it ships stable, the floor is fixed for that major's lifetime. For v6, the floor is Node.js 22.19.0. In short, `engines.node` on a released line never goes up. We track Node.js's own [release schedule](https://nodejs.org/en/about/previous-releases) and drop end-of-life Node versions only when we cut a new major — never on LTS, and never mid-major. ### Security fixes on LTS versions Security is the one thing that can override "no changes on LTS", and we work hard to avoid even that. If a vulnerability's only fix lives in a driver major that *would* break Keyv's contract, we first try to pin a patched release of the compatible major, or get the fix backported. Only if there is genuinely no compatible fix do we make an announced, documented exception — this is rare and clearly communicated. ### Peer dependencies Some adapters take their driver as a peer dependency, so you control its version. On an LTS line we keep the supported peer range stable; support for a driver's new breaking major is added in the next major, not backported. For the v5 → v6 changes themselves, see the [v5 to v6 Migration](/docs/migration/v5-to-v6/) guide. The v5 documentation site is archived at [keyv.org/v5](/v5/). ## API Reference URL: https://keyv.org/api - Not available. ## Changelog URL: https://keyv.org/changelog ### v6.1.0 URL: https://keyv.org/changelog/v6-1-0 Date: October 6, 2026 Tag: Release ## keyv@6.1.0 — 2026-10-06 First stable release of Keyv v6, published to npm's `latest` tag. _All 20 published packages release in lockstep at 6.1.0; there is no 6.0.0. `@keyv/website` is private and not published._ Coming from v5? Follow the [v5 to v6 migration guide](https://keyv.org/docs/migration/v5-to-v6/), or point your coding agent at [https://keyv.org/skills/migrate.](https://keyv.org/skills/migrate.) v5 stays in maintenance; install it with `keyv@5`. ### ⚠ BREAKING CHANGES These are changes since `6.0.0-rc.1`. Coming from v5, start with the [migration guide](https://keyv.org/docs/migration/v5-to-v6/). - **keyv, adapters:** the namespace separator option is `namespaceSeparator` on every adapter that joins the namespace and the key, and it defaults to `::`; `keySeparator` and `keyPrefixSeparator` are gone (d0bc310, #2189) Migration from rc.1: rename the option. To keep reading namespaced data rc.1 wrote, set `namespaceSeparator: ':'` on the memory and bridge adapters, `@keyv/etcd`, `@keyv/dynamo`, `@keyv/cloudflare-kv` and `@keyv/valkey`. `@keyv/redis` already used `::` in rc.1. Migration from v5: v5's Keyv also prefixed every key with `:`, so the setting depends on the adapter. A default v5 `@keyv/redis` setup stored `keyv::keyv:foo`, which v6 reads with `new Keyv(new KeyvRedis(uri, { namespaceSeparator: '::keyv:' }), { namespace: 'keyv' })`. If you used `createKeyv()`, set only the same `namespace`. For other adapters, see [The Default `keyv` Namespace Was Removed](https://keyv.org/docs/migration/v5-to-v6/#the-default-keyv-namespace-was-removed). - **keyv:** `throwOnErrors` is removed; a failed call returns a fallback value when an `error` listener is attached and rejects when none is (860dba7, #2155) Migration: remove `throwOnErrors`, and attach an `error` listener if you want fallback values instead of rejections. - **keyv:** a namespace set on the storage adapter is used when Keyv has none (c6e88e7, #2156) Migration: data rc.1 wrote in that setup has no namespace; remove the adapter's namespace to keep reading it, or let it refill. - **keyv:** a namespaced `clear()` fails instead of wiping a store it can't list (790eb3c, #2186) Migration: give the store `keys()` or `iterator()`, or call `clear()` on a Keyv instance without a namespace to empty it. - **keyv:** writes fail when an encryption adapter is set and serialization is off; rc.1 stored those values unencrypted (b73ee16, #2176) Migration: keep serialization on, which is the default, when you use encryption. - **postgres, sqlite, mongo, dynamo, cloudflare-kv, etcd:** keys that start with `:` are stored as given instead of being treated as already prefixed (9dec04c, #2159) Migration: entries rc.1 wrote under such keys read as missing; write them again. - **encrypt-node, encrypt-web:** `@keyv/encrypt-node` accepts only AES-GCM, AES-CCM and ChaCha20-Poly1305 with `base64`, `base64url` or `hex` output, and `@keyv/encrypt-web` accepts only AES-GCM; AES-CBC is removed (b06ec8b, #2187) Migration: the defaults are unchanged; re-encrypt values written with any other algorithm or encoding before you upgrade. - **dynamo:** keys written without a TTL no longer expire, and `sixHoursInMilliseconds` is removed (476761d, #2161) Migration: set Keyv's `ttl` option for a default expiry, as in `new Keyv(store, { ttl: 6 * 60 * 60 * 1000 })`. - **etcd:** the `lease` property is removed, and the store `ttl` applies to each key from its own write (6ba3096, #2160) Migration: remove code that reads or sets `store.lease`. - **etcd:** without a namespace, `clear()` and `iterator()` only touch entries Keyv wrote without a namespace (8a77946, #2173) Migration: set `noNamespaceAffectsAll: true` for the rc.1 behavior, and `namespaceSeparator: ':'` while etcd still holds namespaced rc.1 entries. - **memcache:** `clear()` only removes the store's own entries, and values rc.1 wrote read as missing (12415c5, #2179) Migration: let the cache refill; set `noNamespaceAffectsAll: true` on a store without a namespace to flush the whole server. - **bigmap:** setting `storeSize` keeps every entry and no longer emits `clear` (b80b44d, #2178) Migration: call `clear()` yourself if you resized the map to empty it. ### Features - add the `keyv-migrate` agent skill, which upgrades a project from Keyv v4 or v5 to v6; it is published at [https://keyv.org/skills/migrate](https://keyv.org/skills/migrate) (bae30d5, #2171) ```bash npx skills add jaredwray/keyv --skill keyv-migrate ``` - add a `namespaceSeparator` option to every adapter that joins the namespace and the key; it defaults to `::` (d0bc310, #2189) ```ts import Keyv from 'keyv'; import KeyvEtcd from '@keyv/etcd'; // Read keys written with the old ':' separator const keyv = new Keyv(new KeyvEtcd('etcd://localhost:2379', { namespaceSeparator: ':' }), { namespace: 'keyv' }); ``` ### Bug Fixes - keyv: promise-based stores without async methods go through `KeyvBridgeAdapter` (9c82ca3, #2157) - keyv: the sanitizer strips patterns until none remain (3462350, #2158) - keyv, postgres: fractional TTLs no longer fail writes, and postgres `disconnect()` releases the pool it connected with (82daf5d, #2168) - postgres, sqlite: a `clearExpiredInterval` over 24.8 days no longer runs cleanup every millisecond (920ad81, #2164) - cloudflare-kv: keys with a TTL of 60 seconds or less are removed by KV (ce6efce, #2162) - etcd: the value envelope uses Keyv's JSON serializer, so `Buffer` and `BigInt` values round-trip (9010961, #2041) - etcd: `setMany()` reports failed writes as `false` (c8133f7, #2172) - memcache: keys memcached can't store now work, and rejected writes return `false` (365eeba, #2174) - mongo: add a v6 migration script so documents v5 wrote stay readable (4068b0a, #2152) - mongo: GridFS reads the newest revision, and `delete()` removes every revision (8101af5, #2163) - mysql: tables get a primary key on `(namespace, id)`, and existing tables are migrated on connect (1bb5d90, #2165) - mysql: the primary-key migration keeps primary keys you added and finds generated invisible ones (fbbb044, #2170) - mysql, postgres: the v6 migration scripts ship in the package and run with `npx tsx` (8ede7f4, #2150) - mysql, valkey: `keyv` is a peer dependency instead of a bundled copy (2c72abe, #2149) - postgres: the migration script drops the legacy primary key first, `deleteMany()` runs as one statement, and SQL `NULL` reads as `undefined` (aa692eb, #2064) - redis: `createKeyv()` accepts cluster and sentinel options, replacing the client removes the old client's listeners, and missing values are `undefined` (cab81d2, #2062) - redis: concurrent operations during the handshake share one connect instead of failing (bb35d2b, #2105) - redis: `connectionTimeout` covers the handshake, and timed-out connects close their sockets (00a48ba, #2108) - redis: `createKeyvNonBlocking()` stops reconnecting to a server that is down (0575171, #2167) - redis: `clear()` and `iterator()` match the namespace literally, not as a glob pattern (b91b8bf, #2185) - sqlite: converting a v5 table runs in a transaction, and the `sqlite3` driver no longer hangs after a failed statement (90630ee, #2063) - valkey: reads return `undefined`, never `null` (2435715, #2065) - valkey: `clear()` removes only its own namespace, not namespaces that share its prefix (4d369be, #2147) - valkey: `clear()`, `iterator()` and `useSets` work in cluster mode (a4326e9, #2166) ### Documentation - keyv.org moves to the Docula modern template, and the v5 docs are archived at [https://keyv.org/v5/](https://keyv.org/v5/) (52f692d, #2066) - how to keep reading data written by v5, with each adapter's stored key layout (df63ef6, #2151) - encryption: use a random secret as the key, or derive one with PBKDF2 (b5eeec9, #2188) - postgres, redis: TLS how-tos for Amazon RDS for PostgreSQL and Redis Cloud (bda7916, #2194) - migration guide and skill corrections (13c683e, #2169; f1bb9e3, #2175; bec33f4, #2177) ### Internal - npm releases are staged and approved with 2FA, with provenance and an Aikido scan gate; stable v6 releases stage under `latest` (#2057, #2124, #2148) - runtime dependency upgrades: `@redis/client` 6.2.1, `mongodb` 7.6.0, `mysql2` 3.24.2, `pg` 8.23.0, `better-sqlite3` 13.0.3, `memcache` 1.10.0, AWS SDK DynamoDB 3.1121.0, `msgpackr` 2.1.0, `lz4-napi` 2.10.0, `hookified` 3.0.3 (#2083–#2092) ### Contributors - @jaredwray (99) ### Full List of Changes - etcd - fix: Use Keyv default serializer for value envelope by @jaredwray in #2041 - mono - chore: defense - stage npm publishes with Aikido gate by @jaredwray in #2057 - website - docs: migrate to Docula 2 modern template and archive v5 by @jaredwray in #2066 - redis - refactor: v6 client swap, API docs, and test uniformity by @jaredwray in #2062 - postgres - fix: v6 release review (migration, API docs, events) by @jaredwray in #2064 - sqlite - fix: harden v6 sqlite adapter, docs, and tests by @jaredwray in #2063 - valkey - refactor: v6 review cleanup for docs, tests, and events by @jaredwray in #2065 - redis - fix: share in-flight connect so concurrent ops are not dropped by @jaredwray in #2105 - redis - fix: Abort timed-out Redis connects without leaking sockets by @jaredwray in #2108 - mono - chore: release concurrency group + v5 staged publishing docs by @jaredwray in #2124 - valkey - fix: clear() only removes keys in the exact namespace by @jaredwray in #2147 - mono - fix: stage stable v6 releases under latest, not v6-lts by @jaredwray in #2148 - mono - fix: declare keyv as a peer dependency of mysql and valkey by @jaredwray in #2149 - mono - fix: make the mysql and postgres v6 migration scripts runnable by @jaredwray in #2150 - mono - docs: explain how to keep reading data written by v5 by @jaredwray in #2151 - mongo - fix: add a v6 migration script so v5 documents stay readable by @jaredwray in #2152 - keyv - fix: follow the EventEmitter error rule and remove throwOnErrors by @jaredwray in #2155 - keyv - fix: keep a namespace set on the storage adapter by @jaredwray in #2156 - keyv - fix: route promise-based stores without async methods through the bridge by @jaredwray in #2157 - keyv - fix: strip sanitizer patterns until none remain by @jaredwray in #2158 - mono - fix: keys that start with the namespace no longer collide by @jaredwray in #2159 - etcd - fix: default ttl applies per key and keeps working after the first lease expires by @jaredwray in #2160 - dynamo - fix: clear() removes every scan page and keys without a ttl no longer expire by @jaredwray in #2161 - cloudflare-kv - fix: keys with a ttl of 60 seconds or less are removed by KV by @jaredwray in #2162 - mongo - fix: GridFS reads the newest value and delete removes every revision by @jaredwray in #2163 - mono - fix: a clearExpiredInterval over 24.8 days no longer runs cleanup every millisecond by @jaredwray in #2164 - mysql - fix: tables get a primary key on (namespace, id) by @jaredwray in #2165 - valkey - fix: clear, iterator and useSets work in cluster mode by @jaredwray in #2166 - redis - fix: createKeyvNonBlocking stops reconnecting, and failed connects stop adding listeners by @jaredwray in #2167 - mono - fix: fractional TTLs no longer fail writes, and postgres disconnect releases the pool it connected with by @jaredwray in #2168 - mono - docs: drop the removed useKeyPrefix option from dynamo and cloudflare-kv examples by @jaredwray in #2169 - mysql - fix: Primary key migration keeps owner keys, replaces prefix keys, and finds hidden generated keys by @jaredwray in #2170 - etcd - fix: setMany reports failed writes as false by @jaredwray in #2172 - etcd - fix: Without a namespace, clear() and iterator() only touch Keyv's own entries by @jaredwray in #2173 - mono - feat: Add keyv-migrate agent skill at keyv.org/skills/migrate and fix stale v6 docs by @jaredwray in #2171 - memcache - fix: Keys memcached can't store now work, and rejected writes return false by @jaredwray in #2174 - mono - docs: Correct old delete results and etcd clear() in the migration skill by @jaredwray in #2175 - keyv - fix: writes fail with an error when encryption is set without serialization by @jaredwray in #2176 - skills - docs: bound the Redis "every key" range to @keyv/redis 2.7 through 3.0 by @jaredwray in #2177 - bigmap - fix: Changing storeSize or storeHashFunction keeps every entry by @jaredwray in #2178 - memcache - fix: clear() only removes the store's own entries by @jaredwray in #2179 - redis - fix: clear() and iterator() match the namespace literally by @jaredwray in #2185 - keyv - fix: a namespaced clear() fails instead of wiping a store it can't scope by @jaredwray in #2186 - mono - fix: authenticated ciphers only, bridge setMany() results, serializer \_\_proto\_\_ by @jaredwray in #2187 - mono - docs: use a random secret as the encryption key, or derive one with PBKDF2 by @jaredwray in #2188 - mono - feat: `namespaceSeparator` on every adapter, defaulting to `::` by @jaredwray in #2189 - mono - docs: Amazon RDS for PostgreSQL and Redis Cloud how-tos by @jaredwray in #2194 - mono - chore: Release v6.1.0 by @jaredwray in #2192 - …plus 51 dependency, tooling, CI, test and repo-maintenance PRs; see the full diff. **Full diff:** [https://github.com/jaredwray/keyv/compare/v6.0.0](https://github.com/jaredwray/keyv/compare/v6.0.0)-rc.1...v6.1.0 ### v6.0.0-rc.1 URL: https://keyv.org/changelog/v6-0-0-rc-1 Date: August 3, 2026 Tag: Release ## keyv v6.0.0-rc.1 — 2026-08-03 Promote 6.0 to release candidate: Cloudflare KV adapter, MySQL fixes, and a full dependency refresh. _All published `@keyv/*` adapters release in lockstep at this version. `@keyv/website` is private and not published._ ### ⚠ BREAKING CHANGES - **mysql:** keys are now stored as `VARBINARY` (6e519b4, #2015; f579073, #2016) Migration: `@keyv/mysql` tables created under `6.0.0-beta.4` use the previous key column type. Recreate the keyv table, or `ALTER` the key column to `VARBINARY`, before upgrading. - **keyv:** `checkExpired` now defaults to `true` (f067213, #1984) Migration: expired keys are now checked and cleared by default. Pass `checkExpired: false` to restore the previous behavior. - **keyv:** removed the namespace `removeKeyPrefix` behavior for v6 (73fd79b, #2013) Migration: keys are no longer stripped of their namespace prefix on read. If you relied on the stripped form, read the full namespaced key. ### Features - add Cloudflare Workers KV storage adapter (e004467, #1985) ```js import { createKeyv } from "@keyv/cloudflare-kv"; // REST mode — from any Node.js process const keyv = createKeyv({ mode: "rest", accountId: process.env.CF_ACCOUNT_ID, namespaceId: process.env.CF_KV_NAMESPACE_ID, apiToken: process.env.CF_API_TOKEN, }); // Or "bind" mode inside a Worker: createKeyv({ kvNamespace: env.MY_KV }) ``` - mysql: move to async config changes (b775072, #2018) - keyv: add the built-in adapters to the docs (2e03276, #1983) - mysql: add docs (e07dc4c, #2019) ### Bug Fixes - mysql: isolate pooled connection lifecycles (86b61c8, #2012) - mysql: scheduled cleanup firing (97fa359, #2017) - mysql: deleting expired keys sometimes fails (6e5aff2, #2014) - mysql: resolve TypeScript errors (dc563b6, #2011) ### Documentation - add keyv-s3fifo to third-party storage adapters (fb420e7, #2020) ### Internal - refactor: add `KeyvAny`/`KeyvAnyArray` types and replace explicit `any` (49ed583, #2010) - 34 dependency and tooling upgrades across the monorepo — highlights: TypeScript 6→7, pnpm 11.5→11.18, better-sqlite3 12→13 (N-API, drops `prebuild-install`), mongodb 7.4→7.5, mysql2 3.22→3.23, iovalkey 0.3→0.4, `@redis/client` 6.0→6.1, hookified 3.0.1→3.0.2, `actions/setup-node` v6→v7, and the Node engines floor raised to ≥ 22.19.0. Full inventory below. ### Contributors - @jaredwray (47) - @BJS-kr (1) ### Full List of Changes - keyv - feat: adding in the built in adapters to docs by @jaredwray in #1983 - keyv - fix: moving checkExpired to default to true by @jaredwray in #1984 - cloudflare-kv - feat: Add Cloudflare Workers KV storage adapter by @jaredwray in #1985 - mono - chore: upgrade code quality dependencies by @jaredwray in #1986 - mono - chore: upgrade TypeScript and build tooling by @jaredwray in #1987 - mono - chore: upgrade js-yaml to v5 (breaking) by @jaredwray in #1988 - keyv - chore: upgrade keyv-file by @jaredwray in #1989 - mono - chore: upgrade GitHub Actions (breaking) by @jaredwray in #1990 - dynamo - chore: upgrade AWS SDK dependencies by @jaredwray in #1991 - mongo - chore: upgrade mongodb by @jaredwray in #1992 - postgres - chore: upgrade pg by @jaredwray in #1993 - sqlite - chore: upgrade better-sqlite3 by @jaredwray in #1994 - redis - chore: upgrade @redis/client by @jaredwray in #1995 - memcache - chore: upgrade memcache by @jaredwray in #1996 - mono - chore: upgrade hookified by @jaredwray in #1997 - serialize - chore: upgrade msgpackr by @jaredwray in #1998 - test-suite - chore: upgrade bignumber.js by @jaredwray in #1999 - bigmap - chore: upgrade hashery (breaking) by @jaredwray in #2000 - compress-gzip - chore: upgrade pako (breaking) by @jaredwray in #2001 - mono - refactor: add KeyvAny/KeyvAnyArray types and replace explicit any by @jaredwray in #2010 - mysql - fix: resolve TypeScript errors by @jaredwray in #2011 - mysql - fix: isolate pooled connection lifecycles by @jaredwray in #2012 - fix: removing the namespace removeKeyPrefix with v6 by @jaredwray in #2013 - mysql - fix: deleting expired keys sometimes fail by @jaredwray in #2014 - mysql - fix: moving to VARBINARY for key by @jaredwray in #2015 - mysql - fix: moving to varbinary for key (fixes) by @jaredwray in #2016 - mysql - fix: scheduled cleanup firing by @jaredwray in #2017 - mysql - feat: moving to async config changes by @jaredwray in #2018 - mysql - feat: adding in docs by @jaredwray in #2019 - docs: add keyv-s3fifo to third-party storage adapters by @BJS-kr in #2020 - mono - chore: upgrade code quality dependencies by @jaredwray in #2021 - mono - chore: upgrade TypeScript and build tooling by @jaredwray in #2022 - mono - chore: upgrade pnpm to 11.18.0 by @jaredwray in #2023 - mono - chore: upgrade GitHub Actions by @jaredwray in #2024 - dynamo - chore: upgrade AWS SDK DynamoDB dependencies by @jaredwray in #2025 - redis - chore: upgrade @redis/client to 6.1.0 by @jaredwray in #2026 - mongo - chore: upgrade mongodb to 7.5.0 by @jaredwray in #2027 - mysql - chore: upgrade mysql2 to 3.23.2 by @jaredwray in #2028 - valkey - chore: upgrade iovalkey to 0.4.0 by @jaredwray in #2029 - memcache - chore: upgrade memcache to 1.9.0 by @jaredwray in #2030 - mono - chore: raise Node engines floor to 22.19.0 by @jaredwray in #2031 - sqlite - chore: upgrade better-sqlite3 to 13.0.2 by @jaredwray in #2032 - mono - chore: upgrade hookified to 3.0.2 by @jaredwray in #2033 - bigmap - chore: upgrade hashery to 3.0.1 by @jaredwray in #2034 - test-suite - chore: upgrade bignumber.js to 11.1.5 by @jaredwray in #2035 - mono - chore: upgrade lz4-napi to 2.9.1 by @jaredwray in #2036 - serialize - chore: upgrade msgpackr to 2.0.5 by @jaredwray in #2037 - compress - chore: upgrade pako to 3.0.1 by @jaredwray in #2038 **Full diff:** [https://github.com/jaredwray/keyv/compare/v6.0.0](https://github.com/jaredwray/keyv/compare/v6.0.0)-beta.4...v6.0.0-rc.1 ### v6.0.0-beta.4 URL: https://keyv.org/changelog/v6-0-0-beta-4 Date: June 18, 2026 Tag: Release ## Keyv v6.0.0-beta.4 — 2026-06-18 Finalize the v6 storage-adapter API (ttl → expires) and complete the cross-adapter code/test review. ### ⚠ BREAKING CHANGES - Storage adapters now use `expires` (absolute epoch-ms timestamp) instead of a relative `ttl`. (da9c08f, #1981) Migration: if you call a storage adapter directly or implement a custom one, read the absolute `expires` value from the entry envelope instead of accepting a `ttl` argument. The `Keyv` core API is unchanged — it continues to derive `expires` from the value envelope, so typical `keyv.set(key, value, ttl)` usage is unaffected. ### Features - **bigmap:** wire up Hookified events — `BigMap` now emits `SET`, `DELETE`, and `CLEAR` via the new `BigMapEvents` enum. (b88d03f, #1977) ```ts import { BigMap, BigMapEvents } from '@keyv/bigmap'; const map = new BigMap(); map.on(BigMapEvents.SET, (key, value) => console.log('set', key, value)); map.on(BigMapEvents.DELETE, (key) => console.log('deleted', key)); map.set('a', '1'); // → "set a 1" map.delete('a'); // → "deleted a" ``` Also renames the exported `MapInterfacee` type to `MapInterface` (typo fix — safe within the v6 beta). ### Bug Fixes - **etcd:** support the grpc-gateway v2 error format for etcd 3.6 compatibility. (dcb64bd, #1964) - **dynamo:** strip the namespace prefix in the iterator and align tests/docs. (75198aa, #1965) - **etcd:** return `undefined` for missing values and align tests/docs. (1e84580, #1966) - **mysql:** return `undefined` instead of `null`, guard `getMany`, and align tests/docs. (d76926b, #1969) ### Documentation - **keyv:** fix README API accuracy and strengthen the code/test review. (685bc77, #1979) - **keyv:** add a jsDelivr badge to the README. (418ce7a, #1963) ### Internal - **dynamo:** code clean up and minor fixes. (9048a87, #1970) - **etcd:** code clean up and documentation. (aed5638, #1972) - **postgres:** code/test review for `@keyv/postgres`. (9fa6847, #1971) - **redis:** full code and test review cleanup. (480a560, #1974) - **memcache:** add an error handler. (394e254, #1973) - **memcache:** uniform test suite, fix namespace docs, validate API. (95612fc, #1967) - **mongo:** uniform test suite, fix README API docs. (0240400, #1968) - **mongo:** documentation and fixes (includes #1980 review follow-ups). (f31850d, #1976) - **sqlite:** full code and test review cleanup. (8539cfd, #1975) - **valkey:** full code and test review. (e8a3ffa, #1978) ### Contributors - @jaredwray (18) ### Full List of Changes - feat: adding in jsDelivr badge for Keyv by @jaredwray in #1963 - etcd - fix: support grpc-gateway v2 error format for etcd 3.6 compatibility by @jaredwray in #1964 - dynamo - fix: strip namespace prefix in iterator and align tests/docs by @jaredwray in #1965 - etcd - fix: return undefined for missing values and align tests/docs by @jaredwray in #1966 - memcache - test: uniform test suite, fix namespace docs, validate API by @jaredwray in #1967 - mongo - test: uniform test suite, fix README API docs by @jaredwray in #1968 - mysql - fix: return undefined not null, guard getMany, and align tests/docs by @jaredwray in #1969 - dynamo - chore: code clean up and minor fixes by @jaredwray in #1970 - etcd - chore: code clean up and documentation by @jaredwray in #1972 - postgres - refactor: code/test review for @keyv/postgres by @jaredwray in #1971 - redis - chore: full code and test review cleanup by @jaredwray in #1974 - memcache - chore: adding in error handler by @jaredwray in #1973 - sqlite - refactor: full code and test review cleanup by @jaredwray in #1975 - keyv - docs: fix README API accuracy and strengthen code/test review by @jaredwray in #1979 - valkey - refactor: full code and test review by @jaredwray in #1978 - bigmap - feat: wire up hookified events and complete code/test review by @jaredwray in #1977 - mongo - chore: documentation and fixes by @jaredwray in #1976 - keyv (breaking) - storage adapters now only use expires instead of ttl by @jaredwray in #1981 **Full diff:** [https://github.com/jaredwray/keyv/compare/v6.0.0](https://github.com/jaredwray/keyv/compare/v6.0.0)-beta.3...v6.0.0-beta.4 ### v6.0.0-beta.3 URL: https://keyv.org/changelog/v6-0-0-beta-3 Date: June 11, 2026 Tag: Release # Keyv v6.0.0-beta.3 This release rolls up the entire v6 beta cycle — everything merged since `v6.0.0-alpha.3`. v6 is a major, ground-up modernization of Keyv: a leaner core, a new raw-data API, first-class capability detection, telemetry, two new encryption packages, a dependency-free etcd adapter, and a wave of breaking dependency upgrades across the monorepo. > **Heads up:** v6 contains a number of breaking changes vs. v5. If you are upgrading from v5, read the [v5 → v6 migration guide](https://github.com/jaredwray/keyv/blob/main/website/site/docs/migration.md) alongside these notes. --- ## Highlights - 🔐 **Two new encryption packages** — `@keyv/encrypt-node` (Node.js `crypto`) and `@keyv/encrypt-web` (Web Crypto API), with a shared wire format so they're cross-compatible. - 🧩 **Raw data API** — `getRaw` / `getManyRaw` / `setRaw` / `setManyRaw` for working directly with the stored `{ value, expires }` envelope. - 🔎 **Capability detection** — `detectKeyv`, `detectKeyvStorage`, `detectKeyvCompression`, `detectKeyvSerialization`, `detectKeyvEncryption` helpers. - 📊 **Stats / telemetry overhaul** — aggregate counters plus LRU-bounded per-key frequency maps. - 🧼 **Key sanitization** — opt-in protection against SQL/Mongo/path-traversal/control-character injection in keys and namespaces. - 🪝 **Hookified everywhere** — unified events + pre/post hooks across the core and every adapter, now including `setMany`, `deleteMany`, `clear`, and `disconnect`. - 🌐 **Dependency-free etcd adapter** — talks to etcd v3 over its HTTP/JSON gateway via an in-house client (no `etcd3`). - ⚙️ **Optional serialization** and **no key-prefixing in core** for a smaller, faster default path. - 🏗️ **Build & toolchain modernization** — moved to `tsdown`, TypeScript 6, and a refreshed release pipeline (OIDC publishing). - 📦 **Major dependency upgrades** across Redis, MongoDB, MySQL, Postgres, DynamoDB, msgpackr, hookified, hashery, and more. --- ## ⚠️ Breaking Changes ### Core - **`StoredData` and `StoredDataRaw` types removed.** Use the `KeyvValue` envelope (`{ value, expires? }`) and the new raw API instead. (#1929) - **Keys are no longer prefixed in core.** Namespacing/prefixing is now handled by the storage adapters that need it, not the core. (#1899) - **`get` no longer checks expiry by default.** Expiration is evaluated lazily/where appropriate to keep the hot path fast; expired entries still resolve to `undefined` through the normal read paths. To re-enable core-level expiry checks, set the `checkExpired: true` option. (#1923) - **Moved to [Hookified](https://github.com/jaredwray/hookified) for events + hooks.** Replaces the old `EventEmitter` base across core and adapters. (#1900) - **`.set()` now returns a boolean** instead of the instance. (#1904) - **Iterator API simplified** and various method signatures cleaned up. (#1902) - **`setRaw` / `setManyRaw` no longer take a `ttl` argument** — set `expires` on the value envelope instead. (#1905) - **`opts` removed from `KeyvStorageAdapter`** and the `opts` property removed from the `Keyv` class. (#1906) ### Adapters & tooling (dependency bumps that change minimums) - **`@redis/client` upgraded to v6** (breaking). (#1954) - **hookified upgraded to v3** (breaking) across the monorepo. (#1957) - **hashery upgraded to v2** in BigMap (breaking). (#1956) - **msgpackr upgraded to v2** in `@keyv/serialize-msgpackr` (breaking). (#1958) - **bignumber.js upgraded to v11** in the test-suite (breaking). (#1955) - **docula upgraded to v2** for the website (breaking). (#1947) - **Code-quality deps, GitHub Actions, and build tooling** upgraded (some breaking minimum versions). (#1944, #1946, #1945) - **TypeScript 6** is now used to build the monorepo. (#1933) - **test-suite v6 overhaul** — compliance tests rewritten for the v6 API. If you maintain a third-party adapter against `@keyv/test-suite`, expect changes. (#1931) --- ## 🔐 New: Encryption Packages Two new adapters let you encrypt values transparently. They share a wire format, so data written by one can be read by the other (same key + algorithm). ### `@keyv/encrypt-node` — Node.js `crypto` Supports AES-GCM (default), AES-CCM, ChaCha20-Poly1305, AES-CBC, and any cipher available in your Node install. (#1927) ```js import Keyv from 'keyv'; import KeyvEncryptNode from '@keyv/encrypt-node'; const encryption = new KeyvEncryptNode({ key: 'your-secret-key' }); const keyv = new Keyv({ encryption }); await keyv.set('foo', 'bar'); const value = await keyv.get('foo'); // 'bar' (decrypted automatically) ``` ```js // Pick an algorithm and output encoding const encryption = new KeyvEncryptNode({ key: 'your-secret-key', algorithm: 'chacha20-poly1305', encoding: 'hex', }); ``` ### `@keyv/encrypt-web` — Web Crypto API Works in browsers, Deno, Cloudflare Workers, and Node.js 18+ with no Node-specific dependencies. Supports AES-GCM (recommended) and AES-CBC. (#1928) ```js import Keyv from 'keyv'; import KeyvEncryptWeb from '@keyv/encrypt-web'; const encryption = new KeyvEncryptWeb({ key: 'your-secret-key' }); const keyv = new Keyv({ encryption }); await keyv.set('foo', 'bar'); const value = await keyv.get('foo'); // 'bar' ``` **Cross-compatibility wire format** (same for both packages): - **AES-GCM:** `base64([IV (12 bytes) || AuthTag (16 bytes) || Ciphertext])` - **AES-CBC:** `base64([IV (16 bytes) || Ciphertext])` --- ## 🧩 Core: Raw Data API Work directly with the stored envelope (`{ value, expires? }`) — useful for replication, cache warming, and moving data between stores. (#1897, #1929) ```js import Keyv from 'keyv'; const keyv = new Keyv(); // Write a raw envelope with an absolute expiry timestamp await keyv.setRaw('foo', { value: 'bar', expires: Date.now() + 60_000 }); // No expiry await keyv.setRaw('foo', { value: 'bar' }); // Read the raw envelope back const raw = await keyv.getRaw('foo'); // { value: 'bar', expires: 1234567890 } // Copy between instances without unwrapping/rewrapping if (raw) { await other.setRaw('foo', raw); } // Batch variants await keyv.setManyRaw([ { key: 'a', value: { value: 1 } }, { key: 'b', value: { value: 2, expires: Date.now() + 60_000 } }, ]); const many = await keyv.getManyRaw(['a', 'b']); ``` > The store-level TTL is derived automatically from `value.expires`, so you no longer pass a separate `ttl` to the raw setters. --- ## 🔎 Core: Capability Detection New helpers report exactly which parts of an interface an object implements. Each returns a `compatible` flag — `true` only when the full interface is satisfied — plus a `methods` map describing whether each method `exists` and its `methodType` (`"sync"` / `"async"` / `"none"`). (#1909, #1930) ```ts import Keyv, { detectKeyv, detectKeyvStorage, detectKeyvCompression, detectKeyvSerialization, detectKeyvEncryption, } from 'keyv'; detectKeyv(new Keyv()).compatible; // true (only when ALL capabilities are present) detectKeyv(new Map()).compatible; // false — but methods.get.exists is still true // Storage detection reports the detected store type plus sync/async per method const r = detectKeyvStorage(new Map()); r.compatible; // true r.store; // "mapLike" ("keyvStorage" | "mapLike" | "asyncMap" | "none") r.methods.get.methodType; // "sync" detectKeyvSerialization(JSON).compatible; // true detectKeyvCompression({ compress: d => d, decompress: d => d }).compatible; // true detectKeyvEncryption({ encrypt: d => d, decrypt: d => d }).compatible; // true ``` --- ## 📊 Core: Stats / Telemetry Opt-in statistics with aggregate counters and LRU-bounded per-key frequency maps. (#1912) ```js const keyv = new Keyv({ stats: true }); await keyv.set('foo', 'bar'); await keyv.get('foo'); // hit await keyv.get('nonexistent'); // miss await keyv.delete('foo'); keyv.stats.hits; // 1 keyv.stats.misses; // 1 keyv.stats.sets; // 1 keyv.stats.deletes; // 1 // Per-key frequency (each map capped at maxEntries, default 1000) keyv.stats.hitKeys.get('foo'); // 1 keyv.stats.missKeys.get('nonexistent'); // 1 keyv.stats.reset(); // clears counters and maps keyv.stats.enabled = false; // disable at runtime (auto-unsubscribes) ``` --- ## 🧼 Core: Key Sanitization Opt-in detection that strips dangerous *patterns* (not harmless characters) from keys and namespaces — guarding against SQL injection, MongoDB operator injection, path traversal, and control-character/CRLF attacks. Results are LRU-cached for speed. ```js const keyv = new Keyv({ sanitize: true }); // or fine-grained: const keyv2 = new Keyv({ sanitize: { sql: true, mongo: true, path: true, escape: true } }); ``` Applied to every key-accepting method (`get`, `set`, `delete`, `has`, the `*Many` variants, and the raw variants), plus namespaces at construction and on the `namespace` setter. --- ## 🪝 Core: Events, Hooks & Error Handling - **Hooks for more operations** — added pre/post hooks for `setMany`, `deleteMany`, `clear`, and `disconnect`, in addition to the existing single-key hooks. (#1918, #1924) - **`throwOnErrors`** — make operations throw instead of emitting `'error'`, so you can `try/catch` (great with `@keyv/redis` connection handling). (#1910) ```js import Keyv from 'keyv'; import KeyvRedis from '@keyv/redis'; const keyv = new Keyv({ store: new KeyvRedis('redis://localhost:6379'), throwOnErrors: true }); try { await keyv.set('foo', 'bar'); } catch (error) { // handle connection/timeout errors yourself } ``` - **Key prefixing moved to adapters.** Prefixing/namespacing is now handled by the storage adapters that need it rather than the core. (#1899) - **Encode/decode now propagate errors** instead of swallowing them, and several stats/telemetry edge cases were fixed (no `STAT_SET` on empty set, `setRaw` telemetry, `getManyRaw` dead code). (#1922, #1920, #1921, #1919) --- ## ⚙️ Core: Optional Serialization Serialization is now optional. Disable it to store raw objects (ideal for the default in-memory `Map`, where string conversion isn't needed). (#1898) ```js const keyv = new Keyv({ serialization: false }); ``` Pipeline ordering when serialization/compression are configured: - **On set:** serialize (optional) → compress (optional) → store - **On get:** store → decompress (optional) → parse (optional) → value If compression is configured without a serializer, Keyv falls back to `JSON.stringify`/`JSON.parse` since compression needs string input. --- ## 🌐 Storage Adapters - **etcd: dependency-free client.** `@keyv/etcd` now talks to etcd v3 directly over its HTTP/JSON gateway via a small in-house client — the `etcd3` dependency is gone. Requires etcd v3+ and Node.js 20+ (uses global `fetch` / `AbortSignal.timeout`). TTL via etcd leases, namespace isolation, async iterator, and `setMany`/`getMany`/`deleteMany`/`hasMany` are all supported. (#1936, #1893) - **DynamoDB:** added `disconnect()` and `iterator()`; moved to v6 requirements with namespace support; TTL now stored in milliseconds; internal `isExpired` rename. AWS SDK dependencies upgraded. (#1914, #1894, #1934, #1935, #1948) - **Compression adapters** moved to the `KeyvCompressionAdapter` standard. (#1901) - **BigMap:** optimized hash function and hot-path performance. (#1915) - **Adapter dependency upgrades:** MongoDB (#1951), MySQL/mysql2 (#1952), Postgres/pg (#1953), memcache (#1950). --- ## 🏗️ Build, Tooling & Release - Moved the monorepo build to **`tsdown`**. (#1926) - Upgraded to **TypeScript 6**. (#1933) - New **release management with OIDC** and multi-version publishing, plus a hardened release pipeline. (#1942) - **test-suite:** v6 compliance overhaul, and TTL tests can now specify milliseconds or seconds. (#1931, #1949) - **Stability:** hardened service-backed test suites against timing flakes. (#1960) - **Docs/links:** fixed `main`-vs-`master` links and broken logo links in package READMEs. (#1939, #1943) --- ## 📦 Notable Dependency Upgrades | Package | Change | PR | |---|---|---| | `@redis/client` | → v6 (breaking) | #1954 | | `hookified` | → v3 (breaking) | #1957 | | `hashery` (BigMap) | → v2 (breaking) | #1956 | | `msgpackr` (serialize) | → v2 (breaking) | #1958 | | `bignumber.js` (test-suite) | → v11 (breaking) | #1955 | | `docula` (website) | → v2 (breaking) | #1947 | | `mongodb` | upgraded | #1951 | | `mysql2` | upgraded | #1952 | | `pg` | upgraded | #1953 | | AWS SDK (dynamo) | upgraded | #1948 | | memcache | upgraded | #1950 | | TypeScript | → v6 | #1933 | | GitHub Actions | upgraded (breaking) | #1946 | --- ## Full Changelog by Release ### Since `v6.0.0-beta.1` - `mono` - test: harden service-backed suites against timing flakes (#1960) - `serialize-msgpackr` - chore: upgrade msgpackr to v2 (breaking) (#1958) - `mono` - chore: upgrade hookified to v3 (breaking) (#1957) - `bigmap` - chore: upgrade hashery to v2 (breaking) (#1956) - `test-suite` - chore: upgrade bignumber.js to v11 (breaking) (#1955) - `redis` - chore: upgrade @redis/client to v6 (breaking) (#1954) - `postgres` - chore: upgrade pg (#1953) - `mysql` - chore: upgrade mysql2 (#1952) - `mongo` - chore: upgrade mongodb (#1951) - `memcache` - chore: upgrade memcache (#1950) - `dynamo` - chore: upgrade AWS SDK dependencies (#1948) - `test-suite` - feat: allow storage TTL tests to specify milliseconds or seconds (#1949) - `website` - chore: upgrade docula to v2 (breaking) (#1947) - `mono` - chore: upgrade GitHub Actions (breaking) (#1946) - `mono` - chore: upgrade TypeScript and build tooling (#1945) - `mono` - chore: upgrade code quality dependencies (breaking) (#1944) - `mono` - docs: fix broken keyv logo link in package READMEs (#1943) - `feat`: release management with OIDC and multi versions (#1942) - `keyv` - fix: `main` branch used instead of `master` for links (#1939) - `etcd` - feat: replace etcd3 dependency with built-in HTTP/JSON client (#1936) - `dynamo` - fix: renaming internal isExpired (#1935) - `dynamo` - fix: storing ttl in ms now also (#1934) - `mono` - chore: upgrading to TypeScript 6 (#1933) ### `v6.0.0-beta.1` - `keyv` - feat (breaking) stats / telemetry overhaul (#1912) - `keyv` - feat: (breaking) memory adapter, bridge adapter, keyv overhaul (#1913) - `bigmap` - feat: optimize BigMap hash function and hot path performance (#1915) - `dynamo` - feat: add disconnect and iterator methods to KeyvDynamo (#1914) - `keyv` - fix: handling has and hasMany better (#1916) - `keyv` - fix: adding in decode expiring to has (#1917) - `keyv` - feat: adding hooks for setMany and deleteMany (#1918) - `keyv` - fix: dead code on getManyRaw (#1919) - `keyv` - fix: on set with no result do not send telemetry STAT_SET (#1920) - `keyv` - fix: telemetry issue on setRaw (#1921) - `keyv` - fix: having encode / decode propagate errors (#1922) - `keyv` - feat: (breaking) by default keyv no longer checks expires (#1923) - `keyv` - feat: adding in hooks for clear and disconnect (#1924) - `keyv` - fix: minor bug fixes on memory, ttl, etc (#1925) - `mono` - feat: moving to tsdown for build (#1926) - `encryption-node` - feat: add Node.js encryption adapter for Keyv (#1927) - `encrypt-web` - feat: adding new web crypto module (#1928) - `keyv` - feat: (breaking) removing StoredData and StoredDataRaw types (#1929) - `keyv` - feat: enhancing capabilities (#1930) - `test-suite` - feat (breaking) overhaul based on v6 changes (#1931) ### `v6.0.0-alpha.4` - `keyv` - feat: (breaking) moving to Hookified (#1900) - `compression` - feat: moving to KeyvCompressionAdapter standard (#1901) - `keyv` - feat: (breaking) api changes and iterator simplification (#1902) - `keyv` - feat: moving storage setMany to use KeyvEntry (#1903) - `keyv` - feat: (breaking) moving to boolean return on set (#1904) - `keyv` - fix: (breaking) setRaw and setMany raw do not need ttl param (#1905) - `keyv` - feat: (breaking) removing opts from KeyvStorageAdapter (#1906) - `keyv` - feat: browser compatibility (#1907) - `keyv` - fix: updating checks for browser tests (#1908) - `feat`: updating capability helper functions (#1909) - `keyv` - feat: clean up of code with fixes and helpers (#1910) **Full Changelog**: [https://github.com/jaredwray/keyv/compare/v6.0.0](https://github.com/jaredwray/keyv/compare/v6.0.0)-alpha.3...v6.0.0-beta.3 ### v6.0.0-beta.1 URL: https://keyv.org/changelog/v6-0-0-beta-1 Date: April 1, 2026 Tag: Release ## What's Changed * keyv - feat (breaking) stats / telemetry overhaul by @jaredwray in [https://github.com/jaredwray/keyv/pull/1912](https://github.com/jaredwray/keyv/pull/1912) * keyv - feat: (breaking) memory adapter, bridge adapter, keyv overhaul by @jaredwray in [https://github.com/jaredwray/keyv/pull/1913](https://github.com/jaredwray/keyv/pull/1913) * bigmap - feat: Optimize BigMap hash function and hot path performance by @jaredwray in [https://github.com/jaredwray/keyv/pull/1915](https://github.com/jaredwray/keyv/pull/1915) * dynamo - feat: Add disconnect and iterator methods to KeyvDynamo by @jaredwray in [https://github.com/jaredwray/keyv/pull/1914](https://github.com/jaredwray/keyv/pull/1914) * keyv - fix: handling has and hasMany better by @jaredwray in [https://github.com/jaredwray/keyv/pull/1916](https://github.com/jaredwray/keyv/pull/1916) * keyv - fix: adding in decode expiring to has by @jaredwray in [https://github.com/jaredwray/keyv/pull/1917](https://github.com/jaredwray/keyv/pull/1917) * keyv - feat: adding hooks for setMany and deleteMany by @jaredwray in [https://github.com/jaredwray/keyv/pull/1918](https://github.com/jaredwray/keyv/pull/1918) * keyv - fix: dead code on getManyRaw by @jaredwray in [https://github.com/jaredwray/keyv/pull/1919](https://github.com/jaredwray/keyv/pull/1919) * keyv - fix: on set with no result do not send telemetry STAT_SET by @jaredwray in [https://github.com/jaredwray/keyv/pull/1920](https://github.com/jaredwray/keyv/pull/1920) * keyv - fix: telemetry issue on setRaw by @jaredwray in [https://github.com/jaredwray/keyv/pull/1921](https://github.com/jaredwray/keyv/pull/1921) * keyv - fix: having encode / decode propegate errors by @jaredwray in [https://github.com/jaredwray/keyv/pull/1922](https://github.com/jaredwray/keyv/pull/1922) * keyv - feat: (breaking) by default keyv no longer checks expires by @jaredwray in [https://github.com/jaredwray/keyv/pull/1923](https://github.com/jaredwray/keyv/pull/1923) * keyv - feat: adding in hooks for clear and disconnect by @jaredwray in [https://github.com/jaredwray/keyv/pull/1924](https://github.com/jaredwray/keyv/pull/1924) * keyv - fix: minor bug fixes on memory, ttl, etc by @jaredwray in [https://github.com/jaredwray/keyv/pull/1925](https://github.com/jaredwray/keyv/pull/1925) * mono - feat: moving to tsdown for build by @jaredwray in [https://github.com/jaredwray/keyv/pull/1926](https://github.com/jaredwray/keyv/pull/1926) * encryption-node - feat: Add Node.js encryption adapter for Keyv by @jaredwray in [https://github.com/jaredwray/keyv/pull/1927](https://github.com/jaredwray/keyv/pull/1927) * encrypt-web - feat: adding new web crypto module by @jaredwray in [https://github.com/jaredwray/keyv/pull/1928](https://github.com/jaredwray/keyv/pull/1928) * keyv - feat: (breaking) removing StoredData and StoredDataRaw types by @jaredwray in [https://github.com/jaredwray/keyv/pull/1929](https://github.com/jaredwray/keyv/pull/1929) * keyv - feat: enhancing capabilities by @jaredwray in [https://github.com/jaredwray/keyv/pull/1930](https://github.com/jaredwray/keyv/pull/1930) * test-suite - feat (breaking) overhaul based on v6 changes by @jaredwray in [https://github.com/jaredwray/keyv/pull/1931](https://github.com/jaredwray/keyv/pull/1931) **Full Changelog**: [https://github.com/jaredwray/keyv/compare/v6.0.0](https://github.com/jaredwray/keyv/compare/v6.0.0)-alpha.4...v6.0.0-beta.1 ### v6.0.0-alpha.4 URL: https://keyv.org/changelog/v6-0-0-alpha-4 Date: March 27, 2026 Tag: Release ## What's Changed * keyv - feat: (breaking) moving to Hookified by @jaredwray in [https://github.com/jaredwray/keyv/pull/1900](https://github.com/jaredwray/keyv/pull/1900) * compression - feat: moving to KeyvCompressionAdapter standard by @jaredwray in [https://github.com/jaredwray/keyv/pull/1901](https://github.com/jaredwray/keyv/pull/1901) * keyv - feat: (breaking) api changes and iterator simplification by @jaredwray in [https://github.com/jaredwray/keyv/pull/1902](https://github.com/jaredwray/keyv/pull/1902) * keyv - feat: moving storage setMany to use KeyvEntry by @jaredwray in [https://github.com/jaredwray/keyv/pull/1903](https://github.com/jaredwray/keyv/pull/1903) * keyv - feat: (breaking) moving to boolean return on set by @jaredwray in [https://github.com/jaredwray/keyv/pull/1904](https://github.com/jaredwray/keyv/pull/1904) * keyv - fix: (breaking) setRaw and setMany raw do not need ttl param by @jaredwray in [https://github.com/jaredwray/keyv/pull/1905](https://github.com/jaredwray/keyv/pull/1905) * keyv - feat: (breaking) removing opts from KeyvStorageAdapter by @jaredwray in [https://github.com/jaredwray/keyv/pull/1906](https://github.com/jaredwray/keyv/pull/1906) * keyv - feat: browser compatability by @jaredwray in [https://github.com/jaredwray/keyv/pull/1907](https://github.com/jaredwray/keyv/pull/1907) * keyv - fix: updating checks for browser tests by @jaredwray in [https://github.com/jaredwray/keyv/pull/1908](https://github.com/jaredwray/keyv/pull/1908) * feat: updating capability helper functions by @jaredwray in [https://github.com/jaredwray/keyv/pull/1909](https://github.com/jaredwray/keyv/pull/1909) * keyv - feat: clean up of code with fixes and helpers by @jaredwray in [https://github.com/jaredwray/keyv/pull/1910](https://github.com/jaredwray/keyv/pull/1910) **Full Changelog**: [https://github.com/jaredwray/keyv/compare/v6.0.0](https://github.com/jaredwray/keyv/compare/v6.0.0)-alpha.3...v6.0.0-alpha.4 ### v6.0.0-alpha.3 URL: https://keyv.org/changelog/v6-0-0-alpha-3 Date: March 22, 2026 Tag: Release ## What's Changed * sqlite - feat: moving to namespace and modern adapter methods by @jaredwray in [https://github.com/jaredwray/keyv/pull/1884](https://github.com/jaredwray/keyv/pull/1884) * sqlite - feat: adding in benchmarks by @jaredwray in [https://github.com/jaredwray/keyv/pull/1885](https://github.com/jaredwray/keyv/pull/1885) * sqlite - feat: adding in driver for sqlite3 for legacy by @jaredwray in [https://github.com/jaredwray/keyv/pull/1886](https://github.com/jaredwray/keyv/pull/1886) * sqlite - feat: major clean up of drivers and code base by @jaredwray in [https://github.com/jaredwray/keyv/pull/1887](https://github.com/jaredwray/keyv/pull/1887) * memcache - feat: moving to using faker for unit tests by @jaredwray in [https://github.com/jaredwray/keyv/pull/1888](https://github.com/jaredwray/keyv/pull/1888) * redis - chore: updating tests with faker by @jaredwray in [https://github.com/jaredwray/keyv/pull/1889](https://github.com/jaredwray/keyv/pull/1889) * dynamo - chore: moving to using faker for tests by @jaredwray in [https://github.com/jaredwray/keyv/pull/1890](https://github.com/jaredwray/keyv/pull/1890) * etcd - chore: moving to faker for tests by @jaredwray in [https://github.com/jaredwray/keyv/pull/1891](https://github.com/jaredwray/keyv/pull/1891) * bigmap - feat: moving this to core folder as it Map interface by @jaredwray in [https://github.com/jaredwray/keyv/pull/1892](https://github.com/jaredwray/keyv/pull/1892) * etcd - feat: moving to v6 functionality by @jaredwray in [https://github.com/jaredwray/keyv/pull/1893](https://github.com/jaredwray/keyv/pull/1893) * dynamo - feat: moving to v6 requirements many functions and namespace by @jaredwray in [https://github.com/jaredwray/keyv/pull/1894](https://github.com/jaredwray/keyv/pull/1894) * mono - fix: working to speed up actions by @jaredwray in [https://github.com/jaredwray/keyv/pull/1895](https://github.com/jaredwray/keyv/pull/1895) * memcache - fix: handling namespace support better by @jaredwray in [https://github.com/jaredwray/keyv/pull/1896](https://github.com/jaredwray/keyv/pull/1896) * keyv - feat: adding raw set features by @jaredwray in [https://github.com/jaredwray/keyv/pull/1897](https://github.com/jaredwray/keyv/pull/1897) * keyv - feat: moving to serialization optional by @jaredwray in [https://github.com/jaredwray/keyv/pull/1898](https://github.com/jaredwray/keyv/pull/1898) * keyv - feat: (breaking) no longer supporting key prefixing in core by @jaredwray in [https://github.com/jaredwray/keyv/pull/1899](https://github.com/jaredwray/keyv/pull/1899) **Full Changelog**: [https://github.com/jaredwray/keyv/compare/v6.0.0](https://github.com/jaredwray/keyv/compare/v6.0.0)-alpha.2...v6.0.0-alpha.3 ### v6.0.0-alpha.2 URL: https://keyv.org/changelog/v6-0-0-alpha-2 Date: March 4, 2026 Tag: Release ## What's Changed * valkey - feat: moving options to properties by @jaredwray in [https://github.com/jaredwray/keyv/pull/1876](https://github.com/jaredwray/keyv/pull/1876) * valkey - feat: adding in getMany, setMany, deleteMany, etc by @jaredwray in [https://github.com/jaredwray/keyv/pull/1877](https://github.com/jaredwray/keyv/pull/1877) * valkey - feat: (breaking) moving to client instead of redis name by @jaredwray in [https://github.com/jaredwray/keyv/pull/1878](https://github.com/jaredwray/keyv/pull/1878) * mono - feat: migrating to hookified v2 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1879](https://github.com/jaredwray/keyv/pull/1879) * mysql - chore: moving to faker-js for tests by @jaredwray in [https://github.com/jaredwray/keyv/pull/1881](https://github.com/jaredwray/keyv/pull/1881) * test-suite - feat: moving to using faker-js by @jaredwray in [https://github.com/jaredwray/keyv/pull/1882](https://github.com/jaredwray/keyv/pull/1882) **Full Changelog**: [https://github.com/jaredwray/keyv/compare/6.0.0](https://github.com/jaredwray/keyv/compare/6.0.0)-alpha.1...v6.0.0-alpha.2 ### 6.0.0-alpha.1 URL: https://keyv.org/changelog/6-0-0-alpha-1 Date: February 26, 2026 Tag: Release ## What's Changed * redis - feat: exporting RedisSentinelOptions by @jaredwray in [https://github.com/jaredwray/keyv/pull/1823](https://github.com/jaredwray/keyv/pull/1823) * redis - feat: exporting redis sentinel options with updated documentation by @jaredwray in [https://github.com/jaredwray/keyv/pull/1824](https://github.com/jaredwray/keyv/pull/1824) * mono - chore: upgrading vitest to 4.0.18 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1827](https://github.com/jaredwray/keyv/pull/1827) * keyv - chore: upgrading vitest and supporting modules to latest by @jaredwray in [https://github.com/jaredwray/keyv/pull/1828](https://github.com/jaredwray/keyv/pull/1828) * serialize - chore: upgrading vitest to 4.0.18 and supporting packages by @jaredwray in [https://github.com/jaredwray/keyv/pull/1829](https://github.com/jaredwray/keyv/pull/1829) * sqlite - feat: Add WAL (Write-Ahead Logging) mode support by @snomiao in [https://github.com/jaredwray/keyv/pull/1826](https://github.com/jaredwray/keyv/pull/1826) * compress-brotli - chore: upgrading vitest to 4.0.18 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1830](https://github.com/jaredwray/keyv/pull/1830) * compress-gzip - chore: upgrading vitest to 4.0.18 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1831](https://github.com/jaredwray/keyv/pull/1831) * sqlite - feat: Add warning for WAL mode with in-memory SQLite databases by @jaredwray in [https://github.com/jaredwray/keyv/pull/1832](https://github.com/jaredwray/keyv/pull/1832) * docs: Add v5 to v6 migration guide by @jaredwray in [https://github.com/jaredwray/keyv/pull/1833](https://github.com/jaredwray/keyv/pull/1833) * memcache - docs: Add memjs to memcache migration to v5-to-v6 guide by @jaredwray in [https://github.com/jaredwray/keyv/pull/1836](https://github.com/jaredwray/keyv/pull/1836) * mono - chore: moving keyv to better mono structure by @jaredwray in [https://github.com/jaredwray/keyv/pull/1838](https://github.com/jaredwray/keyv/pull/1838) * mono - feat: adding in version sync across all packages by @jaredwray in [https://github.com/jaredwray/keyv/pull/1839](https://github.com/jaredwray/keyv/pull/1839) * mono - fix: tsconfig moving to esnext by @jaredwray in [https://github.com/jaredwray/keyv/pull/1840](https://github.com/jaredwray/keyv/pull/1840) * compress-brotli - feat: moving to native zlib brotli engine by @jaredwray in [https://github.com/jaredwray/keyv/pull/1841](https://github.com/jaredwray/keyv/pull/1841) * mono - refactor: remove ttlSupport property from all storage adapters by @jaredwray in [https://github.com/jaredwray/keyv/pull/1842](https://github.com/jaredwray/keyv/pull/1842) * keyv - refactor: remove opts property from Keyv class by @jaredwray in [https://github.com/jaredwray/keyv/pull/1843](https://github.com/jaredwray/keyv/pull/1843) * keyv - chore: remove cyclic workspace dependencies by @jaredwray in [https://github.com/jaredwray/keyv/pull/1844](https://github.com/jaredwray/keyv/pull/1844) * keyv - chore: adding tests for code coverage by @jaredwray in [https://github.com/jaredwray/keyv/pull/1845](https://github.com/jaredwray/keyv/pull/1845) * memcache - feat: migrating from memjs to memcache by @jaredwray in [https://github.com/jaredwray/keyv/pull/1846](https://github.com/jaredwray/keyv/pull/1846) * memcache - feat: adding in createKeyv helper function by @jaredwray in [https://github.com/jaredwray/keyv/pull/1847](https://github.com/jaredwray/keyv/pull/1847) * memcache - fix: removing serialization as not needed by @jaredwray in [https://github.com/jaredwray/keyv/pull/1848](https://github.com/jaredwray/keyv/pull/1848) * memcache - feat: (breaking) moving to nodes based on memcache options by @jaredwray in [https://github.com/jaredwray/keyv/pull/1849](https://github.com/jaredwray/keyv/pull/1849) * memcache - feat: moving eventemitter to hookified by @jaredwray in [https://github.com/jaredwray/keyv/pull/1850](https://github.com/jaredwray/keyv/pull/1850) * memcache - feat: adding constructor documentation by @jaredwray in [https://github.com/jaredwray/keyv/pull/1851](https://github.com/jaredwray/keyv/pull/1851) * keyv - docs: Move Bun Support section lower in README by @jaredwray in [https://github.com/jaredwray/keyv/pull/1853](https://github.com/jaredwray/keyv/pull/1853) * postgres - feat: adding in table of contents by @jaredwray in [https://github.com/jaredwray/keyv/pull/1856](https://github.com/jaredwray/keyv/pull/1856) * postgres - feat: migrating to hookified and advanced functions by @jaredwray in [https://github.com/jaredwray/keyv/pull/1857](https://github.com/jaredwray/keyv/pull/1857) * postgres - feat: moving to properties by @jaredwray in [https://github.com/jaredwray/keyv/pull/1858](https://github.com/jaredwray/keyv/pull/1858) * postgres - feat: adding in native namespace support by @jaredwray in [https://github.com/jaredwray/keyv/pull/1860](https://github.com/jaredwray/keyv/pull/1860) * postgres - feat: better ttl support by @jaredwray in [https://github.com/jaredwray/keyv/pull/1861](https://github.com/jaredwray/keyv/pull/1861) * mysql - chore: adding table of contents by @jaredwray in [https://github.com/jaredwray/keyv/pull/1862](https://github.com/jaredwray/keyv/pull/1862) * mysql - feat: adding setMany and hasMany by @jaredwray in [https://github.com/jaredwray/keyv/pull/1863](https://github.com/jaredwray/keyv/pull/1863) * mysql - feat: moving to native namespacing by @jaredwray in [https://github.com/jaredwray/keyv/pull/1864](https://github.com/jaredwray/keyv/pull/1864) * mysql - feat: removing dialect as no longer needed by @jaredwray in [https://github.com/jaredwray/keyv/pull/1865](https://github.com/jaredwray/keyv/pull/1865) * mysql - feat: (breaking) moving from keySize to keyLength by @jaredwray in [https://github.com/jaredwray/keyv/pull/1866](https://github.com/jaredwray/keyv/pull/1866) * mysql - feat: moving from eventemitter to hookified by @jaredwray in [https://github.com/jaredwray/keyv/pull/1867](https://github.com/jaredwray/keyv/pull/1867) * mysql - feat: createKeyv helper and options cleanup by @jaredwray in [https://github.com/jaredwray/keyv/pull/1868](https://github.com/jaredwray/keyv/pull/1868) * mongo - feat: migrating to hookified from eventemitter by @jaredwray in [https://github.com/jaredwray/keyv/pull/1869](https://github.com/jaredwray/keyv/pull/1869) * mongo - feat: adding createKeyv helper by @jaredwray in [https://github.com/jaredwray/keyv/pull/1871](https://github.com/jaredwray/keyv/pull/1871) * mongo - feat: moving to more robust options and properties by @jaredwray in [https://github.com/jaredwray/keyv/pull/1872](https://github.com/jaredwray/keyv/pull/1872) * mongo - fix: moving gridFS property to read only by @jaredwray in [https://github.com/jaredwray/keyv/pull/1873](https://github.com/jaredwray/keyv/pull/1873) * mongo - feat: adding hasMany and setMany by @jaredwray in [https://github.com/jaredwray/keyv/pull/1874](https://github.com/jaredwray/keyv/pull/1874) * mono - feat: adding in release action by @jaredwray in [https://github.com/jaredwray/keyv/pull/1875](https://github.com/jaredwray/keyv/pull/1875) ## New Contributors * @snomiao made their first contribution in [https://github.com/jaredwray/keyv/pull/1826](https://github.com/jaredwray/keyv/pull/1826) **Full Changelog**: [https://github.com/jaredwray/keyv/compare/2026](https://github.com/jaredwray/keyv/compare/2026)-01-20...6.0.0-alpha.1 ### 2026-01-20 URL: https://keyv.org/changelog/2026-01-20 Date: January 21, 2026 Tag: Release ## What's Changed * website - feat: centralizing third party storage adapters by @jaredwray in [https://github.com/jaredwray/keyv/pull/1789](https://github.com/jaredwray/keyv/pull/1789) * keyv - feat: validating bun support by @jaredwray in [https://github.com/jaredwray/keyv/pull/1790](https://github.com/jaredwray/keyv/pull/1790) * keyv - feat: adding readme on bun support by @jaredwray in [https://github.com/jaredwray/keyv/pull/1792](https://github.com/jaredwray/keyv/pull/1792) * keyv - feat: adding in jsDoc to KeyvGenericStore by @jaredwray in [https://github.com/jaredwray/keyv/pull/1793](https://github.com/jaredwray/keyv/pull/1793) * keyv - feat: implementing generic iterator by @jaredwray in [https://github.com/jaredwray/keyv/pull/1794](https://github.com/jaredwray/keyv/pull/1794) * keyv - chore: moving to nodejs24 tests by @jaredwray in [https://github.com/jaredwray/keyv/pull/1796](https://github.com/jaredwray/keyv/pull/1796) * keyv - feat: adding in integration tests with generic store by @jaredwray in [https://github.com/jaredwray/keyv/pull/1797](https://github.com/jaredwray/keyv/pull/1797) * redis - fix: adding in error event from redis by @jaredwray in [https://github.com/jaredwray/keyv/pull/1799](https://github.com/jaredwray/keyv/pull/1799) * redis - fix: adding in the error from redis client attempt 2 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1801](https://github.com/jaredwray/keyv/pull/1801) * redis - chore: upgrading redis to 4.0.16 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1802](https://github.com/jaredwray/keyv/pull/1802) * redis - chore: upgrading @faker-js/faker to 10.2.0 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1803](https://github.com/jaredwray/keyv/pull/1803) * redis - fix: move client initialization to constructor to prevent connection on module load (#1805) by @jaredwray in [https://github.com/jaredwray/keyv/pull/1806](https://github.com/jaredwray/keyv/pull/1806) * mono - feat: adding in agents.md by @jaredwray in [https://github.com/jaredwray/keyv/pull/1808](https://github.com/jaredwray/keyv/pull/1808) * mysql - chore: upgrading vitest to 4.0.17 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1809](https://github.com/jaredwray/keyv/pull/1809) * mysql - chore: upgrading mysql2 to 3.16.1 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1810](https://github.com/jaredwray/keyv/pull/1810) * mysql - fix: iterator with cursor by @jaredwray in [https://github.com/jaredwray/keyv/pull/1818](https://github.com/jaredwray/keyv/pull/1818) * mysql - fix: documentation and error checking fixes by @jaredwray in [https://github.com/jaredwray/keyv/pull/1819](https://github.com/jaredwray/keyv/pull/1819) * sqlite - chore: upgrading vitest to 4.0.17 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1811](https://github.com/jaredwray/keyv/pull/1811) * postgres - fix: iteration with more resiliency by @jaredwray in [https://github.com/jaredwray/keyv/pull/1784](https://github.com/jaredwray/keyv/pull/1784) * postgres - fix: fixing tests typing issue by @jaredwray in [https://github.com/jaredwray/keyv/pull/1795](https://github.com/jaredwray/keyv/pull/1795) * postgres - chore: upgrading vitest to 4.0.17 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1812](https://github.com/jaredwray/keyv/pull/1812) * postgres - chore: upgrading pg to 8.17.1 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1813](https://github.com/jaredwray/keyv/pull/1813) * postgres - fix: moving to faker for unique tests by @jaredwray in [https://github.com/jaredwray/keyv/pull/1814](https://github.com/jaredwray/keyv/pull/1814) * bigmap - chore: upgrading vitest to 4.0.17 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1815](https://github.com/jaredwray/keyv/pull/1815) * bigmap - chore: upgrading hashery to 1.4.0 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1816](https://github.com/jaredwray/keyv/pull/1816) * bigmap - chore: upgrading hookified to 1.15.0 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1817](https://github.com/jaredwray/keyv/pull/1817) **Full Changelog**: [https://github.com/jaredwray/keyv/compare/2025](https://github.com/jaredwray/keyv/compare/2025)-12-26...2025-01-20 ### 2025-12-26 URL: https://keyv.org/changelog/2025-12-26 Date: December 26, 2025 Tag: Release ## What's Changed * mysql - chore: upgrading @biomejs/biome to 2.3.9 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1763](https://github.com/jaredwray/keyv/pull/1763) * mysql - chore: upgrading vitest to 4.0.15 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1764](https://github.com/jaredwray/keyv/pull/1764) * sqlite - chore: upgrading @biomejs/biome to 2.3.9 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1765](https://github.com/jaredwray/keyv/pull/1765) * sqlite - chore: upgrading vitest to 4.0.15 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1766](https://github.com/jaredwray/keyv/pull/1766) * postgres - chore: upgrading vitest to 4.0.15 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1767](https://github.com/jaredwray/keyv/pull/1767) * bigmap - chore: upgrading vitest to 4.0.15 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1768](https://github.com/jaredwray/keyv/pull/1768) * bigmap - chore: upgrading hashery to 1.3.0 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1769](https://github.com/jaredwray/keyv/pull/1769) * bigmap - chore: upgrading hookified to 1.14.0 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1770](https://github.com/jaredwray/keyv/pull/1770) * keyv - fix: prevent duplicate namespace prefixing and add iterator test for delete stats by @jorovipe97 in [https://github.com/jaredwray/keyv/pull/1772](https://github.com/jaredwray/keyv/pull/1772) * keyv - fix: updating to return when more specific by @jaredwray in [https://github.com/jaredwray/keyv/pull/1773](https://github.com/jaredwray/keyv/pull/1773) * chore: upgrading vitest to 4.0.16 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1774](https://github.com/jaredwray/keyv/pull/1774) * chore: upgrading @biomejs/biome to 2.3.1 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1775](https://github.com/jaredwray/keyv/pull/1775) * etcd - chore: upgrading vitest to 4.0.16 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1776](https://github.com/jaredwray/keyv/pull/1776) * etcd - chore: upgrading @biomejs/biome to 2.3.10 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1777](https://github.com/jaredwray/keyv/pull/1777) * dynamo - chore: upgrading vitest to 4.0.16 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1778](https://github.com/jaredwray/keyv/pull/1778) * dynamo - chore: upgrading @biomejs/biome to 2.3.10 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1779](https://github.com/jaredwray/keyv/pull/1779) * dynamo - chore: upgrading @aws-sdk to 3.958.0 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1780](https://github.com/jaredwray/keyv/pull/1780) * mongo - chore: upgrading vitest to 4.0.16 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1781](https://github.com/jaredwray/keyv/pull/1781) * mongo - chore: upgrading @biomejs/biome to 2.3.10 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1782](https://github.com/jaredwray/keyv/pull/1782) * mongo - chore: upgrading mongodb to 7.0.0 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1783](https://github.com/jaredwray/keyv/pull/1783) ## New Contributors * @jorovipe97 made their first contribution in [https://github.com/jaredwray/keyv/pull/1772](https://github.com/jaredwray/keyv/pull/1772) **Full Changelog**: [https://github.com/jaredwray/keyv/compare/2025](https://github.com/jaredwray/keyv/compare/2025)-12-10...2025-12-26 ### 2025-12-10 URL: https://keyv.org/changelog/2025-12-10 Date: December 10, 2025 Tag: Release ## What's Changed * redis - feat: updating readme on why namespaces cause memory bloat by @jaredwray in [https://github.com/jaredwray/keyv/pull/1726](https://github.com/jaredwray/keyv/pull/1726) * memcache - chore: upgrading @biomejs/biome to 2.3.7 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1728](https://github.com/jaredwray/keyv/pull/1728) * memcache - chore: upgrading tsup to 8.5.1 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1729](https://github.com/jaredwray/keyv/pull/1729) * memcache - chore: upgrading vitest to 4.0.14 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1730](https://github.com/jaredwray/keyv/pull/1730) * etcd - chore: upgrading @biomejs/biome to 2.3.7 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1731](https://github.com/jaredwray/keyv/pull/1731) * etcd - chore: upgrading vitest to 4.0.14 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1732](https://github.com/jaredwray/keyv/pull/1732) * dynamo - chore: upgrading vitest to 4.0.14 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1733](https://github.com/jaredwray/keyv/pull/1733) * dynamo - chore: upgrading aws-sdk to 3.940.0 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1734](https://github.com/jaredwray/keyv/pull/1734) * mono - feat: moving to minimum release ago to 5 days for updating mod… by @jaredwray in [https://github.com/jaredwray/keyv/pull/1736](https://github.com/jaredwray/keyv/pull/1736) * serialize - chore: upgrading @biomejs/biome to 2.3.8 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1737](https://github.com/jaredwray/keyv/pull/1737) * serialize - chore: upgrading vitest to 4.0.14 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1738](https://github.com/jaredwray/keyv/pull/1738) * keyv - chore: upgrading @biomejs/biome to 2.3.8 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1739](https://github.com/jaredwray/keyv/pull/1739) * keyv - chore: upgrading vitest to 4.0.14 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1740](https://github.com/jaredwray/keyv/pull/1740) * compress-brotli - chore: upgrading @biomejs/biome to 2.3.8 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1741](https://github.com/jaredwray/keyv/pull/1741) * compress-brotli - chore: upgrading vitest to 4.0.14 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1742](https://github.com/jaredwray/keyv/pull/1742) * compress-gzip - chore: upgrading @biomejs/biome to 2.3.8 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1743](https://github.com/jaredwray/keyv/pull/1743) * compress-gzip - chore: upgrading vitest to 4.0.14 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1744](https://github.com/jaredwray/keyv/pull/1744) * compress-lz4 - chore: upgrading @biomejs/biome to 2.3.8 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1745](https://github.com/jaredwray/keyv/pull/1745) * compress-lz4 - chore: upgrading vitest to 4.0.14 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1746](https://github.com/jaredwray/keyv/pull/1746) * mono - chore: upgrading tsup to 8.5.1 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1747](https://github.com/jaredwray/keyv/pull/1747) * mono - chore: upgrading vitest to 4.0.14 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1748](https://github.com/jaredwray/keyv/pull/1748) * keyv - fix: updating namespace adapter interface to be more permissive by @jaredwray in [https://github.com/jaredwray/keyv/pull/1749](https://github.com/jaredwray/keyv/pull/1749) * redis - chore: upgrading @biomejs/biome to 2.3.8 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1752](https://github.com/jaredwray/keyv/pull/1752) * redis - chore: upgrading vitest to 4.0.15 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1753](https://github.com/jaredwray/keyv/pull/1753) * redis - upgrading hookified to 1.13.0 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1754](https://github.com/jaredwray/keyv/pull/1754) * redis - chore: upgrading @redis/client to 5.10.0 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1755](https://github.com/jaredwray/keyv/pull/1755) * valkey - chore: upgrading @biomejs/biome to 2.3.8 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1756](https://github.com/jaredwray/keyv/pull/1756) * valkey - chore: upgrading vitest to 4.0.15 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1757](https://github.com/jaredwray/keyv/pull/1757) * test-suite - chore: upgrading vitest to 4.0.15 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1758](https://github.com/jaredwray/keyv/pull/1758) * test-suite - chore: upgrading @biomejs/biome to 2.3.8 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1759](https://github.com/jaredwray/keyv/pull/1759) * website - chore: upgrading docula to 0.31.1 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1760](https://github.com/jaredwray/keyv/pull/1760) **Full Changelog**: [https://github.com/jaredwray/keyv/compare/2025](https://github.com/jaredwray/keyv/compare/2025)-11-20...2025-12-10 ### 2025-11-20 URL: https://keyv.org/changelog/2025-11-20 Date: November 21, 2025 Tag: Release ## What's Changed * postgres - feat: setMany support by @darky in [https://github.com/jaredwray/keyv/pull/1723](https://github.com/jaredwray/keyv/pull/1723) * mysql - fix: resolving security concern with has method by @jaredwray in [https://github.com/jaredwray/keyv/pull/1724](https://github.com/jaredwray/keyv/pull/1724) * mysql - feat: adding in jsDocs by @jaredwray in [https://github.com/jaredwray/keyv/pull/1725](https://github.com/jaredwray/keyv/pull/1725) **Full Changelog**: [https://github.com/jaredwray/keyv/compare/2025](https://github.com/jaredwray/keyv/compare/2025)-11-17...2025-11-20 ### 2025-11-17 URL: https://keyv.org/changelog/2025-11-17 Date: November 18, 2025 Tag: Release ## What's Changed * bigmap - feat: moving to hashery for hashing by @jaredwray in [https://github.com/jaredwray/keyv/pull/1694](https://github.com/jaredwray/keyv/pull/1694) * postgres - perf: getMany O(n^2) -> O(2n) by @darky in [https://github.com/jaredwray/keyv/pull/1695](https://github.com/jaredwray/keyv/pull/1695) * keyv - fix: setting the exports correctly by @jaredwray in [https://github.com/jaredwray/keyv/pull/1697](https://github.com/jaredwray/keyv/pull/1697) * bigmap - fix: fixing exports to be correct by @jaredwray in [https://github.com/jaredwray/keyv/pull/1698](https://github.com/jaredwray/keyv/pull/1698) * compress-brotli - fix: fixing the exports by @jaredwray in [https://github.com/jaredwray/keyv/pull/1699](https://github.com/jaredwray/keyv/pull/1699) * compress-gzip - fix: updating exports to work correctly by @jaredwray in [https://github.com/jaredwray/keyv/pull/1700](https://github.com/jaredwray/keyv/pull/1700) * compress-lz4 - fix: getting exports to work better by @jaredwray in [https://github.com/jaredwray/keyv/pull/1701](https://github.com/jaredwray/keyv/pull/1701) * dynamo - fix: updating exports to work correctly by @jaredwray in [https://github.com/jaredwray/keyv/pull/1702](https://github.com/jaredwray/keyv/pull/1702) * etcd - fix: making exports work correctly by @jaredwray in [https://github.com/jaredwray/keyv/pull/1703](https://github.com/jaredwray/keyv/pull/1703) * memcache - fix: making exports work correctly by @jaredwray in [https://github.com/jaredwray/keyv/pull/1704](https://github.com/jaredwray/keyv/pull/1704) * mongo - fix: getting exports to work correctly by @jaredwray in [https://github.com/jaredwray/keyv/pull/1705](https://github.com/jaredwray/keyv/pull/1705) * mysql - fix: exports are working correctly by @jaredwray in [https://github.com/jaredwray/keyv/pull/1706](https://github.com/jaredwray/keyv/pull/1706) * postgres - fix: exports working correctly by @jaredwray in [https://github.com/jaredwray/keyv/pull/1707](https://github.com/jaredwray/keyv/pull/1707) * redis - fix: exports are now working correctly by @jaredwray in [https://github.com/jaredwray/keyv/pull/1708](https://github.com/jaredwray/keyv/pull/1708) * serialize - fix: getting exports to work better by @jaredwray in [https://github.com/jaredwray/keyv/pull/1709](https://github.com/jaredwray/keyv/pull/1709) * sqlite - fix: exports now work correctly by @jaredwray in [https://github.com/jaredwray/keyv/pull/1710](https://github.com/jaredwray/keyv/pull/1710) * test-suite - fix: exports need to work correctly by @jaredwray in [https://github.com/jaredwray/keyv/pull/1711](https://github.com/jaredwray/keyv/pull/1711) * valkey - fix: exports working correctly by @jaredwray in [https://github.com/jaredwray/keyv/pull/1712](https://github.com/jaredwray/keyv/pull/1712) * mysql - chore: upgrading vitest to 4.0.10 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1713](https://github.com/jaredwray/keyv/pull/1713) * mysql - chore: upgrading @biomejs/biome to 2.3.6 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1714](https://github.com/jaredwray/keyv/pull/1714) * mysql - chore: upgrading mysql2 to 3.15.3 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1715](https://github.com/jaredwray/keyv/pull/1715) * sqlite - chore: upgrading vitest to 4.0.10 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1716](https://github.com/jaredwray/keyv/pull/1716) * sqlite - chore: upgrading @biomejs/biome to 2.3.6 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1717](https://github.com/jaredwray/keyv/pull/1717) * postgres - chore: upgrading vitest to 4.0.10 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1718](https://github.com/jaredwray/keyv/pull/1718) * postgres - chore: upgrading @biomejs/biome to 2.3.6 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1719](https://github.com/jaredwray/keyv/pull/1719) * bigmap - chore: upgrading vitest to 4.0.10 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1720](https://github.com/jaredwray/keyv/pull/1720) * bigmap - chore: upgrading hookified to 1.13.0 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1721](https://github.com/jaredwray/keyv/pull/1721) * bigmap - chore: upgrading @biomejs/biome to 2.3.6 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1722](https://github.com/jaredwray/keyv/pull/1722) **Full Changelog**: [https://github.com/jaredwray/keyv/compare/2025](https://github.com/jaredwray/keyv/compare/2025)-11-11...2025-11-17 ### 2025-11-11 URL: https://keyv.org/changelog/2025-11-11 Date: November 11, 2025 Tag: Release ## What's Changed * postgres - feat: connect method as public by @darky in [https://github.com/jaredwray/keyv/pull/1681](https://github.com/jaredwray/keyv/pull/1681) * redis - chore: upgrading vitest to 4.0.8 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1682](https://github.com/jaredwray/keyv/pull/1682) * redis - chore: upgrading hookified to 1.12.2 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1683](https://github.com/jaredwray/keyv/pull/1683) * redis - chore: upgrading @redis/client to 5.9.0 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1684](https://github.com/jaredwray/keyv/pull/1684) * redis - feat: moving all the types to a types file by @jaredwray in [https://github.com/jaredwray/keyv/pull/1685](https://github.com/jaredwray/keyv/pull/1685) * redis - feat: moving create helper functions to create.ts by @jaredwray in [https://github.com/jaredwray/keyv/pull/1686](https://github.com/jaredwray/keyv/pull/1686) * valkey - chore: upgrading vitest to 4.0.8 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1687](https://github.com/jaredwray/keyv/pull/1687) * valkey - chore: upgrading @biomejs/biome to 2.3.5 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1689](https://github.com/jaredwray/keyv/pull/1689) * test-suite - chore: upgrading @biomejs/biome to 2.3.5 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1690](https://github.com/jaredwray/keyv/pull/1690) * test-suite - chore: upgrading vitest to 4.0.8 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1691](https://github.com/jaredwray/keyv/pull/1691) * website - chore: upgrading docula to 0.31.0 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1692](https://github.com/jaredwray/keyv/pull/1692) * keyv - fix: POST_GET hook should fire on a miss by @jaredwray in [https://github.com/jaredwray/keyv/pull/1693](https://github.com/jaredwray/keyv/pull/1693) **Full Changelog**: [https://github.com/jaredwray/keyv/compare/2025](https://github.com/jaredwray/keyv/compare/2025)-11-04...2025-11-11 ### 2025-11-04 URL: https://keyv.org/changelog/2025-11-04 Date: November 4, 2025 Tag: Release ## What's Changed * mono - chore: upgrading vitest to 4.0.6 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1659](https://github.com/jaredwray/keyv/pull/1659) * mono - chore: upgrading typescript to 5.9.3 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1660](https://github.com/jaredwray/keyv/pull/1660) * mono - chore: upgrading rimraf to 6.1.0 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1661](https://github.com/jaredwray/keyv/pull/1661) * mono - chore: upgrading @biomejs/biome to 2.3.3 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1662](https://github.com/jaredwray/keyv/pull/1662) * keyv - chore: upgrading vitest to 4.0.6 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1663](https://github.com/jaredwray/keyv/pull/1663) * keyv - chore: upgrading rimraf to 6.1.0 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1664](https://github.com/jaredwray/keyv/pull/1664) * keyv - chore: upgrading @biomejs/biome to 2.3.3 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1665](https://github.com/jaredwray/keyv/pull/1665) * keyv - chore: upgrading @faker-js/faker to 10.1.0 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1666](https://github.com/jaredwray/keyv/pull/1666) * serialize - chore: upgrading vitest to 4.0.6 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1667](https://github.com/jaredwray/keyv/pull/1667) * serialize - chore: upgrading rimraf to 6.1.0 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1668](https://github.com/jaredwray/keyv/pull/1668) * serialize - chore: upgrading @biomejs/biome to 2.3.3 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1670](https://github.com/jaredwray/keyv/pull/1670) * compress-brotli - chore: upgrading vitest to 4.0.6 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1671](https://github.com/jaredwray/keyv/pull/1671) * Update JSDoc and main docs to clarify that TTL is in milliseconds by @natesilva in [https://github.com/jaredwray/keyv/pull/1669](https://github.com/jaredwray/keyv/pull/1669) * compres-brotli - chore: upgrading @biomejs/biome to 2.3.3 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1672](https://github.com/jaredwray/keyv/pull/1672) * compress-gzip - chore: upgrading vitest to 4.0.6 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1673](https://github.com/jaredwray/keyv/pull/1673) * compress-gzip - chore: upgrading rimraf to 6.1.0 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1674](https://github.com/jaredwray/keyv/pull/1674) * compress-gzip - chore: upgrading @biomejs/biome to 2.3.3 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1675](https://github.com/jaredwray/keyv/pull/1675) * compress-lz4 - chore: upgrading vitest to 4.0.6 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1676](https://github.com/jaredwray/keyv/pull/1676) * compress-gzip - chore: upgrading rimraf to 6.1.0 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1677](https://github.com/jaredwray/keyv/pull/1677) * compress-lz4 - chore: upgrading @biomejs/biome to 2.3.3 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1678](https://github.com/jaredwray/keyv/pull/1678) ## New Contributors * @natesilva made their first contribution in [https://github.com/jaredwray/keyv/pull/1669](https://github.com/jaredwray/keyv/pull/1669) **Full Changelog**: [https://github.com/jaredwray/keyv/compare/2025](https://github.com/jaredwray/keyv/compare/2025)-10-25...2025-11-04 ### 2025-10-25 URL: https://keyv.org/changelog/2025-10-25 Date: October 25, 2025 Tag: Release ## What's Changed * website - feat: Add explanation caching nestjs docs by @junghyunbak in [https://github.com/jaredwray/keyv/pull/1645](https://github.com/jaredwray/keyv/pull/1645) * memcache - chore: upgrading @biomejs/biome to 2.3.0 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1646](https://github.com/jaredwray/keyv/pull/1646) * memcache - chore: upgrading typescript to 5.9.3 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1647](https://github.com/jaredwray/keyv/pull/1647) * memcache - chore: upgrading vitest to 4.0.3 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1648](https://github.com/jaredwray/keyv/pull/1648) * etcd - chore: upgrading @biomejs/biome to 2.3.0 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1649](https://github.com/jaredwray/keyv/pull/1649) * etcd - chore: upgrading typescript to 5.9.3 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1650](https://github.com/jaredwray/keyv/pull/1650) * etcd - chore: upgrading vitest to 4.0.3 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1651](https://github.com/jaredwray/keyv/pull/1651) * dynamo - chore: upgrading vitest to 4.0.3 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1652](https://github.com/jaredwray/keyv/pull/1652) * dynamo - chore: upgrading @biomejs/biome to 2.3.0 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1653](https://github.com/jaredwray/keyv/pull/1653) * dynamo - chore: upgrading @aws-sdk to 3.917.0 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1654](https://github.com/jaredwray/keyv/pull/1654) * mongo - chore: upgrading vitest to 4.0.3 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1655](https://github.com/jaredwray/keyv/pull/1655) * compress-brotli - fix: removing c8 as no longer needed by @jaredwray in [https://github.com/jaredwray/keyv/pull/1656](https://github.com/jaredwray/keyv/pull/1656) * keyv - feat: adding in BigMap in Keyv documentation by @jaredwray in [https://github.com/jaredwray/keyv/pull/1657](https://github.com/jaredwray/keyv/pull/1657) * bigmap - feat: updating documentation by @jaredwray in [https://github.com/jaredwray/keyv/pull/1658](https://github.com/jaredwray/keyv/pull/1658) ## New Contributors * @junghyunbak made their first contribution in [https://github.com/jaredwray/keyv/pull/1645](https://github.com/jaredwray/keyv/pull/1645) **Full Changelog**: [https://github.com/jaredwray/keyv/compare/2025](https://github.com/jaredwray/keyv/compare/2025)-10-18...2025-10-25 ### 2025-10-18 URL: https://keyv.org/changelog/2025-10-18 Date: October 18, 2025 Tag: Release ## What's Changed * mysql - chore: upgrading mysql2 to 3.15.2 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1633](https://github.com/jaredwray/keyv/pull/1633) * mysql - chore: upgrading @biomejs/biome to 2.2.6 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1634](https://github.com/jaredwray/keyv/pull/1634) * sqlite - chore: upgrading sqlite to 10.1.0 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1635](https://github.com/jaredwray/keyv/pull/1635) * sqlite - chore: upgrading @biomejs/biome to 2.2.6 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1636](https://github.com/jaredwray/keyv/pull/1636) * postgres - chore: upgrading @biomejs/biome to 2.2.6 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1637](https://github.com/jaredwray/keyv/pull/1637) * bigmap - chore: upgrading hookified to 1.12.2 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1638](https://github.com/jaredwray/keyv/pull/1638) * bigmap - chore: upgrading @biomejs/biome to 2.2.6 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1639](https://github.com/jaredwray/keyv/pull/1639) * bigmap - chore: upgrading @faker-js/faker to 10.1.0 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1640](https://github.com/jaredwray/keyv/pull/1640) * bigmap - feat: updating readme by @jaredwray in [https://github.com/jaredwray/keyv/pull/1641](https://github.com/jaredwray/keyv/pull/1641) * bigmap - feat: adding in createKeyv function by @jaredwray in [https://github.com/jaredwray/keyv/pull/1642](https://github.com/jaredwray/keyv/pull/1642) * keyv - feat: adding in capabilities checker by @jaredwray in [https://github.com/jaredwray/keyv/pull/1643](https://github.com/jaredwray/keyv/pull/1643) **Full Changelog**: [https://github.com/jaredwray/keyv/compare/2025](https://github.com/jaredwray/keyv/compare/2025)-10-09...2025-10-18 ### 2025-10-09 URL: https://keyv.org/changelog/2025-10-09 Date: October 10, 2025 Tag: Release ## What's Changed * sqlite - fix: adding in better filtering on table input by @jaredwray in [https://github.com/jaredwray/keyv/pull/1622](https://github.com/jaredwray/keyv/pull/1622) * bigmap - fix: adding in forEach code that works by @jaredwray in [https://github.com/jaredwray/keyv/pull/1623](https://github.com/jaredwray/keyv/pull/1623) * valkey - fix: removing console.log that was added by accident by @jaredwray in [https://github.com/jaredwray/keyv/pull/1624](https://github.com/jaredwray/keyv/pull/1624) * valkey - chore: adding in iterator test on functionality by @jaredwray in [https://github.com/jaredwray/keyv/pull/1625](https://github.com/jaredwray/keyv/pull/1625) * redis - fix: redis docs by @ATGardner in [https://github.com/jaredwray/keyv/pull/1626](https://github.com/jaredwray/keyv/pull/1626) * redis - chore: upgrading @biomejs/biome to 2.2.5 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1628](https://github.com/jaredwray/keyv/pull/1628) * redis - chore: upgrading hookified to 1.12.1 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1629](https://github.com/jaredwray/keyv/pull/1629) * redis - chore: upgrading @redis/client to 5.8.3 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1630](https://github.com/jaredwray/keyv/pull/1630) * test-suite - chore: upgrading @biomejs/biome to 2.2.5 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1631](https://github.com/jaredwray/keyv/pull/1631) * website - chore: upgrading tsx to 4.20.6 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1632](https://github.com/jaredwray/keyv/pull/1632) * mono - feat: Sort adapters & add Cloudflare KV adapter. by @ariesclark in [https://github.com/jaredwray/keyv/pull/1627](https://github.com/jaredwray/keyv/pull/1627) ## New Contributors * @ATGardner made their first contribution in [https://github.com/jaredwray/keyv/pull/1626](https://github.com/jaredwray/keyv/pull/1626) * @ariesclark made their first contribution in [https://github.com/jaredwray/keyv/pull/1627](https://github.com/jaredwray/keyv/pull/1627) **Full Changelog**: [https://github.com/jaredwray/keyv/compare/2025](https://github.com/jaredwray/keyv/compare/2025)-10-03...2025-10-09 ### 2025-10-03 URL: https://keyv.org/changelog/2025-10-03 Date: October 3, 2025 Tag: Release ## What's Changed * valkey - fix: removing sets namespace as it is not needed by @jaredwray in [https://github.com/jaredwray/keyv/pull/1613](https://github.com/jaredwray/keyv/pull/1613) * keyv - chore: upgrading biome to 2.2.5 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1614](https://github.com/jaredwray/keyv/pull/1614) * serialize - chore: upgrading biome to 2.2.5 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1616](https://github.com/jaredwray/keyv/pull/1616) * mono - chore: removing webpack as unneeded by @jaredwray in [https://github.com/jaredwray/keyv/pull/1617](https://github.com/jaredwray/keyv/pull/1617) * compress-brotli - chore: upgrading biome to 2.2.5 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1618](https://github.com/jaredwray/keyv/pull/1618) * compress-gzip - chore: upgrading biome to 2.2.5 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1619](https://github.com/jaredwray/keyv/pull/1619) * compress-lz4 - chore: upgrading biome to 2.2.5 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1620](https://github.com/jaredwray/keyv/pull/1620) * mongo - fix: possible nosql injection attack on gridfs by @jaredwray in [https://github.com/jaredwray/keyv/pull/1621](https://github.com/jaredwray/keyv/pull/1621) **Full Changelog**: [https://github.com/jaredwray/keyv/compare/2025](https://github.com/jaredwray/keyv/compare/2025)-09-27...2025-10-03 ### 2025-09-27 URL: https://keyv.org/changelog/2025-09-27 Date: September 27, 2025 Tag: Release ## What's Changed * website - chore: upgrading docula to 0.30.0 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1594](https://github.com/jaredwray/keyv/pull/1594) * bigmap - feat: moving to node 18 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1597](https://github.com/jaredwray/keyv/pull/1597) * bigmap - chore: upgrading hookified to 1.12.1 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1598](https://github.com/jaredwray/keyv/pull/1598) * keyv -feat: adding in stats documentation by @jaredwray in [https://github.com/jaredwray/keyv/pull/1595](https://github.com/jaredwray/keyv/pull/1595) * keyv - fix: setMany was not passing prefixed keys by @jaredwray in [https://github.com/jaredwray/keyv/pull/1599](https://github.com/jaredwray/keyv/pull/1599) * memcache - chore: upgrading biome to 2.2.4 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1603](https://github.com/jaredwray/keyv/pull/1603) * etcd - chore: upgrading biome to 2.2.4 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1604](https://github.com/jaredwray/keyv/pull/1604) * dynamo - chore: upgrading biome to 2.2.4 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1605](https://github.com/jaredwray/keyv/pull/1605) * dynamo - feat: adding in create keyv helper function by @jaredwray in [https://github.com/jaredwray/keyv/pull/1610](https://github.com/jaredwray/keyv/pull/1610) * dynamo - upgrading @aws-sdk/dynamo to 3.896.0 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1606](https://github.com/jaredwray/keyv/pull/1606) * mongo - chore: upgrading biome to 2.2.4 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1607](https://github.com/jaredwray/keyv/pull/1607) * mongo - fix: now using Keyv in workspace by @jaredwray in [https://github.com/jaredwray/keyv/pull/1608](https://github.com/jaredwray/keyv/pull/1608) * mongo - chore: upgrading mongodb to 6.20.0 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1609](https://github.com/jaredwray/keyv/pull/1609) * mono - chore: add third party adapter keyv-browser by @zaaack in [https://github.com/jaredwray/keyv/pull/1602](https://github.com/jaredwray/keyv/pull/1602) ## New Contributors * @zaaack made their first contribution in [https://github.com/jaredwray/keyv/pull/1602](https://github.com/jaredwray/keyv/pull/1602) **Full Changelog**: [https://github.com/jaredwray/keyv/compare/2025](https://github.com/jaredwray/keyv/compare/2025)-09-17...2025-09-27 ### 2025-09-17 URL: https://keyv.org/changelog/2025-09-17 Date: September 17, 2025 Tag: Release ## What's Changed * mysql - chore: upgrading mysql2 to 3.15.0 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1582](https://github.com/jaredwray/keyv/pull/1582) * mysql - chore: upgrading biome to 2.2.4 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1583](https://github.com/jaredwray/keyv/pull/1583) * mysql - chore: updating to not use deprecated OkPacket by @jaredwray in [https://github.com/jaredwray/keyv/pull/1591](https://github.com/jaredwray/keyv/pull/1591) * sqlite - chore: upgrading @faker-js/faker to 10.0.0 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1584](https://github.com/jaredwray/keyv/pull/1584) * postgres - chore: upgrading biom to 2.2.4 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1585](https://github.com/jaredwray/keyv/pull/1585) * bigmap - chore: upgrading hookified to 1.12.0 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1586](https://github.com/jaredwray/keyv/pull/1586) * bigmap - chore: upgrading @faker-js/faker to 10.0.0 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1587](https://github.com/jaredwray/keyv/pull/1587) * mono - chore: updating codecov config by @jaredwray in [https://github.com/jaredwray/keyv/pull/1588](https://github.com/jaredwray/keyv/pull/1588) * mono - chore: updating biome lint and checks by @jaredwray in [https://github.com/jaredwray/keyv/pull/1589](https://github.com/jaredwray/keyv/pull/1589) * keyv - fix: hasMany was not working and passing back the wrong key by @jaredwray in [https://github.com/jaredwray/keyv/pull/1590](https://github.com/jaredwray/keyv/pull/1590) **Full Changelog**: [https://github.com/jaredwray/keyv/compare/2025](https://github.com/jaredwray/keyv/compare/2025)-09-10...2025-09-17 ### 2025-09-10 URL: https://keyv.org/changelog/2025-09-10 Date: September 10, 2025 Tag: Release ## What's Changed * mono - fix: updating codecov to get a fix going by @jaredwray in [https://github.com/jaredwray/keyv/pull/1555](https://github.com/jaredwray/keyv/pull/1555) * website - chore: fixing docs on caching to not be ignored by @jaredwray in [https://github.com/jaredwray/keyv/pull/1561](https://github.com/jaredwray/keyv/pull/1561) * keyv - chore: upgrading @biomejs/biome to 2.2.3 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1567](https://github.com/jaredwray/keyv/pull/1567) * keyv - chore: upgrading @faker-js/faker to 10.0.0 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1568](https://github.com/jaredwray/keyv/pull/1568) * serialize - fix: handling colon as part of the object parameter name by @jaredwray in [https://github.com/jaredwray/keyv/pull/1569](https://github.com/jaredwray/keyv/pull/1569) * serialize - chore: upgrading @biomejs/biome to 2.2.3 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1570](https://github.com/jaredwray/keyv/pull/1570) * memcache - chore: upgrading @biomejs/biome to 2.2.3 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1571](https://github.com/jaredwray/keyv/pull/1571) * redis - fix: on cluster it cannot do multi() by @jaredwray in [https://github.com/jaredwray/keyv/pull/1562](https://github.com/jaredwray/keyv/pull/1562) * redis - fix: when call mget, keys within the same master, should land o… by @lchenay in [https://github.com/jaredwray/keyv/pull/1560](https://github.com/jaredwray/keyv/pull/1560) * redis - chore: upgrading @biomejs/biome to 2.2.3 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1572](https://github.com/jaredwray/keyv/pull/1572) * redis - chore: upgrading hookified to 1.12.0 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1573](https://github.com/jaredwray/keyv/pull/1573) * redis - chore: upgrading @faker-js/faker to 10.0.0 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1574](https://github.com/jaredwray/keyv/pull/1574) * redis - chore: upgrading @redis/client to 5.8.2 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1575](https://github.com/jaredwray/keyv/pull/1575) * test-suite - chore: upgrading @biomejs/biome to 2.2.3 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1576](https://github.com/jaredwray/keyv/pull/1576) * dynamo - feat: exposing the client for better usage by @jaredwray in [https://github.com/jaredwray/keyv/pull/1564](https://github.com/jaredwray/keyv/pull/1564) * dynamo - chore: upgrading @biomejs/biome to 2.2.3 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1577](https://github.com/jaredwray/keyv/pull/1577) * dynamo - chore: upgrading @aws-sdk to 3.883.0 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1578](https://github.com/jaredwray/keyv/pull/1578) * compress-brotli - chore: upgrading @biomejs/biome to 2.2.3 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1579](https://github.com/jaredwray/keyv/pull/1579) * compress-gzip - chore: upgrading @biomejs/biome to 2.2.4 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1580](https://github.com/jaredwray/keyv/pull/1580) * compress-lz4 - chore: upgrading @biomejs/biome to 2.2.4 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1581](https://github.com/jaredwray/keyv/pull/1581) ## New Contributors * @lchenay made their first contribution in [https://github.com/jaredwray/keyv/pull/1560](https://github.com/jaredwray/keyv/pull/1560) **Full Changelog**: [https://github.com/jaredwray/keyv/compare/2025](https://github.com/jaredwray/keyv/compare/2025)-08-16...2025-09-10 ### 2025-08-16 URL: https://keyv.org/changelog/2025-08-16 Date: August 16, 2025 Tag: Release ## What's Changed * mono - chore: upgrading xo to 1.2.2 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1541](https://github.com/jaredwray/keyv/pull/1541) * mono - chore: upgrading typescript to 5.9.2 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1542](https://github.com/jaredwray/keyv/pull/1542) * mono - feat migrating to biome from xo by @jaredwray in [https://github.com/jaredwray/keyv/pull/1552](https://github.com/jaredwray/keyv/pull/1552) * sqlite - chore: upgrading xo to 1.2.2 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1543](https://github.com/jaredwray/keyv/pull/1543) * postgres - chore: upgrading xo and @types/pg to latest by @jaredwray in [https://github.com/jaredwray/keyv/pull/1544](https://github.com/jaredwray/keyv/pull/1544) * mysql - chore: upgrading xo to 1.2.2 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1545](https://github.com/jaredwray/keyv/pull/1545) * mysql - chore: upgrading mysql2 to 3.14.3 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1546](https://github.com/jaredwray/keyv/pull/1546) * etcd - chore: upgrading xo and typescript to latest by @jaredwray in [https://github.com/jaredwray/keyv/pull/1547](https://github.com/jaredwray/keyv/pull/1547) * valkey - chore: upgrading xo to 1.2.2 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1548](https://github.com/jaredwray/keyv/pull/1548) * website - chore: upgrading tsx to 4.20.4 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1549](https://github.com/jaredwray/keyv/pull/1549) * serialize - chore: upgrading xo to 1.2.2 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1550](https://github.com/jaredwray/keyv/pull/1550) * serialize - chore: upgrading typescript to 5.9.2 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1551](https://github.com/jaredwray/keyv/pull/1551) * redis - fix: readme to be correct on KeyvRedisOptions by @jaredwray in [https://github.com/jaredwray/keyv/pull/1553](https://github.com/jaredwray/keyv/pull/1553) **Full Changelog**: [https://github.com/jaredwray/keyv/compare/2025](https://github.com/jaredwray/keyv/compare/2025)-08-02...2025-08-16 ### 2025-08-02 URL: https://keyv.org/changelog/2025-08-02 Date: August 2, 2025 Tag: Release ## What's Changed * valkey - fix: use proper types for options by @Michsior14 in [https://github.com/jaredwray/keyv/pull/1520](https://github.com/jaredwray/keyv/pull/1520) * keyv - chore: upgrading xo to 1.2.1 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1523](https://github.com/jaredwray/keyv/pull/1523) * keyv - feat: adding in getRaw and getManyRaw by @jaredwray in [https://github.com/jaredwray/keyv/pull/1525](https://github.com/jaredwray/keyv/pull/1525) * redis - feat: add step-by-step guide for using @keyv/redis with NestJS by @JardeFelicio in [https://github.com/jaredwray/keyv/pull/1524](https://github.com/jaredwray/keyv/pull/1524) * redis - feat: support redis sentinel for KeyvRedis store by @thomasdom in [https://github.com/jaredwray/keyv/pull/1528](https://github.com/jaredwray/keyv/pull/1528) * redis - chore: upgrading xo to 1.2.1 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1533](https://github.com/jaredwray/keyv/pull/1533) * redis - chore: upgrading hookified to 1.11.0 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1534](https://github.com/jaredwray/keyv/pull/1534) * redis - chore: upgrading @redis/client to 5.7.0 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1535](https://github.com/jaredwray/keyv/pull/1535) * memcche - chore: upgrading xo to 1.2.1 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1531](https://github.com/jaredwray/keyv/pull/1531) * memcache - chore: upgrading typescript to 5.9.2 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1532](https://github.com/jaredwray/keyv/pull/1532) * test-suite - chore: upgrading bignumber.js to 9.3.1 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1536](https://github.com/jaredwray/keyv/pull/1536) * dynamo - upgrading @aws-sdk/client-dynamodb to 3.859.0 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1537](https://github.com/jaredwray/keyv/pull/1537) * dynamo - feat: use random table names for better test isolation by @brunocamargos in [https://github.com/jaredwray/keyv/pull/1526](https://github.com/jaredwray/keyv/pull/1526) ## New Contributors * @Michsior14 made their first contribution in [https://github.com/jaredwray/keyv/pull/1520](https://github.com/jaredwray/keyv/pull/1520) * @JardeFelicio made their first contribution in [https://github.com/jaredwray/keyv/pull/1524](https://github.com/jaredwray/keyv/pull/1524) * @thomasdom made their first contribution in [https://github.com/jaredwray/keyv/pull/1528](https://github.com/jaredwray/keyv/pull/1528) **Full Changelog**: [https://github.com/jaredwray/keyv/compare/2025](https://github.com/jaredwray/keyv/compare/2025)-07-19...2025-08-02 ### 2025-07-19 URL: https://keyv.org/changelog/2025-07-19 Date: July 19, 2025 Tag: Release ## What's Changed * dynamo - feat: add automatic table creation and ttl configuration by @brunocamargos in [https://github.com/jaredwray/keyv/pull/1493](https://github.com/jaredwray/keyv/pull/1493) * bigmap - feat: adding in bigmap for keyv by @jaredwray in [https://github.com/jaredwray/keyv/pull/1497](https://github.com/jaredwray/keyv/pull/1497) * redis - feat: (breaking) upgrading @redis/client to v5 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1494](https://github.com/jaredwray/keyv/pull/1494) * redis - fixing createKeyv to do correct namespacing with Keyv by @jaredwray in [https://github.com/jaredwray/keyv/pull/1498](https://github.com/jaredwray/keyv/pull/1498) * redis - fix: fixing the disconnect on error so it triggers by @jaredwray in [https://github.com/jaredwray/keyv/pull/1499](https://github.com/jaredwray/keyv/pull/1499) * redis - feat: adding in createKeyvNonBlocking by @jaredwray in [https://github.com/jaredwray/keyv/pull/1503](https://github.com/jaredwray/keyv/pull/1503) * keyv - feat: adding in throwErrors option by @jaredwray in [https://github.com/jaredwray/keyv/pull/1500](https://github.com/jaredwray/keyv/pull/1500) * keyv - fix: setMany setting entries twice by @nathan-knight in [https://github.com/jaredwray/keyv/pull/1504](https://github.com/jaredwray/keyv/pull/1504) * keyv - fix: `getMany` serially awaiting expired key deletion by @nathan-knight in [https://github.com/jaredwray/keyv/pull/1505](https://github.com/jaredwray/keyv/pull/1505) * keyv - fix: fix callback parameter in keyv hook handler. by @GabuTheDev in [https://github.com/jaredwray/keyv/pull/1506](https://github.com/jaredwray/keyv/pull/1506) * mono - chore: upgrading xo to 1.2.1 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1507](https://github.com/jaredwray/keyv/pull/1507) * mono - chore: upgrading webpack to 5.100.2 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1508](https://github.com/jaredwray/keyv/pull/1508) * sqlite - chore: upgrading xo to 1.2.1 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1509](https://github.com/jaredwray/keyv/pull/1509) * sqlite - chore: upgrading @faker-js/faker to 9.9.0 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1510](https://github.com/jaredwray/keyv/pull/1510) * postgres - chore: upgrading xo to 1.2.1 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1511](https://github.com/jaredwray/keyv/pull/1511) * postgres - chore: upgrading pg to 8.16.3 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1512](https://github.com/jaredwray/keyv/pull/1512) * mysql - chore: upgrading xo to 1.2.1 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1513](https://github.com/jaredwray/keyv/pull/1513) * mysql - chore: upgrading mysql2 to 3.14.2 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1514](https://github.com/jaredwray/keyv/pull/1514) * memcache - chore: upgrading xo to 1.2.1 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1515](https://github.com/jaredwray/keyv/pull/1515) * valkey - chore: upgrading xo to 1.2.1 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1516](https://github.com/jaredwray/keyv/pull/1516) * website - chore: upgrading docula to 0.13.1 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1517](https://github.com/jaredwray/keyv/pull/1517) * serialize - feat: upgrading xo to 1.2.1 and clean up by @jaredwray in [https://github.com/jaredwray/keyv/pull/1518](https://github.com/jaredwray/keyv/pull/1518) * test-suite - feat: moving to internal compression adapter for testing by @jaredwray in [https://github.com/jaredwray/keyv/pull/1502](https://github.com/jaredwray/keyv/pull/1502) ## New Contributors * @nathan-knight made their first contribution in [https://github.com/jaredwray/keyv/pull/1504](https://github.com/jaredwray/keyv/pull/1504) * @GabuTheDev made their first contribution in [https://github.com/jaredwray/keyv/pull/1506](https://github.com/jaredwray/keyv/pull/1506) **Full Changelog**: [https://github.com/jaredwray/keyv/compare/2025](https://github.com/jaredwray/keyv/compare/2025)-07-09...2025-07-19 ### 2025-07-09 URL: https://keyv.org/changelog/2025-07-09 Date: July 9, 2025 Tag: Release ## What's Changed * valkey - fix: fixing createKeyv to return Keyv instance by @jaredwray in [https://github.com/jaredwray/keyv/pull/1468](https://github.com/jaredwray/keyv/pull/1468) * dynamo - feat: add dynamodb implementation by @brunocamargos in [https://github.com/jaredwray/keyv/pull/1475](https://github.com/jaredwray/keyv/pull/1475) * keyv - chore: upgrading xo to 1.1.1 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1477](https://github.com/jaredwray/keyv/pull/1477) * keyv - chore: upgrading @faker-js/faker to 9.9.0 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1478](https://github.com/jaredwray/keyv/pull/1478) * keyv - chore: upgrading vitest to 3.2.4 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1479](https://github.com/jaredwray/keyv/pull/1479) * memcache - chore: upgrading xo to 1.1.1 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1480](https://github.com/jaredwray/keyv/pull/1480) * memcache - chore: upgrading vitest to 3.2.4 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1481](https://github.com/jaredwray/keyv/pull/1481) * redis - fix: adding in connection / no-op failure strategies by @jaredwray in [https://github.com/jaredwray/keyv/pull/1471](https://github.com/jaredwray/keyv/pull/1471) * redis - feat: adding in throw error options and no-op for flaky redis instance on calls by @jaredwray in [https://github.com/jaredwray/keyv/pull/1474](https://github.com/jaredwray/keyv/pull/1474) * redis - chore: upgrading xo to 1.1.1 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1482](https://github.com/jaredwray/keyv/pull/1482) * redis - feat: updating the readme with errors and options by @jaredwray in [https://github.com/jaredwray/keyv/pull/1476](https://github.com/jaredwray/keyv/pull/1476) * redis - chore: upgrading vitest to 3.2.4 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1483](https://github.com/jaredwray/keyv/pull/1483) * redis - chore: upgrading @faker-js/faker to 9.9.0 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1484](https://github.com/jaredwray/keyv/pull/1484) * test-suite - chore: upgrading vitest to 3.2.4 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1485](https://github.com/jaredwray/keyv/pull/1485) * compress-brotli - chore: upgrading xo to 1.1.1 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1486](https://github.com/jaredwray/keyv/pull/1486) * compress-brotli - chore: upgrading vitest to 3.2.4 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1487](https://github.com/jaredwray/keyv/pull/1487) * compress-gzip - chore: upgrading xo to 1.1.1 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1488](https://github.com/jaredwray/keyv/pull/1488) * compress-gzip - chore: upgrading vitest to 3.2.4 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1489](https://github.com/jaredwray/keyv/pull/1489) * compress-lz4 - chore: upgrading xo to 1.1.1 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1490](https://github.com/jaredwray/keyv/pull/1490) * compress-lz4 - chore: upgrading lz4-napi to 2.9.0 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1491](https://github.com/jaredwray/keyv/pull/1491) * compress-lz4 - chore: upgrading vitest to 3.2.4 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1492](https://github.com/jaredwray/keyv/pull/1492) ## New Contributors * @brunocamargos made their first contribution in [https://github.com/jaredwray/keyv/pull/1475](https://github.com/jaredwray/keyv/pull/1475) **Full Changelog**: [https://github.com/jaredwray/keyv/compare/2025](https://github.com/jaredwray/keyv/compare/2025)-06-21...2025-07-09 ### 2025-06-21 URL: https://keyv.org/changelog/2025-06-21 Date: June 21, 2025 Tag: Release ## What's Changed * redis - fix: fixing readme and createKeyv helper by @jaredwray in [https://github.com/jaredwray/keyv/pull/1452](https://github.com/jaredwray/keyv/pull/1452) * sqlite - chore: upgrading xo to 1.1.0 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1454](https://github.com/jaredwray/keyv/pull/1454) * sqlite - chore: testing iterator with useKeyPrefix and documentation by @jaredwray in [https://github.com/jaredwray/keyv/pull/1466](https://github.com/jaredwray/keyv/pull/1466) * postgres - upgrading xo to 1.1.0 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1455](https://github.com/jaredwray/keyv/pull/1455) * mysql - chore: upgrading xo to 1.1.0 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1458](https://github.com/jaredwray/keyv/pull/1458) * etcd - chore: upgrading xo to 1.1.0 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1459](https://github.com/jaredwray/keyv/pull/1459) * etcd - chore: upgrading vitest to 3.2.4 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1460](https://github.com/jaredwray/keyv/pull/1460) * valkey - chore: upgrading vitest to 3.2.4 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1461](https://github.com/jaredwray/keyv/pull/1461) * valkey - chore: upgrading iovalkey to 0.3.3 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1462](https://github.com/jaredwray/keyv/pull/1462) * valkey - fix: fixing the createKeyv to work correctly by @jaredwray in [https://github.com/jaredwray/keyv/pull/1467](https://github.com/jaredwray/keyv/pull/1467) * website - chore: upgrading docula to 0.13.0 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1463](https://github.com/jaredwray/keyv/pull/1463) * mono - chore: upgrading webpack to 5.99.9 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1464](https://github.com/jaredwray/keyv/pull/1464) * mono - chore: upgrading vitest to 3.2.4 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1465](https://github.com/jaredwray/keyv/pull/1465) * mono - chore: updating the github actions with permissions by @jaredwray in [https://github.com/jaredwray/keyv/pull/1453](https://github.com/jaredwray/keyv/pull/1453) * mono - chore: working on getting codecov reporting by @jaredwray in [https://github.com/jaredwray/keyv/pull/1456](https://github.com/jaredwray/keyv/pull/1456) * mono - chore: clean up as ts-node and c8 are not needed anymore by @jaredwray in [https://github.com/jaredwray/keyv/pull/1457](https://github.com/jaredwray/keyv/pull/1457) **Full Changelog**: [https://github.com/jaredwray/keyv/compare/2025](https://github.com/jaredwray/keyv/compare/2025)-06-09...2025-06-21 ### 2025-06-09 URL: https://keyv.org/changelog/2025-06-09 Date: June 10, 2025 Tag: Release ## What's Changed * mongo - chore: fixing exlcudes by @jaredwray in [https://github.com/jaredwray/keyv/pull/1426](https://github.com/jaredwray/keyv/pull/1426) * mongo - fix: no longer rejecting an error when the client does not co… by @jaredwray in [https://github.com/jaredwray/keyv/pull/1450](https://github.com/jaredwray/keyv/pull/1450) * valkey - fix: updating readme to be use iovalkey by @jaredwray in [https://github.com/jaredwray/keyv/pull/1430](https://github.com/jaredwray/keyv/pull/1430) * keyv - fix: should not be setting null on empty expires by @jaredwray in [https://github.com/jaredwray/keyv/pull/1433](https://github.com/jaredwray/keyv/pull/1433) * keyv - chore: upgrading xo to 1.1.0 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1434](https://github.com/jaredwray/keyv/pull/1434) * keyv - chore: upgrading xo to 1.1.0 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1435](https://github.com/jaredwray/keyv/pull/1435) * keyv - chore: upgrading faker-js to 9.8.0 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1436](https://github.com/jaredwray/keyv/pull/1436) * keyv - chore: upgrading vitest to 3.2.3 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1437](https://github.com/jaredwray/keyv/pull/1437) * keyv - fix: handling serialization on setMany by @jaredwray in [https://github.com/jaredwray/keyv/pull/1451](https://github.com/jaredwray/keyv/pull/1451) * memcache - fix: moving keyv to peerDependency by @jaredwray in [https://github.com/jaredwray/keyv/pull/1427](https://github.com/jaredwray/keyv/pull/1427) * memcache - chore: upgrading xo to 1.0.1 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1428](https://github.com/jaredwray/keyv/pull/1428) * memcache - chore: upgrading xo to 1.1.0 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1438](https://github.com/jaredwray/keyv/pull/1438) * memcache - chore: upgrading vitest to 3.2.3 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1439](https://github.com/jaredwray/keyv/pull/1439) * memcache - fix: adding note on compression not supported by @jaredwray in [https://github.com/jaredwray/keyv/pull/1440](https://github.com/jaredwray/keyv/pull/1440) * redis - chore: upgrading xo to 1.1.0 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1441](https://github.com/jaredwray/keyv/pull/1441) * redis - chore: upgrading vitest to 3.2.3 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1442](https://github.com/jaredwray/keyv/pull/1442) * test-suite - chore: upgrading vitest to 3.2.3 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1443](https://github.com/jaredwray/keyv/pull/1443) * compress-brotli - chore: upgrading xo to 1.1.0 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1444](https://github.com/jaredwray/keyv/pull/1444) * compress-brotli - chore: upgrading compress-brotli to 1.3.13 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1445](https://github.com/jaredwray/keyv/pull/1445) * compres-brotli - chore: upgrading vitest to 3.2.3 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1446](https://github.com/jaredwray/keyv/pull/1446) * compress-gzip - chore: upgrading xo to 1.1.0 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1447](https://github.com/jaredwray/keyv/pull/1447) * compress-lz4 - chore: upgrading xo to 1.1.0 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1448](https://github.com/jaredwray/keyv/pull/1448) * compress-lz4 - chore: upgrading vitest to 3.2.3 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1449](https://github.com/jaredwray/keyv/pull/1449) **Full Changelog**: [https://github.com/jaredwray/keyv/compare/2025](https://github.com/jaredwray/keyv/compare/2025)-05-17...2025-06-09 ### 2025-05-17 URL: https://keyv.org/changelog/2025-05-17 Date: May 17, 2025 Tag: Release ## What's Changed * mongo - fix: adding in the db key to use by @olekristensen in [https://github.com/jaredwray/keyv/pull/1412](https://github.com/jaredwray/keyv/pull/1412) * sqlite - fix: fixing database close to work correctly by @jaredwray in [https://github.com/jaredwray/keyv/pull/1414](https://github.com/jaredwray/keyv/pull/1414) * sqlite - fix: updating tests to handle the close correctly by @jaredwray in [https://github.com/jaredwray/keyv/pull/1415](https://github.com/jaredwray/keyv/pull/1415) * postgres - chore: upgrading pg to 8.16.0 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1417](https://github.com/jaredwray/keyv/pull/1417) * postgres - fix: removing types.ts from coverage report by @jaredwray in [https://github.com/jaredwray/keyv/pull/1418](https://github.com/jaredwray/keyv/pull/1418) * mysql - chore: upgrading mysql2 to 3.14.1 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1419](https://github.com/jaredwray/keyv/pull/1419) * etcd - chore: upgrading vitest to 3.1.3 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1420](https://github.com/jaredwray/keyv/pull/1420) * website - chore: upgrading tsx to 4.19.4 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1421](https://github.com/jaredwray/keyv/pull/1421) * mono - chore: upgrading webpack to 5.99.8 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1422](https://github.com/jaredwray/keyv/pull/1422) * mono - chore: upgrading tsup to 8.5.0 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1423](https://github.com/jaredwray/keyv/pull/1423) * mono - chore: upgrading vitest to 3.1.3 by @jaredwray in [https://github.com/jaredwray/keyv/pull/1424](https://github.com/jaredwray/keyv/pull/1424) * mono - feat: moving all scripts and docker to a folder by @jaredwray in [https://github.com/jaredwray/keyv/pull/1425](https://github.com/jaredwray/keyv/pull/1425) ## New Contributors * @olekristensen made their first contribution in [https://github.com/jaredwray/keyv/pull/1412](https://github.com/jaredwray/keyv/pull/1412) **Full Changelog**: [https://github.com/jaredwray/keyv/compare/2025](https://github.com/jaredwray/keyv/compare/2025)-05-03...2025-05-17