Database is an important software in an application when we want to store some data and retrieve them later. But sometimes, we just want to be able to store some temporarily data, which are not useful for the backend and that can be lost without having problems. In this case, store this in a nosql or sql database can be overkill. It’s a typical case where the Web Storage API can be great. But what is it? And how to use it?
That’s what we are going to talk in this article.
The Web Storage API provides us a way to store some key/value data in the browser.
These data are stored by origin, so it’s not possible to get/update/delete data from another origin.
There are two ways to store data:
localStorage
sessionStorage
This 2 mechanisms have the same API that we are going to see later in the article.
What is the difference between these 2 mechanisms?
The difference is the duration the data is stored. When you use localStorage
, the data is stored until you delete it in JS or the user clear its cache.
Contrary to sessionStorage
that stores the data for a session, i.e. is deleted when the user close its browsers’ tab.
Some properties to be aware:
- data needs to be serializable
- the maximum size is around 5Mb
- it’s always synchronous
- there is no data protection
- can’t be used in web workers
There are a lot of use case where localStorage and sessionStorage are useful. Here I will list a few:
- Remember my choice: after an action that needs to be confirmed, it can be user-friendly to give the choice to confirm automatically the next same actions.
- Dark theme: when you make a dark theme, the first time the user comes into your website, you will get the theme’s preference from his system. Despite that, he can choose to change the theme so let’s remember its choice for the next time he’ll come.
- Anything the user chose that you want to keep (things that can be lost of course)
- Keep the previous search in sessionStorage: thanks to that when the user returns to the listing page you can filter like before during a same session. …
The API is the same for sessionStorage
and localStorage
. It’s the Storage
API:
setItem(key, value)
: add an item in the storage. If the key already exists it will override the previous value.getItem(key)
: get the value corresponding to a key. If the key does not exist it will returnnull
.removeItem(key)
: remove the passed key of the storageclear()
: remove all the entries of the storage for the current domain name.key(index)
: get a value in the storage at the specified index. If there is no key at this index, it will return nulllength
: get the number of value in the storage.
Okay, let’s see this in action working with localStorage
:
// Put "dark" for the key "theme_mode"
localStorage.setItem('theme_mode', 'dark');
// Put "light" for the key "theme_mode"
localStorage.setItem('theme_mode', 'light');
// Will print
// The current theme mode is: "light"
console.log(
'The current theme mode is:',
localStorage.getItem('theme_mode'),
);
// Will print:
// The value in localStorage at the index 0 is: light
console.log(
'The value in localStorage at the index 0 is:',
localStorage.key(0),
);
// Remove the entry for "theme_mode"
localStorage.removeItem('theme_mode');
// Remove all values in localStorage
localStorage.clear();
// Set the value "dark" for "them_mode"
localStorage.theme_mode = 'dark';
// Will print
// The current value of the theme mode is: dark
console.log(
'The current value of the theme mode is:',
localStorage.theme_mode,
);
// Remove the entry corresponding to "theme_mode"
delete localStorage.theme_mode;
In this case if the key does not exist it will return you undefined
(not null
like getItem
). And there is no way to quickly remove all the value without looping through all the values.
It’s possible to listen changes made on localStorage
in other pages thanks to the event storage
. In the callback you will have access to:
key
: the key of the entry that has been changed in thelocalStorage
.newValue
: the new value.oldValue
: the old value.
When is it useful?
It can be used to know if the user has changed the theme in another window.
If it’s the case you can also change the theme in other window that listen the storage
event :)
Let’s code this.
// Configure the `storage` event handler
window.addEventListener(
'storage',
({ key, newValue, oldValue }) => {
// Do whatever we want here
// Probably first check the key received
},
);
The full code is here:
Instead of using the console to watch what you’ve got in your localStorage
and sessionStorage
for the current origin, you can see it directly in the Application tab of your DevTools:
We’ve just seen that the Web Storage API provides us two ways to store non-sensitive data in the browser: localStorage and sessionStorage.
The only difference between both is when the data is cleared, otherwise the use of this two mechanisms is the same setItem
, getItem
, removeItem
or clear
.
With localStorage
you can listen changes made in other pages opened in the user’s browser. The event to listen is storage.
The use cases are multiple. For example dev.to uses it to store the last version edited of a post. So if you refresh your browser without saving, you get the version you’ve just edited. It saved my life a couple of times :) On my site, I use it for the theme mode coupled with css variables (not to re-render everything). Enjoy coding.
Remember, the data is not sent to the backend so if you want to do some authorization, prefer to use the Cookie API to store the JWT token for example. Yeah I will do a next article about that, don’t be afraid. If you want to store more structured data in the browser, you can also use IndexedDb.
You can find me on Twitter if you want to comment this post or just contact me. Feel free to buy me a coffee if you like the content and encourage me.