A guide to using localStorage and sessionStorage

Last updated: January 20, 2023.

Using the HTML Web Storage API, you can save data values in string format in a user’s browser. Saved values can then be retrived again on another page (the saved values survive a page refresh!) or even another website session.

The two methods available for accessing this API using JavaScript are window.localStorage() and window.sessionStorage().

The only difference between these two is that data saved using localStorage persists in a user’s browser until it is manually cleared. Whereas the contents of sessionStorage is cleared every time a user ends the current website session (i.e. tab-level persistence).

Both localStorage and sessionStorage save to the same web storage space but are stored separately. Thus, a value saved using localStorage cannot be accessed later using sessionStorage or vice versa.

The Web Storage API is now supported by all major browsers. The combined storage space limit is 5MB per domain.

This tutorial shows you how to access and work with the Web Storage API using JavaScript.

Table of contents

Saving data to web storage

Data can be saved in a user’s browser by calling the setItem() method.

It requires two arguments: a key in string format and a value in string format. If the value is not in string format, it will be coerced to string format if possible. It is therefore good practice to make sure the value is in string format before saving it to storage to avoid any unwanted surprises!

localStorage.setItem('first-item', "1");
// Saves to localStorage space of web storage

The syntax for saving to sessionStorage is the same:

sessionStorage.setItem('first-item', "1");
// Saves to sessionStorage part of web storage

Retrieving data from web storage

To retrieve a value from web storage, you can use the getItem() method.

If you saved to web storage using localStorage, you can retrieve the item a user saved using the following code, even after a user has closed all tabs and returned to the same domain:

const value = localStorage.getItem('first-item');
console.log(value); // "1"

If you used sessionStorage, values are retrievable on other pages during the same session (survive a page refresh) but are not available for return sessions:

// During same session as item saved:
const value = sessionStorage.getItem('first-item');
console.log(value); // "1"

// After returning to same domain:
const value = sessionStorage.getItem('first-item');
console.log(value); // null
Overwriting Behavior

If you save data using an already existing key, the old entry will be silently overwritten by the new one! You may therefore want to check if an item exists before writing a new one (see below).

Deleting items and clearing storage

To delete an item from local storage, use the removeItem() method via localStorage and sessionStorage.

localStorage.setItem('test-item', "This localStorage thing is quite useful");
localStorage.getItem('test-item'); // "This localStorage thing is quite useful"
localStorage.removeItem('test-item');
localStorage.getItem('test-item'); // null


sessionStorage.setItem('test-item', "The sessionStorage object too!");
sessionStorage.getItem('test-item'); // "The sessionStorage object too!"
sessionStorage.removeItem('test-item');
sessionStorage.getItem('test-item'); // null

Clearing all items

To clear all items stored via localStorage or sessionStorage, use the clear() method.

localStorage.clear();
console.log(localStorage); // {length: 0}

sessionStorage.clear();
console.log(sessionStorage); // {length: 0}

Saving and retrieving objects and arrays

Only string data can be stored in local storage.

But other stringifiable data can also be stored and retrieved by converting it to a string upon saving:

const obj = { name: "Brian", lastName: "Adams" };
const objAsString = JSON.stringify(obj);
localStorage.setItem('my-object', objAsString);

And then converting it back to a data object when retrieving it:

const obj = { name: "Brian", lastName: "Adams" };
const myObjAsString = localStorage.getItem('my-object');
const myObj = JSON.parse(myObjAsString);
console.log(myObj); // { name: "Brian", lastName: "Adams" }

This works for both objects and arrays.

Checking local storage

If item exists

To check if an item already exists in localStorage, you can use a conditional if...else statement, checking if an attempt to retrieve the item returns a truthy value.

localStorage.setItem('test', "x");

function doesItemExist(key) {
  if (localStorage.getItem(key)) {
    return true
  } else {
    return false
  }
}

doesItemExist('test'); // true
doesItemExist('test2'); // false

If local storage is available

In some rare cases, local storage may be inaccessible because it is full or a user's browser settings disallow its use.

You can check if local storage is accessible by attempting to store something there inside a try...catch statement.

function isStorageAvailable() {
  try {
    localStorage.setItem('test-item', "x");
    localStorage.removeItem('test');
    return true;
  } catch(e) {
    console.log("Storage unavailable", e);
    return false;
  }
}

isStorageAvailable(); // true or false

Related links