session-cache-utils
Version:
Lightweight sessionStorage caching utilities for the browser.
90 lines (55 loc) β’ 2.6 kB
Markdown
# β‘οΈ session-cache-utils
> Super lightweight, zero-dependency utility to cache data in `sessionStorage` β with automatic TTL expiration, type safety, and full control.
## π Why use this?
- β
**Simple**: One function to read, one to write, one to invalidate. Thatβs it.
- π§ **Smart**: Auto-expires stale data based on TTL (in minutes).
- π§± **Type-safe**: Written in TypeScript, strongly typed all the way.
- π **Browser-native**: Uses `sessionStorage`, nothing extra.
- π¦ **Framework-agnostic**: Works in React, Next.js, Svelte, or plain JavaScript apps.
## π¦ Installation
```bash
npm install session-cache-utils
```
## Usage/Examples
```javascript
import { writeCache, readCache, invalidateCache } from "session-cache-utils";
//π Write to cache
writeCache("user-profile", { id: 42, name: "Akshit" });
//π Read from cache (if not older than 30 minutes)
const result = readCache<{ id: number; name: string }>("user-profile", 30);
console.log(result?.data); // { id: 42, name: "Akshit" }
//β Invalidate cache
invalidateCache("user-profile");
```
## π API Reference
| Method | Description | Example |
| ---------------------- | ----------------------------- | ---------------------------- |
| `readCache<T>(key, ttlMinutes)` | Reads cached data and returns it only if itβs still fresh (not older than ttlMinutes) | `readCache<User>("user-data", 30) β { data, created_at, updated_at } or null` |
| `writeCache<T>(key, value)` | Writes or updates the cache entry with current timestamps. | `writeCache("user-data", { id: 1, name: "Akshit" }) β true` |
| `invalidateCache(key)` | Removes the specified cache entry from sessionStorage | `invalidateCache("user-data") β true` |
## π¦ CachedDataShape<T>
Internal structure used to store cached entries:
```readCache``` api will always return this type for cached entry else ```null```
```javascript
type CachedDataShape<T> = {
data: T;
created_at: number;
updated_at: number;
};
```
## π§ Use Case Examples
βοΈ Store UI filters temporarily
π Cache API response for current tab
π§ Save navigation state across routes
πΎ Cache form data between page reloads
## β Things to know
Only works client-side (window required).
TTL is capped at 24 hours internally for sanity.
Falls back to null and auto-cleans expired data.
## Authors
β¨ Made with focus by Akshit
- [@akshitworkspace](https://github.com/akshitworkspace)
## License
MIT β free for personal and commercial use.