The Web Storage API: local storage and session storage
With Web Storage API, you can store data locally within the user’s browser.
What is Web Storage API?
Web storage is per origin (per domain and protocol). All pages from one origin can store and access the same data. Web Storage API provides mechanisms by which web browsers can store key/value pairs, in a much more intuitive fashion than using cookies.
It defines two storage mechanisms which are very important: Session Storage and Local Storage, part of the set of storage options available on the Web Platform.
Why use Web Storage API?
Web Storage API provides 2 objects for storing data on the client:
- localStorage: Stores data with no expiration date. The data will not be deleted when the browser is closed and will be available the next day, week, or year.
- sessionStorage: Stores data for only one session. The data is deleted when the user closes the specific browser tab.
Create/Update:
Web Storage allows you to save data as key/value pairs. Key/value pairs are always stored as strings. Remember to convert them to another format when needed.
localStorage.setItem(“key”, “value”);
sessionStorage.setItem(“key”, “value”);
Read:
With the getItem method, you can read the saved data. “value” is what will be returned.
localStorage.getItem(“key”);
sessionStorage.getItem(“key”);
Delete:
With the removeItem method, you can remove specific key/value pair and with the clear method, you can remove all saved data.
localStorage.removeItem(“key”);
sessionStorage.removeItem(“key”);
localStorage.clear();
sessionStorage.clear();
Difference:
localStorage stores data with no expiration date, and get cleared only through JavaScript or clearing the browser cache.
sessionStorage stores data only for a session, meaning that the data is stored until the browser tab is closed.