Simple key-value storage with support for multiple backends
Keyv provides a consistent interface for key-value storage across multiple backends via storage adapters. It supports TTL based expiry, making it suitable as a cache or a persistent key-value store.
There are a few existing modules similar to Keyv, however Keyv is different because it:
Map
APIBuffer
Install Keyv.
npm install --save keyv
By default everything is stored in memory, you can optionally also install a storage adapter.
npm install --save @keyv/redis
npm install --save @keyv/valkey
npm install --save @keyv/mongo
npm install --save @keyv/sqlite
npm install --save @keyv/postgres
npm install --save @keyv/mysql
npm install --save @keyv/etcd
npm install --save @keyv/memcache
First, create a new Keyv instance.
import Keyv from 'keyv';
You can create a Keyv
instance with a generic type to enforce type safety for the values stored. Additionally, both the get
and set
methods support specifying custom types for specific use cases.
const keyv = new Keyv<number>(); // Instance handles only numbers
await keyv.set('key1', 123);
const value = await keyv.get('key1'); // value is inferred as number
You can also specify a type directly in the get
or set
methods, allowing flexibility for different types of values within the same instance.
const keyv = new Keyv(); // Generic type not specified at instance level
await keyv.set<string>('key2', 'some string'); // Method-level type for this value
const strValue = await keyv.get<string>('key2'); // Explicitly typed as string
await keyv.set<number>('key3', 456); // Storing a number in the same instance
const numValue = await keyv.get<number>('key3'); // Explicitly typed as number
This makes Keyv
highly adaptable to different data types while maintaining type safety.
Once you have created your Keyv instance you can use it as a simple key-value store with in-memory
by default. To use a storage adapter, create an instance of the adapter and pass it to the Keyv constructor. Here are some examples:
// redis
import KeyvRedis from '@keyv/redis';
const keyv = new Keyv(new KeyvRedis('redis://user:pass@localhost:6379'));
You can also pass in a storage adapter with other options such as ttl
and namespace
(example using sqlite
):
//sqlite
import KeyvSqlite from '@keyv/sqlite';
const keyvSqlite = new KeyvSqlite('sqlite://path/to/database.sqlite');
const keyv = new Keyv({ store: keyvSqlite, ttl: 5000, namespace: 'cache' });
To handle an event you can do the following:
// Handle DB connection errors
keyv.on('error', err => console.log('Connection Error', err));
Now lets do an end-to-end example using Keyv
and the Redis
storage adapter:
import Keyv from 'keyv';
import KeyvRedis from '@keyv/redis';
const keyvRedis = new KeyvRedis('redis://user:pass@localhost:6379');
const keyv = new Keyv({ store: keyvRedis });
await keyv.set('foo', 'expires in 1 second', 1000); // true
await keyv.set('foo', 'never expires'); // true
await keyv.get('foo'); // 'never expires'
await keyv.delete('foo'); // true
await keyv.clear(); // undefined
It's is just that simple! Keyv is designed to be simple and easy to use.
You can namespace your Keyv instance to avoid key collisions and allow you to clear only a certain namespace while using the same database.
const users = new Keyv(new KeyvRedis('redis://user:pass@localhost:6379'), { namespace: 'users' });
const cache = new Keyv(new KeyvRedis('redis://user:pass@localhost:6379'), { namespace: 'cache' });
await users.set('foo', 'users'); // true
await cache.set('foo', 'cache'); // true
await users.get('foo'); // 'users'
await cache.get('foo'); // 'cache'
await users.clear(); // undefined
await users.get('foo'); // undefined
await cache.get('foo'); // 'cache'
Keyv is a custom EventEmitter
and will emit an 'error'
event if there is an error. In addition it will emit a clear
and disconnect
event when the corresponding methods are called.
const keyv = new Keyv();
const handleConnectionError = err => console.log('Connection Error', err);
const handleClear = () => console.log('Cache Cleared');
const handleDisconnect = () => console.log('Disconnected');
keyv.on('error', handleConnectionError);
keyv.on('clear', handleClear);
keyv.on('disconnect', handleDisconnect);
Keyv supports hooks for get
, set
, and delete
methods. Hooks are useful for logging, debugging, and other custom functionality. Here is a list of all the hooks:
PRE_GET
POST_GET
PRE_GET_MANY
POST_GET_MANY
PRE_SET
POST_SET
PRE_DELETE
POST_DELETE
You can access this by importing KeyvHooks
from the main Keyv package.
import Keyv, { KeyvHooks } from 'keyv';
//PRE_SET hook
const keyv = new Keyv();
keyv.hooks.addHandler(KeyvHooks.PRE_SET, (key, value) => console.log(`Setting key ${key} to ${value}`));
//POST_SET hook
const keyv = new Keyv();
keyv.hooks.addHandler(KeyvHooks.POST_SET, (key, value) => console.log(`Set key ${key} to ${value}`));
In these examples you can also manipulate the value before it is set. For example, you could add a prefix to all keys.
const keyv = new Keyv();
keyv.hooks.addHandler(KeyvHooks.PRE_SET, (key, value) => {
console.log(`Setting key ${key} to ${value}`);
key = `prefix-${key}`;
});
Now this key will have prefix- added to it before it is set.
In PRE_DELETE
and POST_DELETE
hooks, the value could be a single item or an Array
. This is based on the fact that delete
can accept a single key or an Array
of keys.
Keyv uses buffer
for data serialization to ensure consistency across different backends.
You can optionally provide your own serialization functions to support extra data types or to serialize to something other than JSON.
const keyv = new Keyv({ serialize: JSON.stringify, deserialize: JSON.parse });
Warning: Using custom serializers means you lose any guarantee of data consistency. You should do extensive testing with your serialisation functions and chosen storage engine.
If you do not want to use serialization you can set the serialize
and deserialize
functions to undefined
. This will also turn off compression.
const keyv = new Keyv();
keyv.serialize = undefined;
keyv.deserialize = undefined;
The official storage adapters are covered by over 150 integration tests to guarantee consistent behaviour. They are lightweight, efficient wrappers over the DB clients making use of indexes and native TTLs where available.
Database | Adapter | Native TTL |
---|---|---|
Redis | @keyv/redis | Yes |
Valkey | @keyv/valkey | Yes |
MongoDB | @keyv/mongo | Yes |
SQLite | @keyv/sqlite | No |
PostgreSQL | @keyv/postgres | No |
MySQL | @keyv/mysql | No |
Etcd | @keyv/etcd | Yes |
Memcache | @keyv/memcache | Yes |
You can also use third-party storage adapters or build your own. Keyv will wrap these storage adapters in TTL functionality and handle complex types internally.
import Keyv from 'keyv';
import myAdapter from 'my-adapter';
const keyv = new Keyv({ store: myAdapter });
Any store that follows the Map
api will work.
new Keyv({ store: new Map() });
For example, quick-lru
is a completely unrelated module that implements the Map API.
import Keyv from 'keyv';
import QuickLRU from 'quick-lru';
const lru = new QuickLRU({ maxSize: 1000 });
const keyv = new Keyv({ store: lru });
The following are third-party storage adapters compatible with Keyv:
Keyv is designed to be easily embedded into other modules to add cache support. The recommended pattern is to expose a cache
option in your modules options which is passed through to Keyv. Caching will work in memory by default and users have the option to also install a Keyv storage adapter and pass in a connection string, or any other storage that implements the Map
API.
You should also set a namespace for your module so you can safely call .clear()
without clearing unrelated app data.
Inside your module:
class AwesomeModule {
constructor(opts) {
this.cache = new Keyv({
uri: typeof opts.cache === 'string' && opts.cache,
store: typeof opts.cache !== 'string' && opts.cache,
namespace: 'awesome-module'
});
}
}
Now it can be consumed like this:
import AwesomeModule from 'awesome-module';
// Caches stuff in memory by default
const awesomeModule = new AwesomeModule();
// After npm install --save keyv-redis
const awesomeModule = new AwesomeModule({ cache: 'redis://localhost' });
// Some third-party module that implements the Map API
const awesomeModule = new AwesomeModule({ cache: some3rdPartyStore });
Keyv supports gzip
and brotli
compression. To enable compression, pass the compress
option to the constructor.
import Keyv from 'keyv';
import KeyvGzip from '@keyv/compress-gzip';
const keyvGzip = new KeyvGzip();
const keyv = new Keyv({ compression: KeyvGzip });
You can also pass a custom compression function to the compression
option. Following the pattern of the official compression adapters.
Great! Keyv is designed to be easily extended. You can build your own compression adapter by following the pattern of the official compression adapters based on this interface:
interface CompressionAdapter {
async compress(value: any, options?: any);
async decompress(value: any, options?: any);
async serialize(value: any);
async deserialize(value: any);
}
In addition to the interface, you can test it with our compression test suite using @keyv/test-suite:
import { keyvCompresstionTests } from '@keyv/test-suite';
import KeyvGzip from '@keyv/compress-gzip';
keyvCompresstionTests(test, new KeyvGzip());
Returns a new Keyv instance.
The Keyv instance is also an EventEmitter
that will emit an 'error'
event if the storage adapter connection fails.
Type: KeyvStorageAdapter
Default: undefined
The connection string URI.
Merged into the options object as options.uri.
Type: String
Default: 'keyv'
This is the namespace for the current instance. When you set it it will set it also on the storage adapter. This is the preferred way to set the namespace over .opts.namespace
.
Type: Object
The options object is also passed through to the storage adapter. Check your storage adapter docs for any extra options.
Type: String
Default: 'keyv'
Namespace for the current instance.
Type: Number
Default: undefined
Default TTL. Can be overridden by specififying a TTL on .set()
.
Type: @keyv/compress-<compression_package_name>
Default: undefined
Compression package to use. See Compression for more details.
Type: Function
Default: JSON.stringify
A custom serialization function.
Type: Function
Default: JSON.parse
A custom deserialization function.
Type: Storage adapter instance
Default: new Map()
The storage adapter instance to be used by Keyv.
Keys must always be strings. Values can be of any type.
Set a value.
By default keys are persistent. You can set an expiry TTL in milliseconds.
Returns a promise which resolves to true
.
Returns a promise which resolves to the retrieved value.
Type: Boolean
Default: false
If set to true the raw DB object Keyv stores internally will be returned instead of just the value.
This contains the TTL timestamp.
Deletes an entry.
Returns a promise which resolves to true
if the key existed, false
if not.
Delete all entries in the current namespace.
Returns a promise which is resolved when the entries have been cleared.
Iterate over all entries of the current namespace.
Returns a iterable that can be iterated by for-of loops. For example:
// please note that the "await" keyword should be used here
for await (const [key, value] of this.keyv.iterator()) {
console.log(key, value);
};
Type: String
The namespace for the current instance. This will define the namespace for the current instance and the storage adapter. If you set the namespace to undefined
it will no longer do key prefixing.
const keyv = new Keyv({ namespace: 'my-namespace' });
console.log(keyv.namespace); // 'my-namespace'
here is an example of setting the namespace to undefined
:
const keyv = new Keyv();
console.log(keyv.namespace); // 'keyv' which is default
keyv.namespace = undefined;
console.log(keyv.namespace); // undefined
Type: Number
Default: undefined
Default TTL. Can be overridden by specififying a TTL on .set()
. If set to undefined
it will never expire.
const keyv = new Keyv({ ttl: 5000 });
console.log(keyv.ttl); // 5000
keyv.ttl = undefined;
console.log(keyv.ttl); // undefined (never expires)
Type: Storage adapter instance
Default: new Map()
The storage adapter instance to be used by Keyv. This will wire up the iterator, events, and more when a set happens. If it is not a valid Map or Storage Adapter it will throw an error.
import KeyvSqlite from '@keyv/sqlite';
const keyv = new Keyv();
console.log(keyv.store instanceof Map); // true
keyv.store = new KeyvSqlite('sqlite://path/to/database.sqlite');
console.log(keyv.store instanceof KeyvSqlite); // true
Type: Function
Default: JSON.stringify
A custom serialization function used for any value.
const keyv = new Keyv();
console.log(keyv.serialize); // JSON.stringify
keyv.serialize = value => value.toString();
console.log(keyv.serialize); // value => value.toString()
Type: Function
Default: JSON.parse
A custom deserialization function used for any value.
const keyv = new Keyv();
console.log(keyv.deserialize); // JSON.parse
keyv.deserialize = value => parseInt(value);
console.log(keyv.deserialize); // value => parseInt(value)
Type: CompressionAdapter
Default: undefined
this is the compression package to use. See Compression for more details. If it is undefined it will not compress (default).
import KeyvGzip from '@keyv/compress-gzip';
const keyv = new Keyv();
console.log(keyv.compression); // undefined
keyv.compression = new KeyvGzip();
console.log(keyv.compression); // KeyvGzip
Type: Boolean
Default: true
If set to true
Keyv will prefix all keys with the namespace. This is useful if you want to avoid collisions with other data in your storage.
const keyv = new Keyv({ useKeyPrefix: false });
console.log(keyv.useKeyPrefix); // false
keyv.useKeyPrefix = true;
console.log(keyv.useKeyPrefix); // true
We welcome contributions to Keyv! 🎉 Here are some guides to get you started with contributing: