All Projects → digitalfortress-tech → localstorage-slim

digitalfortress-tech / localstorage-slim

Licence: MIT license
An ultra slim localstorage wrapper with optional support for ttl and encryption

Programming Languages

javascript
184084 projects - #8 most used programming language
typescript
32286 projects
Makefile
30231 projects

Projects that are alternatives of or similar to localstorage-slim

localDataStorage
💼 A handy wrapper for HTML5 localStorage that seamlessly gets/sets primitive values (Array, Boolean, Date, Float, Integer, Null, Object or String); provides simple data scrambling; intelligently compresses strings; permits query by key as well as query by value and promotes shared storage segmentation in the same domain. Key names and values ar…
Stars: ✭ 42 (-10.64%)
Mutual labels:  localstorage-api, localstorage-wrapper
storm
🌐⚡️LocalStorage manager library for JavaScript
Stars: ✭ 14 (-70.21%)
Mutual labels:  localstorage, localstorage-api
lookie
Store your data in localStorage with optional expiration time. Almost like a cookie.
Stars: ✭ 78 (+65.96%)
Mutual labels:  localstorage, localstorage-api
h5webstorage
Web Storage for Angular 2
Stars: ✭ 38 (-19.15%)
Mutual labels:  localstorage
react-nodejs-mongodb-crud
👨‍💻 Fullstack web app built with MongoDB, NodeJs, React and Redux. Features: Protected routes client/server side, MaterialUI layout
Stars: ✭ 91 (+93.62%)
Mutual labels:  localstorage
WebReader
基于HTML5开发的WebApp阅读器
Stars: ✭ 19 (-59.57%)
Mutual labels:  localstorage
theme-change
Change CSS theme with toggle, buttons or select using CSS custom properties and localStorage
Stars: ✭ 283 (+502.13%)
Mutual labels:  localstorage
kesho
store cache any data type string, boolean, jsonObject, jsonArray, .....
Stars: ✭ 19 (-59.57%)
Mutual labels:  localstorage
kurimudb
⚓ 足够简单的前端存储解决方案
Stars: ✭ 213 (+353.19%)
Mutual labels:  localstorage
WaWebSessionHandler
(DISCONTINUED) Save WhatsApp Web Sessions as files and open them everywhere!
Stars: ✭ 27 (-42.55%)
Mutual labels:  localstorage
phaser-super-storage
A cross platform storage plugin for Phaser
Stars: ✭ 49 (+4.26%)
Mutual labels:  localstorage
elm-storage
Unified interface for accessing and modifying LocalStorage, SessionStorage and Cookies
Stars: ✭ 13 (-72.34%)
Mutual labels:  localstorage
localstorage-manager
LocalStorage Manager is a Chrome extension to add, edit, remove, export and import local storage and session storage data
Stars: ✭ 37 (-21.28%)
Mutual labels:  localstorage
redux-tab-sync
open this twice and play around
Stars: ✭ 22 (-53.19%)
Mutual labels:  localstorage
host-webfonts-locally
OMGF automagically caches the Google Fonts used by your theme/plugins locally. No configuration (or brains) required!
Stars: ✭ 13 (-72.34%)
Mutual labels:  localstorage
speechly expense tracker project
This is a code repository for the corresponding video tutorial
Stars: ✭ 285 (+506.38%)
Mutual labels:  localstorage
Materialstartpage
Save your favorite sites with stylish using Local Storage
Stars: ✭ 12 (-74.47%)
Mutual labels:  localstorage
client-persist
Offline storage for your web client. Supports IndexedDB, WebSQL, localStorage and sessionStorage with an easy to crawl with API.
Stars: ✭ 14 (-70.21%)
Mutual labels:  localstorage
Paper
A minimal notes application in Jetpack Compose with MVVM architecture. Built with components like DataStore, Coroutines, ViewModel, LiveData, Room, Navigation-Compose, Coil, koin etc.
Stars: ✭ 122 (+159.57%)
Mutual labels:  localstorage
archer-svgs
异步加载svg解决方案
Stars: ✭ 23 (-51.06%)
Mutual labels:  localstorage

localstorage-slim.js

npm version Build Status code style Downloads maintained License


An ultra slim localstorage wrapper with optional support for ttl and encryption

localstorage-slim.js

  • is an pure JS localstorage wrapper with ZERO DEPENDENCIES!
  • is a very light-weight library
  • supports TTL (i.e. expiry of data in LocalStorage)
  • supports encryption/decryption
  • checks LocalStorage browser support internally
  • Allows you to store data in multiple formats (numbers, strings, objects, arrays, ...) with checks for cyclic references

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,

// using ES6 modules
import ls from 'localstorage-slim';

// using CommonJS modules
var ls = require('localstorage-slim');

In the browser context,

<!-- Include the library -->
<script src="./node_modules/localstorage-slim/dist/localstorage-slim.js"></script>

<!-- Alternatively, you can use a CDN with jsdelivr -->
<script src="https://cdn.jsdelivr.net/npm/localstorage-slim"></script>
<!-- or with unpkg.com -->
<script src="https://unpkg.com/[email protected]/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

/*** Store in localstorage ***/
const value = {
  a: new Date(),
  b: null,
  c: false,
  d: 'superman',
  e: 1234
}
ls.set('key1', value); // value can be anything (object, array, string, numbers,...)
ls.set('key2', value, { ttl: 5 }); // with optional ttl in seconds
ls.set('key3', value, { encrypt: true }); // with optional encryption

/*** Retrieve from localstorage ***/
const result1 = ls.get('key1');  // { a: "currentdate", b: "null", c: false, d: 'superman', e: 1234 }

// within 5 seconds
const result2 = ls.get('key2');  // { a: "currentdate", b: "null", c: false, d: 'superman', e: 1234 }
// after 5 seconds
const result2 = ls.get('key2');  // null

const result3 = ls.get('key3', { decrypt: true }); // { a: "currentdate", b: "null", c: false, d: 'superman', e: 1234 }

Configuration

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 An encryption function whose signature can be seen on the left. 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 whose signature can be seen on the left. 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.

Encryption/Decryption

LocalStorage-slim allows you to encrypt the data that will be stored in your localStorage.

// enable encryption globally
ls.config.encrypt = true;

// optionally use a different secret key
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 -

// enable encryption
ls.config.encrypt = true;
// set a global secret
ls.config.secret = 'secret-password';

// override encrypter function
ls.config.encrypter = (data: unknown, secret: string): string => 'encrypted string';
// override decrypter function
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.

// Then, use ls as you normally would
ls.set(...); // internally calls ls.config.encrypter(...);
ls.get(...); // internally calls ls.config.decrypter(...);

// you can encrypt a particular LS item by providing a different secret as well.
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).


API

The Api is very similar to that of the native LocalStorage API.


1. ls.set(key, value, config = {})

Sets an item in the LocalStorage. It can accept 3 arguments

  1. key: string [Required] - The key with which the value should be associated
  2. value: string|Date|Number|Object|Boolean|Null [Required] - The value to be stored
  3. config: Config [Optional] - This argument accepts the same properties 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); // returns undefined if successful or false if there was a problem

// with ttl
ls.config.ttl = 3;      // global ttl set to 3 seconds
ls.set('key', 'value'); // value expires after 3s
ls.set('key', 'value', { ttl: 5 }); // value expires after 5s (overrides global ttl)

// with encryption (to encrypt particular fields)
ls.set('key', 'value', { encrypt: true });

2. ls.get(key, config = {})

Retrieves the Data associated with the key stored in the LocalStorage. It accepts 2 arguments -

  1. key: string [Required] - The key with which the value is associated
  2. config: Config [Optional] - This argument accepts the same properties 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); // value retrieved from LS

// if ttl was set
ls.get('key'); // returns the value if ttl has not expired, else returns null

// when a particular field is encrypted, and it needs decryption
ls.get('key', { decrypt: true });

// get decrypted value when global encryption is enabled
ls.config.encrypt = true;
ls.get('key'); // returns decrypted value

3. ls.flush(force = false)

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. It 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().

// removes all expired data (i.e. ttl has expired)
ls.flush();
// removes all data that has a ttl (i.e. even if the ttl has not expired yet)
ls.flush(true);

4. ls.remove(key)

Accepts the key: string as an argument to remove the data associated with it.

// delete data from the LS
ls.remove('key'); // returns undefined if successful, false otherwise

5.ls.clear()

Clears the entire localstorage linked to the current domain.

// removes all data from the LS
ls.clear(); // returns undefined if successful, false otherwise

Screenshot


Contribute

Interested in contributing features and fixes?

Read more on contributing.

Changelog

See the Changelog

License

MIT © Digital Fortress

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].