Storing data with localStorage and Lockr

localStorage is one of the options an application has if it needs to store data on the client side. It is a key/value store and provides a very simple api. All modern browsers support it (IE since version 8).

setItem stores a value with a certain key. First argument is the name of the key and the second argument is the value. A key can only exists once. Calling setItem multiple times with the same key overwrites the previous entry. Key and value must be a string and setItem will automatically convert a non-string value to a string. This is a problem for objects because they get converted to the string "[object Object]". To solve that an application has to convert objects to a string before it calls setItem. One way to do it is with the JSON.stringify function.

When the key is not a valid name for a property the application needs to use the ['property'] syntax (or setItem and getItem).

localStorage['11']='eleven';const e = localStorage['11'];// "eleven"

removeItem removes the entry for a specific key.

localStorage.removeItem('one');

clear removes all key/value pairs.

localStorage.clear();

Another related storage option is sessionStorage. It provides exactly the same functions as localStorage. The big difference is that data stored in localStorage survives a browser restart, data in sessionStorage does not. But even the data survives a browser restart, an application should not depend on the prospect that the data is stored and available forever. The data in a localStorage can be erased at anytime either by the user or browser. iOS for example removes data from the localStorage when it runs low on storage.

In the examples above we saw that keys and values need to be strings. When the application stores a number localStorage automatically converts it to a string and getItem returns a string. An application can solve that by converting the value with JSON.stringify and JSON.parse.

Lockr is a thin wrapper around localStorage. This library does the conversion to JSON behind the scenes and makes your application's code more concise. This example stores a number and a boolean and returns the values with the same type.

Lockr has a size of 3000 bytes (version 0.8.4) in minified form and can be installed with bower, npm or with a simple script tag in the html page. In a npm project you can install it with the following command

npm install lockr

And if you work with TypeScript you can install the TypeScript definition file like this: