DEV Community

Cover image for Web Storage API: localStorage and sessionStorage
Romain Trotard
Romain Trotard

Posted on • Edited on • Originally published at romaintrotard.com

Web Storage API: localStorage and sessionStorage

Database is an important software in a 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.

What is it?

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

When to use it?

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. ...

How to use it?

Storage API

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 return null.
  • removeItem(key): remove the passed key of the storage
  • clear(): 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 null
  • length: 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();
Enter fullscreen mode Exit fullscreen mode

Note: It's also possible to manipulate the data like you will do with a "simple" object:

// 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;
Enter fullscreen mode Exit fullscreen 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.

Note: The MDN encourages us not to use direct properties but to prefer the Storage API.


storage event

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 the localStorage.
  • newValue: the new value.
  • oldValue: the old value.

Note: An event is send only when the value has changed.

When is it useful?
It can be used to know if the user has changed the theme in an other 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
  }
);
Enter fullscreen mode Exit fullscreen mode

The full code is here:

Note: To play with, open in a new window twice (on my computer I need to use browser's private mode, I'm investigate on the reason):
Open in new window in codesandbox


Chrome DevTools

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:

See the storage in the Application tab of DevTools


Conclusion

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.


Do not hesitate to comment and if you want to see more, you can follow me on Twitter or go to my Website.

Top comments (0)