Skip to main content

JavaScript Usage

Cachemate works out of the box in pure JavaScript environments, including legacy CommonJS setups, modern ECMAScript Modules (ESM), and serverless scripts.


Import Syntax

cache.mjs
import { Client } from 'cachemate';

export const client = new Client({
memoryMaxMb: 64,
redisUrls: ['redis://127.0.0.1:6379'],
registry: {
entries: {
users: { tag: 'u', versionKey: 'cm:ver:users' },
},
},
});

Memory Fallback & The memoryMaxMb Warning

In JavaScript (where TypeScript compiler checks are not active), if you omit memoryMaxMb or pass an invalid value (e.g. NaN, negative number, or non-finite number), Cachemate gracefully falls back to a safe 64 MB in-memory LRU cache and emits an informative warning:

[cachemate] memoryMaxMb missing/invalid (got NaN) — defaulting in-memory LRU fallback to 64 MB. Pass memoryMaxMb explicitly to control process memory use.

Best Practice

Always supply memoryMaxMb in your configuration to match your container or server memory limits:

const client = new Client({
// Explicitly allocate up to 128 MB for in-memory emergency failover
memoryMaxMb: 128,
redisUrls: [process.env.REDIS_URL],
});

Zero-Config In-Memory Fallback

If you don't supply any redisUrls, Cachemate functions purely as an in-memory LRU caching layer with table versioning. This is ideal for local testing, CI test suites, or lightweight single-process services:

// Test suite or mock environment:
const testClient = new Client({
memoryMaxMb: 32,
registry: {
entries: {
products: { tag: 'p', versionKey: 'ver:products' },
},
},
});

async function runTest() {
const data = await testClient.cache({
tables: ['products'],
filters: { id: 1 },
loader: async () => ({ id: 1, name: 'Sample Item' }),
});
console.log(data); // { id: 1, name: 'Sample Item' }

await testClient.invalidate('products');
}

Connection Lifecycle & Graceful Shutdown

When shutting down your Node.js application, invoke client.close() to cleanly terminate all Redis socket connections and drain pending ref counts:

process.on('SIGTERM', async () => {
console.log('Closing Cachemate client...');
await client.close();
process.exit(0);
});