Skip to content

Web Storage in JS – How to Use localStorage and sessionStorage

Web storage is the JavaScript API browsers provide for storing data locally and securely within a user’s browser.

Types of Web Storage

The two main types of web storage are:

  • Session storage (Window.sessionStorage)
  • Local storage (Window.localStorage)

What Is the Window.sessionStorage Object?

The Window.sessionStorage web storage object stores data that persists for only one session of an opened tab.

In other words, whatever gets stored in the Window.sessionStorage object will not disappear on a reload of the web page. Instead, the computer will delete the stored data only when users close the browser tab or window.

Note the following:

  • The Window.sessionStorage object’s storage limit is much larger than a cookie.
  • The data stored inside the session storage is per-origin and per-instance. In other words, http://example.com’s sessionStorage object is different from https://example.com’s sessionStorage object because the two origins use different schemes.
  • Per-instance means per-window or per-tab. In other words, the sessionStorage object’s lifespan expires once users close the instance (window or tab).
  • Browsers create a unique page session for each new tab or window. Therefore, users can run multiple instances of an app without any interference between each instance’s session storage. (Note: Cookies do not have good support for running multiple instances of the same app. Such an attempt can cause errors such as double entry of bookings.)

What Is the Window.localStorage Object?

The Window.localStorage web storage object stores data that persists even when users close their browser tab (or window).

In other words, whatever gets stored in the Window.localStorage object will not disappear during a reload or reopening of the web page or when users close their browsers. Those data have no expiration time. Browsers never clear them automatically.

The computer will delete the Window.localStorage object’s content in the following instances only:

  1. When the content gets cleared through JavaScript
  2. When the browser’s cache gets cleared

Note the following:

  • The Window.localStorage object’s storage limit is larger than the Window.sessionStorage.
  • The data stored inside the local storage is per-origin. In other words, http://example.com’s localStorage object is different from https://example.com’s localStorage object because the two origins use different schemes.
  • There are inconsistencies with how browsers handle the local storage of documents not served from a web server (that is, pages with a file: URL scheme). Therefore, the localStorage object may behave differently among different browsers.

How to Access the Web Storage

You can access the two web storage objects by:

  1. Using the same technique for accessing regular JavaScript objects
  2. Using the web storage’s built-in interfaces

For instance, the three statements below do the same thing (that is, they set bestColor’s value). But the third line is recommended because it uses web storage’s setItem() method.

sessionStorage.bestColor = "Green";
sessionStorage["bestColor"] = "Green";
sessionStorage.setItem("bestColor", "Green");

What Is a Web Storage’s Built-In Interface?

Web storage’s built-in interfaces are the recommended tools for reading and manipulating a web storage object.

The six main types of web storage built-in interfaces are:

CodeSweetly ads

Master NPM Package Creation

Elevate your skills, boost your projects, and stand out in the coding world.
Learn more

Web Storage vs. Cookies: What’s the Difference?

Below are the differences between web storage and cookie.

Storage limit

Cookie: Have 4 kilobytes maximum storage limit.

Web storage: Can store a lot more than 4 kilobytes of data. For instance, Safari 8 can store up to 5 MB, while Firefox 34 permits 10 MB.

Data transfer to the server

Cookie: Transfers data to the server each time browsers send HTTP requests to the web server.

Web storage: Never transfers data to the server.

Weak integrity and confidentiality

Cookie: Suffers from weak integrity and weak confidentiality issues.

Web storage: Do not suffer from weak integrity and confidentiality issues because it stores data per-origin.

Property

Web storage: Web storage is a property of the Window object.

Cookie: Cookie is a property of the Document object.

Expiration

Web storage: Browsers determine web storage’s expiration date.

Cookie: You can specify a cookie’s expiration date.

Retrieving individual data

Web storage: You can choose the specific data you wish to retrieve.

Cookie: There’s no way to retrieve individual data. You always have to recall all the data to read any single one.

The syntax for storing data

Web storage:

webStorageObject.setItem(key, value);

Cookie:

document.cookie = "key=value";

The syntax for reading data

Web storage:

webStorageObject.getItem(key);

Cookie:

document.cookie;

The syntax for removing data

Web storage:

webStorageObject.removeItem(key);

Cookie:

document.cookie = "key=; expires=Thu, 01 May 1930 00:00:00 UTC";

The snippet above used an empty value and a past expiration date to delete the cookie.

Now that we know what web storage is and how to access it, we can practice using it in a JavaScript project.

Time to Practice with Web Storage 🤸‍♂️🏋️‍♀️

Consider the following To-Do List app:

http://localhost:3000

The Problem

The issue with the To-Do List app is this:

  • Tasks disappear whenever users refresh the webpage.

Your Exercise

Use the appropriate Web Storage APIs to accomplish the following tasks:

  1. Prevent the Session pane’s To-Do items from disappearing whenever users reload the browser.
  2. Prevent the Local section’s To-Do items from disappearing whenever users reload or close their browser tab (or window).
  3. Auto-display the Session section’s previously added tasks on page reload.
  4. Auto-display the Local section’s previously added tasks on page reload (or browser reopen).

Bonus Exercise

Use your browser’s console to:

  1. Check the number of items in your session storage.
  2. Display the name of your local storage’s zeroth index item.
  3. Delete all the items in your session storage.

Try the Web Storage Exercise

How Did You Go About Solving the Web Storage Exercise?

Below are feasible ways to get the exercise done.

How to prevent the Session Storage pane’s To-Do items from disappearing on page reload

Whenever users click the “Add task” button,

  1. Get existing session storage’s content, if any. Otherwise, return an empty array.
  2. Merge the existing to-do items with the user’s new input.
  3. Add the new to-do list to the browser’s session storage object.

Here’s the code:

sessionAddTaskBtn.addEventListener("click", () => {
// Get existing session storage's content, if any. Otherwise, return an empty array:
const currentTodoArray =
JSON.parse(sessionStorage.getItem("codesweetlyStore")) || [];
// Merge currentTodoArray with the user's new input:
const newTodoArray = [
...currentTodoArray,
{ checked: false, text: sessionInputEle.value },
];
// Add newTodoArray to the session storage object:
sessionStorage.setItem("codesweetlyStore", JSON.stringify(newTodoArray));
const todoLiElements = createTodoLiElements(newTodoArray);
sessionTodosContainer.replaceChildren(...todoLiElements);
sessionInputEle.value = "";
});

Try Editing It

How to prevent the Local Storage pane’s To-Do items from disappearing on page reload or reopen

Whenever users click the “Add task” button,

  1. Get existing local storage’s content, if any. Otherwise, return an empty array.
  2. Merge the existing to-do items with the user’s new input.
  3. Add the new to-do list to the browser’s local storage object.

Here’s the code:

localAddTaskBtn.addEventListener("click", () => {
// Get existing local storage's content, if any. Otherwise, return an empty array:
const currentTodoArray =
JSON.parse(localStorage.getItem("codesweetlyStore")) || [];
// Merge currentTodoArray with the user's new input:
const newTodoArray = [
...currentTodoArray,
{ checked: false, text: localInputEle.value },
];
// Add newTodoArray to the local storage object:
sessionStorage.setItem("codesweetlyStore", JSON.stringify(newTodoArray));
const todoLiElements = createTodoLiElements(newTodoArray);
localTodosContainer.replaceChildren(...todoLiElements);
localInputEle.value = "";
});

Try Editing It

How to auto-display the Session section’s previously added tasks on page reload

Whenever users reload the page,

  1. Get existing session storage’s content, if any. Otherwise, return an empty array.
  2. Use the retrieved content to create <li> elements.
  3. Populate the tasks display space with the <li> elements.

Here’s the code:

window.addEventListener("load", () => {
// Get existing session storage's content, if any. Otherwise, return an empty array:
const sessionTodoArray =
JSON.parse(sessionStorage.getItem("codesweetlyStore")) || [];
// Use the retrieved sessionTodoArray to create <li> elements:
const todoLiElements = createTodoLiElements(sessionTodoArray);
// Populate the tasks display space with the todoLiElements:
sessionTodosContainer.replaceChildren(...todoLiElements);
});

Try Editing It

How to auto-display the Local section’s previously added tasks on page reload or reopen

Whenever users reload or reopen the page,

  1. Get existing local storage’s content, if any. Otherwise, return an empty array.
  2. Use the retrieved content to create <li> elements.
  3. Populate the tasks display space with the <li> elements.

Here’s the code:

window.addEventListener("load", () => {
// Get existing local storage's content, if any. Otherwise, return an empty array:
const localTodoArray =
JSON.parse(localStorage.getItem("codesweetlyStore")) || [];
// Use the retrieved localTodoArray to create <li> elements:
const todoLiElements = createTodoLiElements(localTodoArray);
// Populate the tasks display space with the todoLiElements:
localTodosContainer.replaceChildren(...todoLiElements);
});

Try Editing It

CodeSweetly ads

Express Your Love for Coding!

Explore CodeSweetly's Shop for an array of stylish products to enhance your coding experience.
Shop now

How to check the total items in the browser’s session storage

Use session storage’s length property like so:

console.log(sessionStorage.length);

Try Editing It

How to display the local storage’s zeroth index item’s name

Use the local storage’s key() method as follows:

console.log(localStorage.key(0));

Try Editing It

How to empty the browser’s session storage

Use the session storage’s clear() method as follows:

sessionStorage.clear();

How to Continue Practicing with Web Storage 🧗‍♀️🚀

The to-do app still has a lot of potential. For instance, you can:

  • Convert it to a React TypeScript application.
  • Make it keyboard accessible.
  • Allow users to delete or edit individual tasks.
  • Allow users to star (mark as important) specific tasks.
  • Let users specify due dates.

So, feel free to continue developing what we’ve built in this tutorial so you can better understand the web storage objects.

For instance, here’s my attempt at making the two panes functional:

http://localhost:3000