Papa's Perspective
A Unified Approach to Client-Side Storage
This simple API can give you a leg up on local storage in your Web apps.
Web apps, generally, have sets of data that either don't change a whole lot, or that represent state -- the configuration, content and attributes -- which must be maintained between page calls. HTTP offers a variety of great features, but state has to be reset between page calls because it's stateless. So where do you store that data in Web applications? The concept of local storage addresses this challenge quite nicely.
Why Use Storage?
Local storage in HTML5 refers specifically to the localStorage object. I recommend using it if you're building an app for an HTML5-compliant browser that implements localStorage. (You can check the popular site, caniuse.com, to see if your browsers support localStorage and other features.) Historically, browsers have used a variety of techniques to store local data, including localStorage, sessionStorage (which differs from localStorage in that its data goes away when the browser closes), globalStorage, cookies and userData.
You can use cookies, but there are some limitations, which Christian Heilmann explains in his article, "Local Storage and How to Use It on Web Sites". It's worth noting that while you can store a lot of data in local storage, you should use this feature judiciously -- it's not a database, after all. Local storage is ideal for retaining data that either doesn't change often (you can set expiration dates), or to help maintain state across pages, tabs and browser sessions.
Say you're building a Web app that supports multiple versions of different browsers. You want to use localStorage where available, but also fall back and provide graceful degradation in older browsers. What do you do? Certainly not a lot of conditional logic -- bleh!
Unified API with Amplify.store
This is the sweet spot for AmplifyJS, a library of jQuery components built by the folks at appendTo LLC. It includes three main features: AJAX requests, pub/sub messaging and storage. The amplify.store object provides a unified way to persist data from a variety of Web browsers. It offers a single API across multiple browsers, which implement storage quite differently. The amplify.store library hides the complexity and logic, so you can focus on storing and retrieving data -- and not on how to handle it in different browsers. You can find a complete list of the amplify.store default storage mechanisms based on browser support here.
Note: If your browser doesn't support JSON2, you must include JSON2.js as well. This is required in Internet Explorer 7 and earlier versions to use the JSON.stringify and JSON.parse methods.
Local storage stores a key value pair, where the key and the value are both strings. What this means is that if you want to store arrays and objects, you should serialize them first, using JSON.stringify (and de-serialize them with JSON.parse). However, if you use amplify.store, it will serialize and de-serialize the data to and from JSON for you.
The following sample code defines an array of people objects:
var testKey = 'people';
var testVal = [
{ name: 'John', age: 34, pets: [{name: 'Fido', type: 'dog'},
{name: 'Tink', type: 'cat'}]},
{ name: 'Landon', age: 14, pets: [{name: 'Iron Man', type: 'dog'},
{name: 'McQueen', type: 'dog'}]}];
You can store these objects using amplify.store by passing a key value, followed by the textVal object. Amplify.store will serialize the data in testVal, do a check for localStorage support (and fallback, if necessary), then store the data.The data can be retrieved using the same store method, by only passing a key value. You can also clear the storage by passing a null in for the value.
Examining Local Storage
You can examine what's currently in local storage by calling amplify.store and passing no parameters. If you want to know which key values are being stored, you could also run a script. You can clear a data value from local storage immediately by calling amplify.store(key, null) or setting an expiration on the data when you store it. Simply pass an optional parameter to the store method following the data value. The parameter is an object containing an expiration value in milliseconds.
The simplicity of the API, its support for the localStorage object and its graceful degradation make this one of my favorite APIs for this space. All of the sample code can be found in this fiddle, which uses toastr to display the values and log the storage and retrieval.
About the Author
John Papa is a Microsoft Regional Director and former Microsoft technical evangelist. Author of 100-plus articles and 10 books, he specializes in professional application development with Windows, HTML5, JavaScript, CSS, Silverlight, Windows Presentation Foundation, C#, .NET and SQL Server. Check out his online training with Pluralsight; find him at johnpapa.net and on Twitter at twitter.com/john_papa.