JavaScript - Web Storage API (localStorage and sessionStorage)
The Web Storage API is a feature in modern web browsers that allows websites to store data in a user’s browser. It is used to store key-value pairs locally on the client side. This storage mechanism is part of HTML5 and is simpler and more efficient than using cookies for storing data.
There are two main types of web storage:
1. localStorage
localStorage stores data with no expiration time. The data remains stored in the browser even after the browser window is closed. It will stay there until the user manually clears it or the website removes it.
Key characteristics of localStorage:
-
Data is stored as key-value pairs.
-
Data persists even after the browser is closed.
-
Storage limit is usually around 5–10 MB depending on the browser.
-
Data is only accessible by the same origin (same domain, protocol, and port).
Example:
// Store data
localStorage.setItem("username", "Rahul");
// Retrieve data
let user = localStorage.getItem("username");
console.log(user);
// Remove a specific item
localStorage.removeItem("username");
// Clear all stored data
localStorage.clear();
2. sessionStorage
sessionStorage is similar to localStorage but the data is stored only for the duration of a page session. When the browser tab is closed, the stored data is automatically deleted.
Key characteristics of sessionStorage:
-
Data is stored as key-value pairs.
-
Data is cleared when the browser tab is closed.
-
Each tab has its own session storage.
-
Data is accessible only within the same tab and origin.
Example:
// Store data
sessionStorage.setItem("sessionID", "12345");
// Retrieve data
let id = sessionStorage.getItem("sessionID");
console.log(id);
// Remove data
sessionStorage.removeItem("sessionID");
Difference between localStorage and sessionStorage
localStorage keeps data permanently until it is manually removed, while sessionStorage stores data only for the current browser tab session. localStorage is shared across all tabs of the same website, whereas sessionStorage is limited to the specific tab where the data was stored.
Common uses of Web Storage API
The Web Storage API is commonly used for saving user preferences, storing theme settings such as dark or light mode, keeping temporary form data, caching small amounts of data for faster page loading, and maintaining login session information on the client side.