full-stack overflow

02 Jan 2018

WebStorage API: localStorage and sessionStorage

The Web Storage API allows you to store data for a given origin (page on your site) that can persist across sessions. Data is stored as key-value pairs. There can only be one value for a given key, although that value can be a JSON.stringify()d object. Web Storage is well-supported across browsers with few limitations, aside from browser-specific limits on storage space.

two types: long (session) and longer (local)

There are two types of storage that differ only in the amount of time their data is persisted.

sessionStorage maintains data so long as the browser program is open. It doesn’t matter if the tab or window is closed. As long as the browser instance exists, sessionStorage persists. When the instance dies, so does the stored data.

localStorage persists data even when the browser instance itself is closed and reopened.

storage methods

These methods are the same for sessionStorage and localStorage.

.getItem(key) returns the value associated with the given key, or null if the key does not exist

.setItem(key, value) sets the item with the given key to the specified value. Overwrites existing values.

.removeItem(key) removes the given item from storage.

.key(i) returns the ith key of localStorage, or null if the key does not exist. We can easily find all the keys in localStorage like this:

function getLocalStorageKeys() {
  let i = 0;
  let keys = [];
  while (localStorage.key(i) !== null) {
  return keys;

storing and retrieving objects

When you store keys and values in the Storage API, they will be coerced to strings. If you have an object in valid JSON format, you have to call JSON.stringify() on the data that you want to store, and then use setItem on this stringified object.

When you retrieve the item with getItem, you can turn the result back into an object for your program with JSON.parse().


const allMyCats = {
  fluffy: {
    age: 4,
    nickname: "billy",
  costello: {
    age: 6,
    nickname: "grunt",
localStorage.setItem("cool-cats", JSON.stringify(allMyCats));

localStorage.getItem('cool-cats') will yield this string:


which can be parsed to give us our original allMyCats.

localStorage.removeItem('cool-cats') returns undefined and removes ‘cool-cats’.


Web Storage should be treated as user input since it is directly modifiable by the user. If you use localStorage to persist some data for a user that you save to a database or elsewhere, be sure to validate and sanitize it. Also, do not store any sensitive data like passwords in localStorage.

A fun project

Try writing code that remembers the window size that a user set last time they visited the site, and resize the window onLoad when the user returns. Would you use sessionStorage or localStorage? Are there ways to make such a feature more usable and less obtrusive?