Provides convenient interfaces wrapping browser
Web Storage APIs
(localStorage/sessionStorage) that make it easy to safely use those APIs and
store/retrieve any type of data.
Yeah, there's a bunch of packages like this one on npm and they all do about the same thing. Here's what this particular one offers:
- Full safety against errors when the web storage API is not available
- In-memory fallback when the web storage API is not available
- JSON serialization/deserialization by default so any data type can b e stored
- Custom serialization in case you need more control
- Very small package size
- Full TypeScript support
- 100% test coverage
import { LocalStorage, SessionStorage } from '@nwoltman/web-storage';LocalStorage and SessionStorage provide the same API. Values are serialized
with JSON.stringify() when written and parsed with JSON.parse() when read.
key(string) - The storage key to write.value(any) - The value to serialize and store.
LocalStorage.set('settings', { theme: 'dark' });key(string) - The storage key to read.defaultValue(any) - Optional value returned when the key is missing, stored JSON cannot be parsed, or storage access fails.- Default:
null
- Default:
- Returns (any) - The deserialized stored value or the default value.
const settings = LocalStorage.get('settings', { theme: 'light' });key(string) - The storage key to remove.
LocalStorage.remove('settings');The LocalStorage and SessionStorage interfaces serialize/deserialize data
using JSON.stringify/JSON.parse by default. To use a different serializer,
you can create custom interfaces using the createWebStorage function.
serializer- An object that implementsstringify(value: any) => stringandparse(str: string) => anymethods.
import { createWebStorage } from '@nwoltman/web-storage';
const LocalBase64Storage = createWebStorage('localStorage', {
stringify: (value) => btoa(String(value)),
parse: (value) => atob(value),
});
LocalBase64Storage.set('token', 'abc123');
const token = LocalBase64Storage.get('token');