Skip to content

nwoltman/web-storage

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

@nwoltman/web-storage

NPM Version Build Status

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.

"It's been done before"

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

API

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.

set(key, value)

  • key (string) - The storage key to write.
  • value (any) - The value to serialize and store.
LocalStorage.set('settings', { theme: 'dark' });

get(key[, defaultValue])

  • 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
  • Returns (any) - The deserialized stored value or the default value.
const settings = LocalStorage.get('settings', { theme: 'light' });

remove(key)

  • key (string) - The storage key to remove.
LocalStorage.remove('settings');

Custom WebStorage

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.

createWebStorage(serializer)

  • serializer - An object that implements stringify(value: any) => string and parse(str: string) => any methods.
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');

About

Convenient interfaces wrapping browser Web Storage APIs

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors