@bisham/dom-storage-sync
v0.0.4
Published
A simple Js function that subscribes to storage change events i.e, localStorage, sessionStorage and Cookie Storage
Downloads
116
Maintainers
Readme
A lightweight JavaScript/TypeScript utility for subscribing to changes in browser storage mechanisms: localStorage, sessionStorage, and cookieStorage using the cookieStore API. Useful for real-time sync of storage data across browser tabs or app components.
Features
- 📦 Subscribe to localStorage, sessionStorage, or cookieStorage
- 🔄 Automatically update subscribers on
localStorage,sessionStorageandcookieStoremutations - 🔒 Type-safe with TypeScript support
- 🌐 Multi-tab change detection for
localStorageandsessionStorage
Installation
npm install @bisham/dom-storage-sync
# or
yarn add @bisham/dom-storage-syncUsage
1. Import and Use
import { getStorageSubscription } from "@bisham/dom-storage-sync";
const localStorageSub = getStorageSubscription("localStorage");
const unsubscribe = localStorageSub.subscribe(() => {
console.log("Local Storage changed:", localStorageSub.getSnapshot());
});
// Later, if needed
unsubscribe();import { getStorageSubscription } from "@bisham/dom-storage-sync";
const sessionStorageSub = getStorageSubscription("sessionStorage");
const unsubscribe = sessionStorageSub.subscribe(() => {
console.log("Session Storage changed:", sessionStorageSub.getSnapshot());
});
// Later, if needed
unsubscribe();2. Available Storage Types
'localStorage''sessionStorage''cookieStorage'
3. Example with Cookies
const cookieStorageSub = getStorageSubscription("cookieStorage");
const unsubscribe = cookieStorageSub.subscribe(() => {
console.log("Cookies updated:", cookieStorageSub.getSnapshot());
});API
getStorageSubscription(storageType)
Returns an object that allows you to subscribe to storage changes and get current snapshot.
Parameters
storageType:"localStorage" | "sessionStorage" | "cookieStorage"
Returns
{
getSnapshot: () => Record<string, string | null> | Map<string, CookieInit>,
subscribe: (callback: () => void) => () => void
}getSnapshot()returns current key-value pairs of the selected storage.subscribe(callback)triggers the callback when the storage updates. Returns anunsubscribefunction.
⚠️ Notes
- This utility is intended for client-side use only.
💡 Make sure your app runs in a secure context (HTTPS) for cookieStore to work.
📄 License
MIT © Bisham Kunwor
🧑💻 Author
- Name: Bisham Kunwor
- Email: [email protected]
- GitHub: @BishamKunwor
- Website: bishamkunwor.com.np
