| name | stacks-cache |
| description | Use when implementing caching in Stacks — memory cache, Redis cache, cache-aside pattern (getOrSet), TTL management, cache stats, or cache configuration. Covers @stacksjs/cache and config/cache.ts. |
| license | MIT |
| compatibility | Bun >= 1.3.0, TypeScript |
| allowed-tools | Read Edit Write Bash Grep Glob |
Stacks Cache
Key Paths
- Core package:
storage/framework/core/cache/src/
- Configuration:
config/cache.ts
- Cache storage:
storage/framework/cache/
Cache API (StacksCache)
import { cache, memory } from '@stacksjs/cache'
await cache.get<string>('key')
await cache.set('key', 'value', 3600)
await cache.setForever('key', 'value')
await cache.mget<string>(['key1', 'key2'])
await cache.mset([{ key: 'k1', value: 'v1', ttl: 60 }, ...])
const value = await cache.getOrSet('expensive-key', async () => {
return await computeExpensiveValue()
}, 3600)
await cache.del('key')
await cache.del(['key1', 'key2'])
await cache.deleteMany(['key1', 'key2'])
await cache.remove('key')
await cache.has('key')
await cache.missing('key')
const value = await cache.take<string>('key')
await cache.getTtl('key')
await cache.ttl('key', 7200)
await cache.clear()
await cache.flush()
const stats = await cache.getStats()
const keys = await cache.keys('user:*')
await cache.close()
await cache.disconnect()
Factory Functions
import { createMemoryCache, createRedisCache, createCache } from '@stacksjs/cache'
const memCache = createMemoryCache({
stdTTL: 3600,
checkPeriod: 120,
maxKeys: -1,
useClones: true,
prefix: 'app:'
})
const redisCache = createRedisCache({
url: 'redis://localhost:6379',
host: 'localhost',
port: 6379,
username: undefined,
password: undefined,
database: 0,
tls: false,
stdTTL: 3600,
prefix: 'app:'
})
const cache = createCache('memory')
const cache = createCache('redis', { host: 'localhost' })
config/cache.ts
{
driver: 'memory',
prefix: 'stacks',
ttl: 3600,
maxKeys: -1,
useClones: true,
drivers: {
redis: { host: 'localhost', port: 6379 },
memory: {}
}
}
Default Instance
cache — default memory cache (pre-configured)
memory — alias for cache
Gotchas
- Default driver is
memory — data lost on restart
- Redis driver requires a running Redis server
getOrSet() is the cache-aside pattern — fetches only on miss
useClones: true means mutations to retrieved objects don't affect cache
take() atomically gets and deletes — useful for one-time tokens
- Cache stats track hits, misses, and hit rate — useful for tuning
keys() supports glob patterns for key listing
- Framework caches (auto-imports, discovered packages) are in
storage/framework/cache/
- Use
buddy clean or buddy fresh to clear framework caches