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
Section titled “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?
Section titled “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
’ssessionStorage
object is different fromhttps://example.com
’ssessionStorage
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?
Section titled “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:
- When the content gets cleared through JavaScript
- When the browser’s cache gets cleared
Note the following:
- The
Window.localStorage
object’s storage limit is larger than theWindow.sessionStorage
. - The data stored inside the local storage is per-origin. In other words,
http://example.com
’slocalStorage
object is different fromhttps://example.com
’slocalStorage
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, thelocalStorage
object may behave differently among different browsers.
How to Access the Web Storage
Section titled “How to Access the Web Storage”You can access the two web storage objects by:
- Using the same technique for accessing regular JavaScript objects
- 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?
Section titled “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:
Web Storage vs. Cookies: What’s the Difference?
Section titled “Web Storage vs. Cookies: What’s the Difference?”Below are the differences between web storage and cookie.
Storage limit
Section titled “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
Section titled “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
Section titled “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
Section titled “Property”Web storage: Web storage is a property of the Window
object.
Cookie: Cookie is a property of the Document
object.
Expiration
Section titled “Expiration”Web storage: Browsers determine web storage’s expiration date.
Cookie: You can specify a cookie’s expiration date.
Retrieving individual data
Section titled “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
Section titled “The syntax for storing data”Web storage:
webStorageObject.setItem(key, value);
Cookie:
document.cookie = "key=value";
The syntax for reading data
Section titled “The syntax for reading data”Web storage:
webStorageObject.getItem(key);
Cookie:
document.cookie;
The syntax for removing data
Section titled “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 🤸♂️🏋️♀️
Section titled “Time to Practice with Web Storage 🤸♂️🏋️♀️”Consider the following To-Do List app:
The Problem
Section titled “The Problem”The issue with the To-Do List app is this:
- Tasks disappear whenever users refresh the webpage.
Your Exercise
Section titled “Your Exercise”Use the appropriate Web Storage APIs to accomplish the following tasks:
- Prevent the Session pane’s To-Do items from disappearing whenever users reload the browser.
- Prevent the Local section’s To-Do items from disappearing whenever users reload or close their browser tab (or window).
- Auto-display the Session section’s previously added tasks on page reload.
- Auto-display the Local section’s previously added tasks on page reload (or browser reopen).
Bonus Exercise
Section titled “Bonus Exercise”Use your browser’s console to:
- Check the number of items in your session storage.
- Display the name of your local storage’s zeroth index item.
- Delete all the items in your session storage.
How Did You Go About Solving the Web Storage Exercise?
Section titled “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
Section titled “How to prevent the Session Storage pane’s To-Do items from disappearing on page reload”Whenever users click the “Add task” button,
- Get existing session storage’s content, if any. Otherwise, return an empty array.
- Merge the existing to-do items with the user’s new input.
- 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 = "";});
How to prevent the Local Storage pane’s To-Do items from disappearing on page reload or reopen
Section titled “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,
- Get existing local storage’s content, if any. Otherwise, return an empty array.
- Merge the existing to-do items with the user’s new input.
- 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 = "";});
How to auto-display the Session section’s previously added tasks on page reload
Section titled “How to auto-display the Session section’s previously added tasks on page reload”Whenever users reload the page,
- Get existing session storage’s content, if any. Otherwise, return an empty array.
- Use the retrieved content to create
<li>
elements. - 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);});
How to auto-display the Local section’s previously added tasks on page reload or reopen
Section titled “How to auto-display the Local section’s previously added tasks on page reload or reopen”Whenever users reload or reopen the page,
- Get existing local storage’s content, if any. Otherwise, return an empty array.
- Use the retrieved content to create
<li>
elements. - 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);});
How to check the total items in the browser’s session storage
Section titled “How to check the total items in the browser’s session storage”Use session storage’s length
property like so:
console.log(sessionStorage.length);
How to display the local storage’s zeroth index item’s name
Section titled “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));
How to empty the browser’s session storage
Section titled “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 🧗♀️🚀
Section titled “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: