:zap: localstorage-slim.js :zap:
An ultra slim localstorage wrapper with optional support for ttl and encryption
🌟 Highlights 🌟
- 📦 A localStorage wrapper with 0 DEPENDENCIES in pure JS (Typescript)!
- 🔥 A super light-weight library
- ⏰ Supports TTL (i.e. expiry of data in LocalStorage)
- 🧬 Supports encryption/decryption
- ⚜️ Store data in multiple formats (numbers, strings, objects, arrays, ...) with checks for cyclic references
- 🌐 Works everywhere (falls back to an in-memory store when localStorage is unavailable/blocked due to a security policy, for example: within incognito mode)
- ⚙️ Configurable to use with sessionStorage or even a custom store that implements the Storage interface.
- 🎀 Framework agnostic!
➕ Install
# you can install typeahead with npm
$ npm install --save localstorage-slim
# Alternatively you can use Yarn
$ yarn add localstorage-slim
Then include the library in your App/Page.
As a module,
import ls from 'localstorage-slim';
var ls = require('localstorage-slim');
In the browser context,
<script src="./node_modules/localstorage-slim/dist/localstorage-slim.js"></script>
<script src="https://cdn.jsdelivr.net/npm/localstorage-slim"></script>
<script src="https://unpkg.com/localstorage-slim@2.7.0/dist/localstorage-slim.js"></script>
The library will be available as a global object at window.ls
🌱 Usage
Typical usage of localstorage-slim is as follows:
Javascript
const value = {
a: new Date(),
b: null,
c: false,
d: 'superman',
e: 1234
}
ls.set('key1', value);
ls.get('key1');
ls.set('key2', value, { ttl: 5 });
ls.get('key2');
ls.get('key2');
ls.set('key3', value, { encrypt: true });
ls.get('key3', { decrypt: true });
LocalStorage-slim
provides you a config object (ls.config
) which can be modified to suit your needs. The available config parameters are as follows and all of them are completely OPTIONAL
Parameter | Description | Default |
---|
ttl?: number|null | Allows you to set a global TTL(time to live) in seconds which will be used for every item stored in the localStorage. Global ttl can be overriden with the ls.set()/ls.get() API. | null |
encrypt?: boolean | Allows you to setup global encryption of the data stored in localStorage Details. It can be overriden with the ls.set()/ls.get() API | false |
decrypt?: boolean | Allows you to decrypt encrypted data stored in localStorage. Used only by the ls.get() API | undefined |
encrypter?: (data: unknown, secret: string): string | The encryption function to be used. A default implementation only obfuscates the value. This function can be overriden with the ls.set()/ls.get() API. | Obfuscation |
decrypter?: (encryptedString: string, secret: string): unknown | A decryption function to be used. A default implementation only performs deobfuscation. This function can be overriden with the ls.set()/ls.get() API. | deobfuscation |
secret?: unknown | Allows you to set a secret key that will be passed to the encrypter/decrypter functions as a parameter. The default implementation accepts a number. Global secret can be overriden with the ls.set()/ls.get() API. | |
storage?: Storage | Allows you to define the Storage to use: localStorage , sessionStorage or even a custom store that implements the Storage interface. By default, localStorage is used and if localStorage is unavailable, then a fallback in-memory store is used | localStorage |
LocalStorage-slim allows you to encrypt the data that will be stored in your localStorage.
ls.config.encrypt = true;
ls.config.secret = 89;
Enabling encryption ensures that the data stored in your localStorage will be unreadable by majority of the users. Be aware of the fact that default implementation is not a true encryption but a mere obfuscation to keep the library light in weight. You can customize the encrypter
/decrypter
functions to write your own algorithm or to use a secure encryption algorithm like AES, TDES, RC4 or rabbit via CryptoJS to suit your needs.
To use a library like CryptoJS, update the following config options -
ls.config.encrypt = true;
ls.config.secret = 'secret-password';
ls.config.encrypter = (data: unknown, secret: string): string => 'encrypted string';
ls.config.decrypter = (encryptedString: string, secret: string): unknown => 'original data';
As seen, you can easily override the encrypter
and decrypter
functions with your own implementation of encryption/decryption logic to secure your data. Some examples can be found here.
ls.set(...);
ls.get(...);
ls.set("key", "value", { secret: 'xyz'});
ls.get("key", { secret: 'xyz'});
⚠️ Note: It is recommended that you do not save user passwords or credit card details in LocalStorage (whether they be encrypted or not).
⚙️ Using sessionStorage/custom store
By configuring the storage
config option, you can easily use another storage instead of the default localStorage
.
ls.config.storage = sessionStorage;
ls.config.storage = (() => {
const store = {
};
return store;
})()
Note: If you use custom storage, it must implement the Storage interface.
✨ API
The Api is very similar to that of the native LocalStorage API
.
Sets an item in the LocalStorage. It can accept 3 arguments
key: string
[Required] - The key with which the value should be associatedvalue: string|Date|Number|Object|Boolean|Null
[Required] - The value to be storedconfig: Config
[Optional] - This argument accepts the same properties (except storage
property) as the global config object. Defaults to an empty object
Returns false
if there was an error, else returns undefined
.
const res = ls.set('key', 'value');
console.log('Value =>', res);
ls.config.ttl = 3;
ls.set('key', 'value');
ls.set('key', 'value', { ttl: 5 });
ls.set('key', 'value', { encrypt: true });
Retrieves the Data associated with the key stored in the LocalStorage. It accepts 2 arguments -
key: string
[Required] - The key with which the value is associatedconfig: Config
[Optional] - This argument accepts the same properties (except storage
property) as the global config object. Defaults to an empty object
If the passed key does not exist, it returns null
.
const value = ls.get('key');
console.log('Value =>', value);
ls.get('key');
ls.get('key', { decrypt: true });
ls.config.encrypt = true;
ls.get('key');
Flushes expired items in the localStorage. This function is called once automatically on initialization. It can accept an optional argument force: boolean
that defaults to false
. If set to true
, it force-flushes all items including the ones that haven't expired yet. Note that doing flush(true)
only affects items that were due to expire sometime in future (i.e. they had a TTL set on them). To remove data, whether or not it has a TTL, use remove()
or clear()
.
ls.flush();
ls.flush(true);
Accepts the key: string
as an argument to remove the data associated with it.
ls.remove('key');
Clears the entire localstorage linked to the current domain.
ls.clear();
💠 Screenshot
❕ Gotchas
When localStorage is not supported by a browser, we fallback to MemoryStorage
. For websites that don't do full page loads, like SPA's, this is a perfect fallback. But for MPA's, though page crashes get prevented, data is not persisted between page loads.
🧑💻 Contribute
Interested in contributing features and fixes?
Read more on contributing.
📝 Changelog
See the Changelog
📄 License
MIT © Digital Fortress