Web storage enables web applications to store data locally within the user's browser.
HTML web storage is superior to cookies in many ways.
Before HTML5, application data had to be stored in cookies, which were included in every server request. Web storage offers greater security, allowing large amounts of data to be stored locally without impacting website performance.
Unlike cookies, web storage has a much larger storage limit (at least 5MB) and does not transfer information to the server.
Web storage is specific to each origin (domain and protocol). This means that all pages from the same origin can store and access the same data.
HTML Web Storage Objects
HTML web storage offers two objects for storing data on the client side:
window.localStorage
- stores data without an expiration date.window.sessionStorage
- stores data for one session only; the data is lost when the browser tab is closed.
Before implementing web storage, it's important to verify browser support for localStorage and sessionStorage, as shown below:
if (typeof(Storage) !== "undefined") {
// Storage available.
} else {
// No storage available.
}
The localStorage Object
The localStorage object stores data without an expiration date. This data persists even when the browser is closed and remains available in the future, whether it's the next day, week, or year.
// Store
localStorage.setItem("fullname", "Sami Khan");
// Retrieve
document.getElementById("local-data").innerHTML = localStorage.getItem("fullname");
Example explained:
- Set a
localStorage
item with the name fullname and the value Sami Khan. - Retrieve the value of fullname and place it into the element with the ID local-data.
localStorage.removeItem("fullname");
Note: Name/value pairs are always stored as strings. Remember to convert them to a different format when necessary. For example, in case of a calculation, you may need to convert the string into a number using Number(string)
.
The sessionStorage Object
The sessionStorage
object is similar to the localStorage
object, but it only retains data for the duration of one session. The data is deleted when the user closes the specific browser tab.
The example below will save and retrieve the text Sami Khan only in the current session, that is, until the browser tab is closed.
// Store
localStorage.setItem("fullname", "Sami Khan");
// Retrieve
document.getElementById("local-data").innerHTML = localStorage.getItem("fullname");
Please check below options for the links to our previous or next tutorial.