Skip to content

Cache

One cache API, swappable drivers. Pick a backend at boot — localStorage, sessionStorage, in-memory map, or any of those with encryption layered on — then call cache.set / cache.get / cache.remove / cache.clear everywhere else. TTL, key prefixing, and default-fallbacks built in. Pairs cleanly with @mongez/atom’s persist slot.

Highlighted features

One API, five drivers

Plain + encrypted variants for localStorage / sessionStorage, plus a runtime in-memory driver. Configure once; swap drivers without touching call sites.

Per-entry TTL

cache.set(“token”, value, 60 * 15) — entries expire on read after their TTL. Or set a default for every key via configuration.

Encryption-at-rest

EncryptedLocalStorageDriver + EncryptedSessionStorageDriver run values through your encrypt/decrypt pair before writing. Sensitive cache values stay opaque on disk.

Key prefixing

prefix: “shop-” namespaces every key so multiple apps on the same domain can’t collide. Set once at config time.

Pairs with @mongez/atom

Any driver satisfies PersistAdapter — drop it into an atom’s persist slot and the atom hydrates from cache + writes through on update.

SSR-safe via RunTimeDriver

No Web Storage dependency. Use in tests or SSR paths where localStorage doesn’t exist; switch back to web storage on the client.

Install

Terminal window
npm install @mongez/cache

@mongez/encryption is an optional peer — install only when using the Encrypted* drivers.

Quick peek

import cache, { PlainLocalStorageDriver, setCacheConfigurations } from "@mongez/cache";
setCacheConfigurations({
driver: new PlainLocalStorageDriver(),
prefix: "shop-", // namespace every key
expiresAfter: 60 * 60, // optional default TTL: 1 hour
});
cache.set("user", { id: 1, name: "Hasan" });
cache.set("token", "abc123", 60 * 15); // override the default TTL
cache.get("user"); // { id: 1, name: "Hasan" }

Pick a backend at boot, then use the same API everywhere.

Available drivers

DriverPersistenceNotes
PlainLocalStorageDriverCross-sessionJSON-serialised; supports TTL envelope
PlainSessionStorageDriverTab-lifetimeSame contract as local-storage variant
EncryptedLocalStorageDriverCross-sessionEncrypt/decrypt before writing
EncryptedSessionStorageDriverTab-lifetimeEncrypted sessionStorage variant
RunTimeDriverIn-memory (lost on reload)SSR-safe; no Web Storage dependency

All drivers implement CacheDriverInterface.

Key pitfalls

  • setCacheConfigurations must be called before first use. The singleton’s driver is undefined until you call it; cache.set(...) before configuring throws.
  • Web Storage drivers throw on the server (no localStorage in Node). Gate driver selection with typeof window === "undefined" and fall back to RunTimeDriver for SSR paths.
  • RunTimeDriver instances are not shared. Two instances have independent stores; no global in-memory registry.

Where to go next