Web Storage
Every time you change the color theme between light and dark, watch a video, add a product to the cart, open or close the sidebar, popular web applications remember the state of the interface and restore it during your next visit.
By default, the state of the interface is stored in the browser tab’s memory and is lost when the web application is closed. To avoid this, you need to store interface data between page visits. This problem is solved by storing information about the state of the web application on the user's computer.
Web Storage API
Web storage consists of local storage (localStorage
) and session storage
(sessionStorage
). It provides a way to store data in an intuitive way, in the
form of key:value
pairs. Technically, only strings can be added to web
storage, but this is not a problem if you use JSON
class methods to convert
complex types. Object methods or functions are not added to web storage, only
data.
Local storage (localStorage
) is unique for each web application and will be
the same across multiple tabs in which the web application is running. Data in
local storage is not deleted even when you close your browser or shut down your
computer. To remove it, you need to use JavaScript.
Session storage (sessionStorage
) is similar to local storage, as it is also
unique for each web application, but the life of the stored data is limited by
the browser tab session. As soon as the user closes the tab or browser, the data
is deleted. In practice, session storage is used much less often.
Do not store passwords, credit card numbers and similar confidential information in web storage. If a malicious script gains access to the web page, it will easily read this data.
Local storage
Intended for permanently storing data in the format of key:value
pairs on the
user's computer and reading it when the page is revisited. Local and session
storages are part of the browser, and they are available as properties of the
window
object, have the same set of properties and methods, and differ only in
behavior.
setItem(key, value)
makes a new or updates an existing storage item.getItem(key)
returns a value with the keykey
from the storage.removeItem(key)
removes an item with the keykey
from the storage.clear()
completely clears all items in the storage.length
stores the number of items in the storage.
Saving
Using the setItem(key, value)
method, you can add a new item as a key:value
pair.
localStorage.setItem("ui-theme", "light");
localStorage.setItem("sidebar", "expanded");
localStorage.setItem("notification-level", "mute");
If you need to store something other than a string, such as an array or object,
you need to convert it to a string using the JSON.stringify()
method.
const settings = {
theme: "dark",
isAuthenticated: true,
options: [1, 2, 3],
};
localStorage.setItem("settings", JSON.stringify(settings));
Reading
The getItem(key)
method is intended to read a storage item with the key key
.
If there is no item with such key in the storage, the method returns null
.
When the value is a regular string, there is no need to parse it.
localStorage.setItem("ui-theme", "dark");
const theme = localStorage.getItem("ui-theme");
console.log(theme); // "dark"
Otherwise, you need to parse the value using the JSON.parse()
method to get
valid data.
const settings = {
theme: "dark",
isAuthenticated: true,
options: [1, 2, 3],
};
localStorage.setItem("settings", JSON.stringify(settings));
const savedSettings = localStorage.getItem("settings");
const parsedSettings = JSON.parse(savedSettings);
console.log(parsedSettings); // settings object
Do not forget to use the try...catch
construct with the JSON.parse()
method
to avoid script crash if reading invalid JSON.
Removal
The removeItem(key)
method removes an existing item with the key key
from
the storage.
localStorage.setItem("ui-theme", "dark");
console.log(localStorage.getItem("ui-theme")); // "dark"
localStorage.removeItem("ui-theme");
console.log(localStorage.getItem("ui-theme")); // null
Storage clearing
Complete storage clearing is not safe, as it can affect the records made by
other project developers. However, if you want to completely clear the storage,
call the clear()
method.
localStorage.setItem("ui-theme", "light");
localStorage.setItem("sidebar", "expanded");
localStorage.setItem("notification-level", "mute");
console.log(localStorage.getItem("ui-theme")); // "light"
console.log(localStorage.getItem("sidebar")); // "expanded"
console.log(localStorage.getItem("notification-level")); // "mute"
localStorage.clear();
console.log(localStorage.getItem("ui-theme")); // null
console.log(localStorage.getItem("sidebar")); // null
console.log(localStorage.getItem("notification-level")); // null
Message saving
Let's create a form to enter a message and save it to localStorage
upon
submission. Change the text box value and click "Save". Text in the output field
will change to the one you entered. Reload the page and you will see the same
text, although you have not entered anything yet. When the page is loaded, the
last stored value is taken from localStorage
. Initially, there is no such
record in the storage, so an empty string will be displayed.
You can view the contents of a web storage in the developer tools, on the
Application
tab. You can also manually delete and add items there. In
practice, this is used during application development and debugging.

Service for localStorage
In order to reduce the amount of repetitive code when working with web storage,
you can create a service with standard methods, for example, save
and load
.
They will abstract repetitive parse error handling code and the like.
const save = (key, value) => {
try {
const serializedState = JSON.stringify(value);
localStorage.setItem(key, serializedState);
} catch (error) {
console.error("Set state error: ", error.message);
}
};
const load = key => {
try {
const serializedState = localStorage.getItem(key);
return serializedState === null ? undefined : JSON.parse(serializedState);
} catch (error) {
console.error("Get state error: ", error.message);
}
};
export default {
save,
load,
};
Now you can safely add and read items from local storage. Try to finish the
remove(key)
method yourself to remove an item, similarly to load(key)
and
save(key, value)
.