JS-EasyCache

Tiny, dependency-free localStorage/sessionStorage cache with expiration, buckets, quota-aware eviction and lossless compression.

View the Project on GitHub iprodev/JS-EasyCache

Try the live demo

JS-EasyCache

npm CI license

A tiny, dependency-free cache for the browser that emulates memcache on top of localStorage (or sessionStorage). Store strings and JSON values with an expiration time, partition them into buckets, and let the library compress large values and make room when storage is full.

Install

npm install js-easycache

Or load it from a CDN as a global EasyCache:

<script src="https://cdn.jsdelivr.net/npm/js-easycache@2/dist/easycache.min.js"></script>

Usage

import EasyCache from 'js-easycache';            // ES modules
// const EasyCache = require('js-easycache');    // CommonJS
// window.EasyCache                              // <script> tag

EasyCache.set('greeting', 'Hello World!', 2);   // expires in 2 minutes
EasyCache.get('greeting');                       // 'Hello World!'

EasyCache.set('data', { name: 'Hemn', age: 26 }); // never expires
EasyCache.get('data').name;                      // 'Hemn'

EasyCache.has('data');                           // true
EasyCache.ttl('greeting');                       // ≈ 2 (minutes left)
EasyCache.remove('greeting');
EasyCache.flush();                               // clear the current bucket

Caching API responses

const user = await EasyCache.getOrSet(
  `user:${id}`,
  () => fetch(`/api/users/${id}`).then((res) => res.json()),
  10, // minutes
);

The factory runs only when the value is not cached. Concurrent calls for the same key share one request, and failed requests are not cached.

Separate caches

import { create } from 'js-easycache';

const apiCache = create({ bucket: 'api', defaultTtl: 10 });
const session = create({ storage: 'session', namespace: 'my-app' });

API

All methods are also available on instances returned by create(). Keys are strings (finite numbers are converted). time is a number of minutes.

Method Description
set(key, value, time?) Stores a value. Returns true on success and false when it could not be stored (storage unavailable, quota exhausted, or a value JSON cannot represent, such as undefined or a function). Throws TypeError for an invalid key or time.
get(key) Returns the value, or null when it is missing or expired.
has(key) true when a non-expired entry exists, including a stored null.
ttl(key) Minutes left (fractional), Infinity for no expiry, null when missing.
remove(key) Removes one entry.
keys() Keys of all live entries in the current bucket.
getOrSet(key, factory, time?) Returns the cached value, or awaits factory(), caches the result and returns it.
flush() Removes all entries in the current bucket.
flushExpired() Removes expired and unreadable entries in the current bucket.
flushAll() Removes every entry of the namespace in all buckets, plus 1.x data.
flushLegacy() Removes data written by EasyCache 1.x.
supported() Whether the storage can be used.
setBucket(name) / resetBucket() / getBucket() Switch between buckets.
enableWarnings(enabled = true) Log evictions, failed writes and corrupt entries to the console.
create(options?) Creates an independent instance (on the default export).
version The library version.

Options for create()

Option Default Description
storage 'local' 'local', 'session', or any object with getItem, setItem, removeItem, key and length.
bucket '' Partition inside the namespace.
namespace 'EasyCache' Prefix shared by all buckets. Must not contain : or start with EasyCache- (used by 1.x).
defaultTtl none Minutes used when set() gets no time. Pass 0 to set() to store without expiry anyway.
compress true Compress large values.
compressThreshold 256 Minimum length (characters) before compression is tried.
warnings false Same as enableWarnings().
migrateLegacy true Read and convert EasyCache 1.x entries.

Expiration

time is in minutes and may be fractional (0.5 is 30 seconds). Numeric strings such as '5' are accepted. 0, Infinity, null and undefined mean the entry never expires. Negative numbers, NaN and other values throw a TypeError. Expired entries are removed when they are read, by flushExpired(), and when space is needed.

Values

Strings are stored as they are. Every other value goes through JSON.stringify, so Date becomes a string, NaN becomes null, and class instances become plain objects. Use has() to tell a stored null from a missing key.

Storage limits

When the storage is full, set() first removes expired entries in every bucket. If that is not enough, it evicts entries of the current bucket, starting with the ones that expire soonest. Entries without expiry are evicted last. If the value still does not fit, set() returns false, and the previous value of that key is removed so a stale value is never served.

Security

Anything in localStorage can be read by every script running on your origin, including injected scripts (XSS). Do not cache access tokens, passwords or personal data. Compression is not encryption.

Migrating from 1.x

Data written by 1.x is converted on first read, keeping its expiry, so cached items survive the upgrade. To drop old data instead, call flushLegacy() or pass migrateLegacy: false.

Breaking changes:

Browser support

All browsers with ES2015 and Web Storage (Chrome, Edge, Firefox, Safari, and their mobile versions). Without Web Storage the cache degrades gracefully: set() returns false and get() returns null.

Demo

Try the live demo. To run it locally, build with npm run build and open demo/index.html.

Development

npm install
npm test               # unit tests (Vitest, Node and jsdom)
npm run typecheck      # TypeScript strict mode
npm run build          # dist/: ESM, CommonJS, UMD, minified UMD and types
npm run test:dist      # smoke test of every build
npm run verify         # all of the above

Releasing

  1. Update version in package.json and src/index.ts, and add a CHANGELOG.md entry.
  2. Publish a GitHub release with the tag v<version>.

The release workflow checks the tag, runs all tests and publishes to npm with provenance. It authenticates through npm Trusted Publishing or an NPM_TOKEN repository secret.

Credits

Created by Hemn Chawroka from iProDev. Compression is adapted from lz-string by pieroxy. Released under the MIT license.