Skip to content
Niket Pathak edited this page Apr 15, 2024 · 6 revisions

1. How to use localStorage and sessionStorage together with this library ?

To to use both sessionStorage and localStorage together with this library with ESM, you will have to duplicate your imports, for example

import ls from 'localstorage-slim';
import ss from 'localstorage-slim';


ss.config.storage = sessionStorage;  // configure this instance to use sessionStorage globally
// ls.config.storage = localStorage; (this is not required since the library defaults to using localStorage)

ss.set('item 1', 'value 1'); // stored in sessionStorage
ls.set('item A', 'value A'); // stored in localStorage

If you are using a CDN, and wish to use the same library for both local + session storage, you can achieve that by doing

// duplicate the library (i.e create 2 different instances of the same library)
window.ss = {
 ...window.ls
} ;

window.ss.config.storage = sessionStorage; // configure this instance to use sessionStorage globally
// window.ls.config.storage = localStorage; // this line is not needed as it defaults to using localStorage

window.ss.set('item 1', 'value 1'); // stored in sessionStorage
window.ls.set('item A', 'value A'); // stored in localStorage

Note: Switching between 2 different storage types on the fly within the same instance is not supported. You can use either localStorage or sessionStorage but not both on the same instance. As an example, imagine that your global storage config uses the default value, then doing (ls.set('x', {storage: sessionStorage}); ) has no effect because the storage option is completely ignored while using the get() or set() API. The value will be set in localStorage and not in sessionStorage. To use sessionStorage alone, you must set the storage config option globally before using the get()/set() API


Clone this wiki locally