CacheFirst is a ismorphic caching library that offers fluent APIs for caching JSON, Blob, Text, and ArrayBuffer data.
npm install cachefirstCacheFirst is a lightweight, isomorphic JavaScript library that provides a cache-first strategy for fetching and storing data in web applications. It supports caching in localStorage, IndexedDB, and in-memory, making it ideal for fast, reliable data access and offline experiences.
Current version: 0.6.0
cacheKey option)ttl option in ms)clear, clearAll)setCatch / .catch() chain)html
`
$3
`bash
npm install cachefirst
`Basic Usage
`js
CacheFirst.fetch('https://api.example.com/data')
.json((data, isFresh, response) => {
console.log('Data', data);
console.log('Fresh from network?', isFresh);
})
.catch(err => console.error(err));
`
isFresh is false for an immediate cached emission (if present) and true when the network response (if different) arrives.Advanced Usage
$3
`js
CacheFirst.fetch('https://api.example.com/user/123', { method: 'GET' }, { cacheKey: 'user:123' })
.json(cb);
`
$3
`js
CacheFirst.fetch('https://api.example.com/config', { method: 'GET' }, { ttl: 5 60 1000 })
.json(cb);
`
$3
`js
CacheFirst.fetch('https://api.example.com/list', { headers: { 'X-Feature': 'A' } }, { ttl: 10000, cacheKey: 'list:A' })
.json(cb);
`
$3
`js
await CacheFirst.clear('user:123'); // remove a specific entry
await CacheFirst.clearAll(); // purge everything managed by CacheFirst
`
$3
`js
CacheFirst.setCatch(err => console.warn('CacheFirst error', err));
`
Or per-call chain:
`js
CacheFirst.fetch(url).json(cb).catch(err => console.error(err));
`API Reference
$3
cacheOptions supports:
- cacheKey?: string custom key overriding auto-hash
- ttl?: number milliseconds-to-live; expired entries are purged lazilyReturns a chain object with:
-
.json(handler)
- .text(handler)
- .blob(handler)
- .arrayBuffer(handler)
- .catch(handler) set error callbackHandler signature:
`ts
(data: any, isFresh: boolean, response?: Response) => void
`$3
Remove a specific cached entry (all tiers).$3
Remove all entries created via CacheFirst.$3
Set a global error handler.How It Works
1. Derives (or uses provided) cache key.
2. Emits cached data (if present & not expired) immediately.
3. Performs a network fetch with a cache-busting query param (userLocalTime).
4. Clones response; reads body twice safely.
5. Hashes body with the response reader function name to detect meaningful changes.
6. Updates cache only if content hash differs.
7. Emits fresh data if changed.TypeScript
Basic typings are included (see index.d.ts).Sample
See sample.html` for a runnable demonstration.