The HTML5 Local Storage API (part of Web Storage) has excellent browser support and is being used in more and more applications. It has a simple API and certainly has its drawbacks, similar to cookies.
Over the past year or so I’ve come across quite a few tools and libraries that use the localStorage API so I’ve compiled many of them together into this post with some code examples and discussion of the features.
Key Takeaways
- The HTML5 Local Storage API is widely supported and increasingly used in applications, but it has limitations similar to cookies. Various JavaScript libraries have been developed to improve and extend its functionality.
- Libraries such as Lockr, store.js, and lscache provide wrappers for the localStorage API, offering additional methods and features. These include storing different data types without manual conversion, deeper browser support, and emulation of Memcached, a memory object caching system.
- Some libraries like secStore.js and localForage offer more specialized functionalities. secStore.js adds a layer of security through the Stanford Javascript Crypto Library, while localForage, built by Mozilla, provides an asynchronous storage API using IndexedDB or WebSQL.
- Other libraries like Basil.js and lz-string offer unique features. Basil.js is a unified localStorage, sessionStorage, and cookie API that allows defining namespaces, storage method priority, and default storage. lz-string allows storing large amounts of data in localStorage by using compression.
Lockr
Lockr is a wrapper for the localStorage API and lets you use a number of useful methods and features. For example, while localStorage is limited to storing only strings, Lockr lets you store different data types without the need to do the conversion yourself:
Lockr.set('website', 'SitePoint'); // string
Lockr.set('categories', 8); // number
Lockr.set('users', [{ name: 'John Doe', age: 18 }, { name: 'Jane Doe', age: 19 }]);
// object
Other features include:
- Retrieve all key/value pairs with the
Lockr.get()
method - Compile all key/value pairs into an array with
Lockr.getAll()
- Delete all stored key/value pairs with
Lockr.flush()
- Add/remove values under a hash key using
Lockr.sadd
andLockr.srem
The Local Storage Bridge
A 1KB library to facilitate exchanging messages between tabs in the same browser, using localStorage as the communication channel. After including the library, here’s some sample code you might use:
// send a message
lsbridge.send('my-namespace', {
message: 'Hello world!'
});
// listen for messages
lsbridge.subscribe('my-namespace', function(data) {
console.log(data); // prints: 'Hello world!'
});
As shown, the send()
method creates and sends the message and the subscribe()
method lets you listen for the specified message. You can read more about the library in this blog post.
Barn
This library provides a Redis-like API with a “fast, atomic persistent storage layer” on top of localStorage. Below is an example code snippet taken from the repo’s README. It demonstrates many of the methods available.
var barn = new Barn(localStorage);
barn.set('key', 'val');
console.log(barn.get('key')); // val
barn.lpush('list', 'val1');
barn.lpush('list', 'val2');
console.log(barn.rpop('list')); // val1
console.log(barn.rpop('list')); // val2
barn.sadd('set', 'val1');
barn.sadd('set', 'val2');
barn.sadd('set', 'val3');
console.log(barn.smembers('set')); // ['val1', 'val2', 'val3']
barn.srem('set', 'val3');
console.log(barn.smembers('set')); // ['val1', 'val2']
Other features of the API include the ability to get ranges with start/end values, getting an array of items, and condensing the entire store of data to save space. The repo has a full reference of all the methods and what they do.
store.js
This is another wrapper, similar to Lockr, but this time provides deeper browser support via fallbacks. The README explains that “store.js uses localStorage when available, and falls back on the userData behavior in IE6 and IE7. No flash to slow down your page load. No cookies to fatten your network requests.”
The basic API is explained in comments in the following code:
// Store 'SitePoint' in 'website'
store.set('website', 'SitePoint');
// Get 'website'
store.get('website');
// Remove 'website'
store.remove('website');
// Clear all keys
store.clear();
In addition, there are some more advanced features:
// Store an object literal; uses JSON.stringify under the hood
store.set('website', {
name: 'SitePoint',
loves: 'CSS'
});
// Get the stored object; uses JSON.parse under the hood
var website = store.get('website');
console.log(website.name + ' loves ' + website.loves);
// Get all stored values
console.log(store.getAll());
// Loop over all stored values
store.forEach(function(key, val) {
console.log(key, val);
});
The README on the GitHub repo has lots of details on depth of browser support and potential bugs and pitfalls to consider (e.g. the fact that some browsers don’t allow local storage in private mode).
lscache
lscache is another localStorage wrapper but with a few extra features. You can use it as a simple localStorage API or you can use the features that emulate Memcached, a memory object caching system.
lscache exposes the following methods, described in the comments in the code:
// set a greeting with a 2 minute expiration
lscache.set('greeting', 'Hello World!', 2);
// get and display the greeting
console.log(lscache.get('greeting'));
// remove the greeting
lscache.remove('greeting');
// flush the entire cache of items
lscache.flush();
// flush only expired items
lscache.flushExpired();
Like the previous library, this one also takes care of serialization, so you can store and retrieve objects:
lscache.set('website', {
'name': 'SitePoint',
'category': 'CSS'
}, 4);
// retrieve data from the object
console.log(lscache.get('website').name);
console.log(lscache.get('website').category);
And finally, lscache lets you partition data into “buckets”. Take a look at this code:
lscache.set('website', 'SitePoint', 2);
console.log(lscache.get('website')); // 'SitePoint'
lscache.setBucket('other');
console.log(lscache.get('website')); // null
lscache.resetBucket();
console.log(lscache.get('website')); // 'SitePoint'
Notice how in the 2nd log, the result is null
. This is because I’ve set a custom bucket before logging the result. Once I’ve set a bucket, anything added to lscache before that point will not be accessible, even if I try to flush it. Only the items in the ‘other’ bucket are accessible or flushable. Then when I reset the bucket, I’m able to access my original data again.
secStore.js
secStore.js is a data storage API that adds an optional layer of security by means of the Stanford Javascript Crypto Library. secStore.js lets you choose your storage method: localStorage, sessionStorage, or cookies. To use secStore.js, you have to also include the aforementioned sjcl.js library.
Here is an example demonstrating how to save some data with the encrypt
option set to ‘true’:
var storage = new secStore;
var options = {
encrypt: true,
data: {
key: 'data goes here'
}
};
storage.set(options, function(err, results) {
if (err) throw err;
console.log(results);
});
Notice the set()
method being used, which passes in the options you specify (including the custom data) along with a callback function that lets you test the results. We can then use the get()
method to retrieve that data:
storage.get(options, function(err, results) {
if (err) throw err;
console.log(results.key); // Logs: "data goes here"
});
If you want to use session storage or cookies instead of local storage with secStore.js, you can define that in the options:
var options = {
encrypt: true,
storage: 'session', // or 'cookies'
data: {
key: 'data here'
}
};
localForage
This library, built by Mozilla, gives you a simple localStorage-like API, but uses asynchronous storage via IndexedDB or WebSQL. The API is exactly the same as localStorage (getItem()
, setItem()
, etc), except its API is asynchronous and the syntax requires callbacks to be used.
So for example, whether you set or get a value, you won’t get a return value but you can deal with the data that’s passed to the callback function, and (optionally) deal with errors:
localforage.setItem('key', 'value', function(err, value) {
console.log(value);
});
localforage.getItem('key', function(err, value) {
if (err) {
console.error('error message...');
} else {
console.log(value);
}
});
Some other points on localForage:
- Supports use of JavaScript promises
- Like other libraries, not limited just to storing strings but you can set and get objects
- Lets you set database information using a
config()
method
Basil.js
Basil.js is described as a unified localStorage, sessionStorage, and cookie API and it includes some unique and very easy to use features. The basic methods can be used as shown here:
basil = new Basil(options);
basil.set('foo', 'bar');
basil.get('foo');
basil.remove('foo');
basil.reset();
You can also use Basil.js to test if localStorage if available:
basil.check('local'); // returns Boolean value
Basil.js also lets you use cookies or sessionStorage:
basil.cookie.set(key, value, {
'expireDays': days, 'domain': 'mydomain.com'
});
basil.cookie.get(key);
basil.sessionStorage.set(key, value);
basil.sessionStorage.get(key);
Finally, in an options
object, you can define the following with an options
object:
- Namespaces for different parts of your data
- Priority order for which storage method to use
- The default storage method
- An expire date for cookies.
options = {
namespace: 'foo',
storages: ['cookie', 'local'],
storage: 'cookie',
expireDays: 31
};
lz-string
The lz-string utility lets you store large amounts of data in localStorage by using compression and it’s pretty straightforward to use. After including the library on your page, you can do the following:
var string = 'A string to test our compression.';
console.log(string.length); // 33
var compressed = LZString.compress(string);
console.log(compressed.length); // 18
string = LZString.decompress(compressed);
Notice the use of the compress()
and decompress()
methods. The comments in the above code show the length values before and after compression. You can see how beneficial this would be seeing how client side storage always has limited space.
As explained in the library’s docs, there are options to compress data to Uint8Array (a new-ish data type in JavaScript) and even the ability to compress the data for storage outside of the client.
Honorable Mentions
The above tools will probably help you do just about anything you want in localStorage, but if you’re looking for more, here are a few more related tools and libraries you might want to check out.
- LokiJS – A fast, in-memory document-oriented datastore for node.js, browser, and Cordova.
- Client Storage for AngularJS – Namespaced client storage for Angular JS. Writes to localStorage, with cookie fallback. No external dependencies other than Angular core; does not depend on ngCookies.
- AlaSQL.js – JavaScript SQL database for browser and Node.js. Handles both traditional relational tables and nested JSON data (NoSQL). Export, store, and import data from localStorage, IndexedDB, or Excel.
- angular-locker – A simple and configurable abstraction for local/session storage in angular projects, providing a fluent api that is powerful and easy to use.
- jsCache – Enables caching of JavaScript files, CSS stylesheets, and images using localStorage.
- LargeLocalStorage – Overcomes various browser deficiencies to offer a large key-value store on the client.
Know any others?
If you’ve built something on top of the localStorage API or a related tool that enhances client-side storage, feel free to let us know about it in the comments.
Frequently Asked Questions (FAQs) about JavaScript Libraries for Local Storage
What are the benefits of using JavaScript libraries for local storage?
JavaScript libraries for local storage offer several benefits. They provide a more efficient way to store data on the client-side, which can significantly improve the performance of your web applications. These libraries also offer a higher level of security compared to traditional methods of data storage, as they allow for data encryption. Additionally, they provide a more user-friendly interface for managing data, making it easier for developers to work with local storage.
How does local storage work in JavaScript?
Local storage in JavaScript allows web applications to store data persistently in a web browser. Unlike cookies, local storage does not expire and is not sent back to the server, making it a more efficient method of data storage. Data stored in local storage is saved across browser sessions, meaning it is still available even if the browser is closed and reopened.
Can I use local storage for sensitive data?
While local storage provides a convenient way to store data on the client-side, it is not recommended for storing sensitive data. This is because local storage is not designed to be a secure storage mechanism. Data stored in local storage can be easily accessed and manipulated using simple JavaScript code. Therefore, sensitive data such as passwords, credit card numbers, or personal user information should not be stored in local storage.
How can I manage data in local storage?
Managing data in local storage involves three main operations: setting items, getting items, and removing items. To set an item, you can use the setItem()
method, which takes two arguments: the key and the value. To retrieve an item, you can use the getItem()
method, which takes the key as an argument and returns the corresponding value. To remove an item, you can use the removeItem()
method, which takes the key as an argument.
What are some popular JavaScript libraries for local storage?
There are several popular JavaScript libraries for local storage, including store.js, localForage, and js-cookie. Store.js provides a simple and consistent API for local storage, and works across all major browsers. LocalForage offers a powerful API for asynchronous storage, and supports IndexedDB, WebSQL, and localStorage. Js-cookie is a lightweight library for handling cookies, and can be used as a fallback when local storage is not available.
How can I check if local storage is available?
You can check if local storage is available by using a simple try/catch block in JavaScript. The window.localStorage
property can be used to access the local storage object. If this property exists and can be used to set and retrieve items, then local storage is available.
What is the storage limit for local storage?
The storage limit for local storage varies between different browsers, but it is typically around 5MB. This is significantly larger than the storage limit for cookies, which is only 4KB. However, it is still a good idea to be mindful of the amount of data you are storing in local storage, as excessive data can slow down your web application.
Can local storage be shared between different browsers?
No, local storage cannot be shared between different browsers. Each web browser has its own separate local storage, so data stored in one browser will not be available in another. This is important to keep in mind when designing web applications that rely on local storage.
How can I clear all data from local storage?
You can clear all data from local storage by using the clear()
method. This method does not take any arguments, and will remove all items from local storage. Be careful when using this method, as it will permanently delete all data in local storage.
Can local storage be used on mobile devices?
Yes, local storage can be used on mobile devices. Most modern mobile web browsers support local storage, so you can use it to store data on both desktop and mobile devices. However, the storage limit may be lower on mobile devices, so it is important to take this into consideration when designing your web application.
Louis is a front-end developer, writer, and author who has been involved in the web dev industry since 2000. He blogs at Impressive Webs and curates Web Tools Weekly, a newsletter for front-end developers with a focus on tools.