keyvhq
keyvhq
keyvhq provides @keyvhq/core plus adapters and decorators for building a simple key-value cache with optional persistence.
Quick Start
Install core:
npm install @keyvhq/core
Use in-memory storage:
const Keyv = require('@keyvhq/core')
const cache = new Keyv()
await cache.set('greeting', 'hello', 1000)
const value = await cache.get('greeting')
Use a Redis adapter:
npm install @keyvhq/core @keyvhq/redis
const Keyv = require('@keyvhq/core')
const KeyvRedis = require('@keyvhq/redis')
const cache = new Keyv({
store: new KeyvRedis('redis://user:pass@localhost:6379'),
namespace: 'app-cache'
})
Recommended Workflow
- Start with
@keyvhq/corein memory for local development. - Add a storage adapter only when persistence or shared cache is needed.
- Set
namespaceper module to avoid collisions and accidental global clears. - Use TTL in milliseconds, either globally (
ttloption) or perset. - Keep cache operations behind one service/module so adapter changes stay isolated.
Core API
new Keyv(options): create instance.set(key, value, ttl?): store value, optional TTL in milliseconds.get(key): read value.has(key): check existence.delete(key): remove one key.clear(): remove all keys in the current namespace.iterator(): async iterate entries (avoid for large datasets).
Common Options
store: adapter instance (default is in-memoryMap).namespace: key namespace to isolate data.ttl: default TTL in milliseconds.serialize/deserialize: custom serialization for advanced types.raw: return internal stored object including expiry metadata.
Adapter Selection
Choose an official adapter based on runtime and infrastructure:
@keyvhq/redis: low-latency shared cache, easy horizontal scaling.@keyvhq/mongo: Mongo-backed cache persistence.@keyvhq/mysql: MySQL or MariaDB-backed storage.@keyvhq/postgres: PostgreSQL-backed storage.@keyvhq/sqlite: file-based local persistence.@keyvhq/file: lightweight JSON/file storage.keyv-s3: S3 object storage adapter for large, low-cost cache persistence.
Connector Setup Snippets
Use one connector at a time as store:
Redis (@keyvhq/redis)
npm install @keyvhq/core @keyvhq/redis
const Keyv = require('@keyvhq/core')
const KeyvRedis = require('@keyvhq/redis')
const cache = new Keyv({
store: new KeyvRedis('redis://user:pass@localhost:6379'),
namespace: 'app-cache'
})
Mongo (@keyvhq/mongo)
npm install @keyvhq/core @keyvhq/mongo
const Keyv = require('@keyvhq/core')
const KeyvMongo = require('@keyvhq/mongo')
const cache = new Keyv({
store: new KeyvMongo('mongodb://user:pass@localhost:27017/dbname'),
namespace: 'app-cache'
})
MySQL (@keyvhq/mysql)
npm install @keyvhq/core @keyvhq/mysql
const Keyv = require('@keyvhq/core')
const KeyvMySQL = require('@keyvhq/mysql')
const cache = new Keyv({
store: new KeyvMySQL('mysql://user:pass@localhost:3306/dbname'),
namespace: 'app-cache'
})
PostgreSQL (@keyvhq/postgres)
npm install @keyvhq/core @keyvhq/postgres
const Keyv = require('@keyvhq/core')
const KeyvPostgres = require('@keyvhq/postgres')
const cache = new Keyv({
store: new KeyvPostgres('postgresql://user:pass@localhost:5432/dbname'),
namespace: 'app-cache'
})
SQLite (@keyvhq/sqlite)
npm install @keyvhq/core @keyvhq/sqlite
const Keyv = require('@keyvhq/core')
const KeyvSQLite = require('@keyvhq/sqlite')
const cache = new Keyv({
store: new KeyvSQLite('sqlite://path/to/database.sqlite'),
namespace: 'app-cache'
})
File (@keyvhq/file)
npm install @keyvhq/core @keyvhq/file
const Keyv = require('@keyvhq/core')
const KeyvFile = require('@keyvhq/file')
const cache = new Keyv({
store: new KeyvFile({ filename: './.cache/keyv.json' }),
namespace: 'app-cache'
})
S3 (keyv-s3)
npm install @keyvhq/core keyv-s3 @aws-sdk/client-s3
const Keyv = require('@keyvhq/core')
const KeyvS3 = require('keyv-s3')
const cache = new Keyv({
store: new KeyvS3({
region: 'us-east-1',
namespace: 'app-cache',
accessKeyId: process.env.S3_ACCESS_KEY_ID,
secretAccessKey: process.env.S3_SECRET_ACCESS_KEY
})
})
Decorators
Use decorators for specialized behavior:
@keyvhq/compress: compress stored payloads.@keyvhq/memoize: memoize function calls through Keyv.@keyvhq/multi: combine local and remote stores.@keyvhq/offline: add offline-aware behavior.@keyvhq/stats: collect usage metrics over time.
Integration Pattern For Libraries
When adding cache support to a module:
- Expose a
cacheoption in module configuration. - Accept any Keyv-compatible store.
- Default to in-memory behavior when no cache is passed.
- Set a dedicated
namespacebefore callingclear().
function createClient({ cache = new Keyv({ namespace: 'my-module' }) } = {}) {
return {
async getOrFetch(key, fetcher, ttl) {
const cached = await cache.get(key)
if (cached !== undefined) return cached
const value = await fetcher()
await cache.set(key, value, ttl)
return value
}
}
}
Reliability Notes
- TTL values are milliseconds.
clear()without a namespace can wipe all entries in that store.- Storage adapter errors should be handled close to cache boundaries.
- For bulk iteration or analytics, prefer native database tooling over
iterator().
References
- Keyv monorepo:
https://github.com/microlinkhq/keyvhq - Root docs:
https://github.com/microlinkhq/keyvhq/blob/master/README.md - Keyv S3 adapter:
/Users/kikobeats/Projects/microlink/keyv-s3
More from microlinkhq/skills
optimo
Optimize and convert images and videos using format-specific compression pipelines on top of ImageMagick and FFmpeg. Use when users need to reduce image or video file sizes, batch-optimize a media directory, convert between formats (JPEG, PNG, WebP, AVIF, HEIC, JXL, MP4, WebM, MOV), resize media by percentage/dimensions/target file size, strip audio tracks from videos, or output optimized images as data URLs.
49k8s-hpa-cost-tuning
Tune Kubernetes HPA scale-up/down behavior, topology spread, and resource requests to reduce idle cluster capacity. Use when users need to audit cluster costs on a schedule, analyze post-incident scaling behavior, investigate why replicas or nodes do not scale down, or reduce over-reservation and wasted compute resources.
32nodejs-performance
Identify, validate, and ship production-safe Node.js optimizations with execution time as the primary objective. Use when users ask to reduce latency (p50/p95/p99), improve throughput, and then reduce CPU/memory/event-loop lag/FD pressure or retry amplification, using one-PR-per-improvement workflows with benchmarks.
29use-pnpm
Always use pnpm as the package manager. Use when installing, adding, or removing dependencies, running scripts, or any npm/yarn/pnpm command. Replaces npm and yarn with pnpm equivalents.
11browserless
Automate headless Chrome with a high-level Puppeteer wrapper for screenshots, PDFs, and content extraction. Use when users need to capture web page screenshots or PDFs programmatically, extract rendered HTML or text from JavaScript-heavy pages, check URL status codes, run Lighthouse audits, or build reliable headless browser automation pipelines.
3microlink-api
Extract metadata, take screenshots, generate PDFs, and scrape custom data from URLs via Microlink API and MQL. Use when users need to build link previews from URLs, capture web page screenshots or PDFs programmatically, scrape DOM elements with CSS selectors, or get structured data from any web page without managing browser infrastructure.
3