Storing and Retrieving Data with JavaScript Local Storage
In this tutorial, we will learn about using the Local Storage and Session Storage API in JavaScript to save and get information on the user's browser.
What is Local Storage?
Local storage is a good way to store data in a web browser with no expiration date. This means the data will still be there even if you close and reopen the browser.
Use Case
You can save user preferences like theme (dark or light mode), language, and other settings using Local Storage.
What is Session Storage?
Session Storage is like Local Storage because you can save data using key/value pairs. But, when users close the tab or window, the data in the session storage is deleted.
Use Case
This is really useful for storing information that is only needed for a short period of time until the user closes the browser. Like things you type into forms or temporary app settings.
Basics Operations
- Storing data.
- Retrieving data.
- Removing data.
- Clearing all data.
Storing Data
To store data in Local Storage, use the localStorage.setItem('key', 'value')
method with a key and value.
// storing a string
localStorage.setItem("username", "James");
// storing a number
localStorage.setItem('userAge', 30);
// Preparing an object to store in local storage
const userData = {
name: "James",
age: 30,
country: "India"
};
// Local Storage only supports strings
// Converting the object to a JSON string and storing it in local storage
localStorage.setItem("userData", JSON.stringify(userData));
Retrieving Data
To retrieve data from Local Storage, use the localStorage.getItem('key')
method with the key.
// Retrieving a string
const username = localStorage.getItem("username");
console.log(username); // Output: JohnDoe
// Retrieving a number
const userAge = localStorage.getItem("userAge");
console.log(userAge); // Output: 30
// Retrieving the stored JSON string
const userData = localStorage.getItem("userData");
// Parsing it back to an object
const retrievedUserData = JSON.parse(userData);
console.log('User Data:', retrievedUserData);
// Output: User Data: { name: "James", age: 30, country: "India" }
Removing Data
To remove a specific item from Local Storage, use the localStorage.removeItem('key')
method with the key.
This demonstrates how to remove an item from local storage and verify its removal.
Clearing All Data
To clear all data from Local Storage, use the localStorage.clear()
method.
This demonstrates how to clear all items from local storage and verify their removal.
// Clearing all items from local storage
localStorage.clear();
// Attempting to retrieve the items to confirm they have been deleted
const clearedUserAge = localStorage.getItem("userAge");
const clearedUserData = localStorage.getItem("userData");
console.log(clearedUserAge); // Output: null
console.log(clearedUserData); // Output: null
Using localStorage.clear()
can have several drawbacks, such as the total loss of all stored data. This can negatively impact the user experience by erasing preferences, settings, and important information. Additionally, Once the data is cleared, it cannot be recovered.
Usage Session Storage
Storage Capacity
Different browsers may have different implementations, storage limits. Most modern browsers provide a storage limit of approximately 5-10 MB per origin.
Local Storage usually offers a larger storage capacity of around 5MB per origin, while Session Storage also generally offers around 5MB per tab or window. This is much more than the 4KB limit of cookies.
Benefits
Usage: Data can be easily stored and retrieved using a simple API.
Storage: Larger storage capacity compared to cookies (typically around 5MB per origin).
Disadvantages
Local storage and session storage are both useful for storing data on the client side, they come with several disadvantages that developers must consider. It is not safe to store important information here as there is no encryption.
Security Risks
Vulnerability to XSS Attacks: Data in local storage can be accessed by any JavaScript running on the page, making it vulnerable to cross-site scripting (XSS) attacks.
No HTTP-Only Protection: Unlike cookies, local storage data cannot be flagged as HTTP-only, meaning it can be accessed via JavaScript at any time.
How to Store an Array in Local or Storage
To store an array in local or session storage, you need to convert the array to a JSON string because local storage only supports string values.
To convert an array into a string, simply use the JSON.stringify(array)
function.
Here is how to do it in local storage:
// Example array
const fruits = ["apple", "banana", "cherry"];
// Convert the array to a JSON string and store it in local storage
localStorage.setItem("fruits", JSON.stringify(fruits));
// for session storage
// Convert the array to a JSON string and store it in session storage
sessionStorage.setItem("fruits", JSON.stringify(fruits));
What Is Difference Between Local Storage And Session Storage
Local Storage and Session Storage are both in the Web Storage API, but they are not the same.
Local Storage
Data stored in local storage does not expire. It remains available until explicitly removed by the user or through the application's code.
Session Storage
Data stored in session storage is only available for the duration of the page session. It is cleared when the page session ends, which usually happens when the browser tab or window is closed.
How To Check If Local Storage Access Is Blocked
You can detect if localStorage access is blocked using a try-catch block in JavaScript
This code is trying to add and delete an item in localStorage. If there is an issue, it means that access to localStorage is blocked.
The function will return either true or false if all operations are successful.
const isLocalStorageAccessible = () => {
try {
// Attempt to use localStorage
localStorage.setItem("test", "test");
localStorage.removeItem("test");
return true;
} catch (e) {
return false;
}
};
Usage