@byburri/locsess-storage-helper
v0.1.2
Published
Browser storage helper
Downloads
30
Readme
@byburri/locsess-storage-helper
A lightweight TypeScript library for working with localStorage and sessionStorage with built-in key prefixing and TTL cache.
Features
- Safe
localStorage/sessionStorageaccess with availability checks - Automatic key prefixing
- TTL cache support (expires items automatically)
clear()only removes keys created by the library- Fully typed with TypeScript
Installation
# npm
npm install @byburri/locsess-storage-helper # yarn
yarn add @byburri/locsess-storage-helperAPI
createLocalStorage(prefix?: string): LocalStorageApi - creates a localStorage wrapper with an optional key prefix.
Example:
import { createLocalStorage } from "@byburri/locsess-storage-helper";
const storage = createLocalStorage("myapp");
storage.set("token", "123");
console.log(storage.get("token")); // "123"
storage.remove("token");
storage.clear(); // removes all keys starting with "myapp-"createSessionStorage(prefix?: string): SessionStorageApi - same as createLocalStorage, but uses sessionStorage instead.
Example:
import { createSessionStorage } from "@byburri/locsess-storage-helper";
const storage = createSessionStorage("myapp");
storage.set("token", "123");
console.log(storage.get("token")); // "123"
storage.remove("token");
storage.clear(); // removes all keys starting with "myapp-"Methods
Local Storage
get(key) - Get the value for a key
set(key, value) - Set a value for a key
remove(key) - Remove a key
clear() - Remove all keys with the current prefix
Cache (TTL)
Supports caching with automatic expiration.
const storage = createLocalStorage("myapp");
// Store user object for 10 minutes
storage.cacheSet("user", { name: "Denys" }, 1000 * 60 * 10);
const user = storage.cacheGet("user"); // returns the cached value
storage.cacheRemove("user"); // remove a cached key
storage.cacheFlushExpired(); // removes all expired cache entriesKey Prefixes
By default, the library uses the prefix: locsess-
You can provide a custom prefix:
const storage = createLocalStorage("myapp");All keys will be stored as:
myapp:keyThis helps to avoid collisions with other localStorage or sessionStorage keys.
TypeScript Usage
The package is fully typed. You can use ReturnType to get API types:
import { createLocalStorage } from "@byburri/locsess-storage-helper";
type LocalStorageApi = ReturnType<typeof createLocalStorage>;
type SessionStorageApi = ReturnType<typeof createSessionStorage>;
const storage: LocalStorageApi = createLocalStorage("myapp");Generic support
const storage = createLocalStorage("myapp");
storage.set("count", 10);
const count = storage.get<number>("count");