What is Web storage?
web storage is a storage location in our browser that can store data locally on our machine.
the web storage api is a small mechanism that the browser uses to securely store key/value pairs.
Key
: The identifier of a piece of data
value
: The value corresponding to the defined key
There are two types of storage in your browser:
Local Storage: Maintains storage for a given web page for an unlimited period of time until it is deleted.
Session Storage: Maintains storage for given web page until the browser is closed completely.
Basic Usage
We will use localStorage in our examples. For any key/value pair, the value given must always be a string. Numbers are automatically converted into strings when stored.
Let's say we want to remember the theme one user prefers every time they come back to our web page. We can use localStorage for this:
Storing Data:
We use the .setItem()
method to store a key/value pair. The first parameter of the function is the key, the second is the value we want to assign to it.
localStorage.setItem('appTheme', 'dark');
Accessing Data:
console.log(localStorage.getItem('appTheme'));
Accessing the whole Storage object
console.log(localStorage);
Working With Objects
Since we can only store strings inside our browser's storage, we have to convert any objects we might want to store onto a JSON string:
const myData = { name: 'david', job: 'web developer'};
localStorage.setItem('user', JSON.stringify(myData));
You can see the changes in your browser's developer tools under the 'application' tab in Chrome or "Storage" tab in Firefox. Notice how the storage in only kept for the web page where we ran our code, the live server localhost:5500.
When you want to read an object that has been stringified, you will need to run JSON.parse()
like so:
console.log(JSON.parse(localStorage.getItem('user')));
Deleting Data
Data stored using localStorage will not be deleted until it is deleted manually or the browser's history is erased.
So in order two delete items, we have two methods:
1. Delete specific items using removeItem()
localStorage.removeItem('appTheme');
this allows you to delete an item by specifying the key that belongs to it.
2. Clear the entire storage for the active web page
localStorage.clear();
This method is straight forward and will erase all key/value pairs entirely from the web page's local storage.
The Storage Event
We can detect storage changes on a web page by using the storage event listener.
Keep in mind that this event will only be triggered when opening two tabs with the same origin, so the same web page. If we make changes to the storage in the first tab, the event will triggered in the second tab and all other tabs will the same origin. You can use this event like so:
window.addEventLister('storage', (e)=>{
console.log(`Storage Event triggered from ${document.title}`)
console.log(e)
});
Other Facts
When browsing privately (incognito), localStorage will also be emptied when you close the browser, in the same way as
sessionStorage
is deleted.With little setup, localStorage can be succesfully used as a small database for basic practice projects and you can implement a full CRUD functionality using it.
The browser's web page storage is actually an object, so you can treat it like one and perform actions such as:
localStorage.appTheme = 'dark':
localStorage['userName'] = 'david';
//using object methods
console.log(Object.values(localStorage))
However, it is best to use the setItem and getItem methods to avoid possible problems.
Wrapping Up
I hope you enjoyed the article, if yes then don't forget to press ❤️ and Subscribe. You can also bookmark it for later use. It was fun to create this article and If you have any queries or suggestions don't hesitate to drop them. See you.
You can extend your support by giving me stars on GitHub Profile.😊👇
G i t h u b
P o r t f o l i o
L i n k e d i n
Top comments (5)
Great article, thanks!
I just wanted to remind everyone that most browsers offer the option to "continue where you left off" to the user when closing the browser for the first time. If this option is selected the sessionStorage content won't be cleared and will still be present if the user closes the browser and opens it again.
This has bitten me in the past so please be careful when using sessionStorage.
Well said,
Most Welcome!
Going to do a follow-up on the IndexedDB API? Not as easy to use, but quite powerful!
This is very well written, and one I'll be referring back to. Thanks!
Thanks a lot mate