localStorage
and sessionStorage
. These web storage objects allow web applications to store key - value pairs directly in the user’s browser, without the need for server - side storage in many cases. This blog will explore the fundamental concepts, usage methods, common practices, and best practices of localStorage
and sessionStorage
.localStorage
and sessionStorage
](#differences - between - localstorage - and - sessionstorage)Web Storage is a client - side storage mechanism introduced in HTML5. It provides a way to store data on the user’s browser in a simple key - value format. Unlike cookies, web storage has a larger storage capacity (usually around 5MB per origin) and the data is not sent to the server with every HTTP request, which can improve performance.
localStorage
and sessionStorage
localStorage
:localStorage
persists even after the browser is closed and reopened. It has no expiration date unless explicitly removed by the web application or the user.sessionStorage
:sessionStorage
is only available for the duration of the page session. When the page session ends (i.e., the tab or window is closed), the data is cleared.sessionStorage
data.To store data in localStorage
or sessionStorage
, you can use the setItem()
method. The method takes two parameters: a key and a value. The value must be a string.
// Storing data in localStorage
localStorage.setItem('username', 'john_doe');
// Storing data in sessionStorage
sessionStorage.setItem('userLoggedIn', 'true');
To retrieve data, you can use the getItem()
method. It takes the key as a parameter and returns the corresponding value. If the key does not exist, it returns null
.
// Retrieving data from localStorage
const username = localStorage.getItem('username');
console.log(username);
// Retrieving data from sessionStorage
const isLoggedIn = sessionStorage.getItem('userLoggedIn');
console.log(isLoggedIn);
To remove a specific key - value pair, you can use the removeItem()
method. It takes the key as a parameter.
// Removing data from localStorage
localStorage.removeItem('username');
// Removing data from sessionStorage
sessionStorage.removeItem('userLoggedIn');
To clear all the data stored in localStorage
or sessionStorage
, you can use the clear()
method.
// Clearing localStorage
localStorage.clear();
// Clearing sessionStorage
sessionStorage.clear();
You can use localStorage
to store user preferences such as theme selection, font size, or language settings. This way, the user’s preferences will be remembered even when they revisit the website.
// Storing user theme preference
const theme = 'dark';
localStorage.setItem('theme', theme);
// Retrieving user theme preference on page load
const storedTheme = localStorage.getItem('theme');
if (storedTheme) {
// Apply the theme
document.body.classList.add(storedTheme);
}
You can use localStorage
to cache API responses to reduce the number of requests to the server. For example, if you have an API that returns a list of products, you can store the response in localStorage
and check if the data is already available before making another API call.
const apiUrl = 'https://api.example.com/products';
// Check if the data is already in localStorage
const cachedData = localStorage.getItem('products');
if (cachedData) {
const products = JSON.parse(cachedData);
// Use the cached products
console.log(products);
} else {
// Make an API call
fetch(apiUrl)
.then(response => response.json())
.then(data => {
// Store the data in localStorage
localStorage.setItem('products', JSON.stringify(data));
// Use the fetched products
console.log(data);
});
}
Since localStorage
and sessionStorage
can only store strings, if you want to store complex data types such as objects or arrays, you need to serialize them using JSON.stringify()
before storing and deserialize them using JSON.parse()
when retrieving.
const user = {
name: 'John Doe',
age: 30
};
// Serialize and store the object in localStorage
localStorage.setItem('user', JSON.stringify(user));
// Retrieve and deserialize the object
const storedUser = localStorage.getItem('user');
if (storedUser) {
const parsedUser = JSON.parse(storedUser);
console.log(parsedUser.name);
}
When working with localStorage
and sessionStorage
, errors can occur, such as the storage quota being exceeded. You should handle these errors gracefully in your code.
try {
localStorage.setItem('largeData', 'a very long string...');
} catch (e) {
if (e instanceof DOMException && (
e.code === 22 ||
e.code === 1014 ||
e.name === 'QuotaExceededError' ||
e.name === 'NS_ERROR_DOM_QUOTA_REACHED')
) {
console.error('Storage quota exceeded');
} else {
console.error('An error occurred:', e);
}
}
localStorage
or sessionStorage
. Since the data is stored on the client - side, it can be accessed by JavaScript code running on the same origin, which poses a security risk.localStorage
and sessionStorage
. Make sure to sanitize all user input and output to prevent XSS vulnerabilities.localStorage
and sessionStorage
are powerful tools in JavaScript for client - side storage. They offer a simple and efficient way to store data on the user’s browser, with different persistence and scope characteristics. By understanding their fundamental concepts, usage methods, common practices, and best practices, you can use them effectively in your web applications to improve performance, store user preferences, and cache data. However, it’s important to handle errors and security considerations carefully to ensure the reliability and security of your application.