localStorage is a key/value storage option available for client-side data persistence in web applications. It provides a straightforward API and is supported by all modern browsers (IE since version 8).
localStorage ¶
setItem
stores a value with a certain key. The first argument is the name of the key, and the second argument is the value. Each key can only exist once. Calling setItem
multiple times with the same key overwrites the previous entry. Key and value must be a string; setItem
automatically converts 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.
localStorage.setItem('one', '1');
localStorage.setItem('two', 2); // automatically converts 2 to the string "2"
const myObj = {firstName: 'John', lastName: 'Doe', age: 36};
localStorage.setItem('123', JSON.stringify(myObj));
getItem
retrieves the value for a specific key. The function returns null when the key does not exist.
const a = localStorage.getItem('one'); // "1"
const b = localStorage.getItem('two'); // "2"
const obj = JSON.parse(localStorage.getItem('123')); // {firstName: 'John', lastName: 'Doe', age: 36}
Another way to set and get values is by directly accessing the key like a property on the localStorage object.
localStorage.one = '1'; // same as localStorage.setItem('one', '1');
const c = localStorage.one; // same as const c = localStorage.getItem('one');
It's possible to mix both approaches.
localStorage.two = '2'
const t = localStorage.getItem('two'); // "2"
There is one subtle difference in the behavior when the key does not exist. getItem
returns null, and the property access returns undefined.
const x = localStorage.getItem('xyz'); // null
const y = localStorage.xyz; // undefined
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 the same functions as localStorage
. The key difference is that data stored in localStorage
persists across browser restarts, whereas data in sessionStorage
does not. However, even though data in localStorage
persists, an application should not rely on it being stored indefinitely. The data can be erased at any time by the user or the browser. For example, iOS may remove data from localStorage
when it runs low on storage.
Lockr ¶
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.set('four', 4);
Lockr.set('five', true);
const f = Lockr.get('four'); // 4
const v = Lockr.get('five'); // true
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 an 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:
npm install @types/lockr --save-dev
set
and get
support storing and retrieving objects.
Lockr.set('anObject', {firstName: 'John', lastName: 'Doe', age: 36});
const anObject = Lockr.get('anObject'); // {age:36, firstName:"John", lastName:"Doe"}
The get
function supports an optional second argument that specifies a default value that is returned when the key does not exist.
const s = Lockr.get('six', 0); // 0
The rm
function removes a key/value entry.
Lockr.rm('four');
Lockr.flush()
removes everything in the localStorage
. It also deletes key/value entries that are stored directly with the localStorage
object.
Lockr does not only wrap existing localStorage
functions; it also adds some useful functionality on top of localStorage
.
getAll()
returns an array with all the stored values.
Lockr.set('1', 'one');
Lockr.set('2', 2);
Lockr.set('3', {name:'John', age: 36});
const values = Lockr.getAll(); // ["one", 2, {age:36,name:"John"}]
The following functions are inspired by Redis and allow an application to manage a set-like structure with a specific key.
sadd
adds a value to a set. If the application tries to add the same value multiple times, sadd
ignores the call.
Lockr.sadd('bond', 'Daniel'); // ["Daniel"]
Lockr.sadd('bond', 'Sean'); // ["Daniel", "Sean"]
Lockr.sadd('bond', 'Daniel'); // ["Daniel", "Sean"]
smembers
returns the values of a set as an array.
Lockr.sadd('bond', 'Pierce');
Lockr.sadd('bond', 'Roger');
Lockr.smembers('bond'); // ["Pierce", "Roger"]
sismember
returns true when the value exists in the set; otherwise, it returns false.
Lockr.sadd('bond', 'Daniel');
Lockr.sadd('bond', 'Roger');
Lockr.sismember('bond', 'Daniel'); // true
Lockr.sismember('bond', 'Jack'); // false
srem
removes a value from a set.
Lockr.sadd('bond', 'Pierce');
Lockr.sadd('bond', 'Jack');
Lockr.srem('bond', 'Jack');
Lockr.smembers('bond'); // ["Pierce"]