DEV Community

loading...
Cover image for Web Storage API

Web Storage API

Naveenchandar
Optimistic human 🧍 and trying hard not to procrastinate things!!!😜 Passionate about Web Development and have a keen interest in learning new technologies.
・3 min read

What is Web Storage
Web storage is more secure, and large amounts of data can be stored locally within the user's browser, without affecting website performance.

Web storage has two types of mechanisms. They are

  • Session storage
  • Local storage

Session Storage
Changes are available per tab. Changes made are saved and available for the current page until the tab is closed.

Local Storage
Changes are available until we explicitly delete it. It will be available in all tabs with the same origin. Even we close the browser or tab or reboot the OS, these changes will remain as it is.

Methods and Properties available in both session storage and local storage are

  • Set Item
  • Get Item
  • Remove Item
  • Clear
  • Key
  • Length

Set Item

It takes two parameters key and value.

window.localStorage.setItem('name', 'Dev Community');
window.sessionStorage.setItem('name', 'Dev Community');
Enter fullscreen mode Exit fullscreen mode

Where name is the key and Dev Community is the value. Also note that local storage and session storage can only store strings.

To store arrays or objects, you should convert them to strings.

To do this, we can use the JSON.stringify() method before storing to setItem.

const person = {
    name: "Naveen Chandar",
    location: "India"
}
window.localStorage.setItem('user',JSON.stringify(person));
window.sessionStorage.setItem('user',JSON.stringify(person));
Enter fullscreen mode Exit fullscreen mode

The stored item can be accessed in application tab in chrome developer tools.

Get Item

This method allows you to access the data stored in the browser’s localStorage/sessionStorage object.

It accepts only one parameter, which is the key given while storing the value, and it returns the value as a string.

window.localStorage.getItem('user');
window.sessionStorage.getItem('user');
Enter fullscreen mode Exit fullscreen mode

This returns a string with value

"{"name":"Naveen Chandar","location":"India"}"
Enter fullscreen mode Exit fullscreen mode

To use this value, you should convert it back to an object.

To do this, we make use of the JSON.parse() method, which converts a JSON string into a JavaScript object.

JSON.parse(window.localStorage.getItem('user'));
JSON.parse(window.sessionStorage.getItem('user'));
Enter fullscreen mode Exit fullscreen mode

Remove Item

This method removes the specified key from the storage if it exists. If there is no item associated with the given key, this method will do nothing.

It accepts only one parameter, which is the key given while storing the value.

window.localStorage.removeItem('user');
window.sessionStorage.removeItem('user');
Enter fullscreen mode Exit fullscreen mode

Clear

This method clears all items present in local storage.
It doesn't accept parameters.

window.localStorage.clear();
window.sessionStorage.clear();
Enter fullscreen mode Exit fullscreen mode

Key

This method is used to get the key on a given position. It will be useful in situations where you need to loop through keys and allows you to pass a number or index to local/session storage to retrieve the name of the key.

window.localStorage.key(index);
window.sessionStorage.key(index);
Enter fullscreen mode Exit fullscreen mode

Length

This property returns the number of data items stored in a given Storage object.

window.localStorage.length;
window.sessionStorage.length;
Enter fullscreen mode Exit fullscreen mode

Broswer Support

It is HTML5 specification and it is supported in all major browsers including IE8. To check whether browser supports for local/session storage

if (typeof(Storage) !== "undefined") {
  // Code for localStorage/sessionStorage.
} else {
  // Sorry! No Web Storage support..
}
Enter fullscreen mode Exit fullscreen mode

Limitations

  • Do not store sensitive user information in local/session storage such as passwords etc.,
  • It is not a alternative for a server based database as information is stored only on the browser (client side).

Difference B/w session storage and local storage

Size

Session storage size is 5MB
Local storage size is 5MB/10Mb

Accessiblity

Session storage can be accessed only on same tab
Local storage can be accessed anywhere within browser tabs.(Not in Incognito mode).

Storage Location

Both session and local storage are stored in browser.

Expiration Date

Session storage will be expired once the tab is closed.
Local storage won't get expired unless removing it manually.

When to use session storage and local storage ?

Session storage - It should be used when you need to store something that changes frequently.
Local storage - It should be used for long term use where data won't get changed often.

Thank you for reading this post. Have a great day πŸ™‚

Discussion (3)

Collapse
lionelrowe profile image
lionel-rowe • Edited

Session storage - It should be used when you need to store something that changes frequently.
Local storage - It should be used for long term use where data won't get changed often.

I don't see why this should be the case. The use cases for each have nothing to do with frequency of changes and everything to do with whether the data needs to persist between tab sessions.

For very frequent writes, especially if they involve large volumes of data, IndexedDB is a better tool as it's asynchronous (non-blocking) and can store many types of structured data without serializing them first.

Unfortunately the IndexedDB API is horrendously designed, so a tiny wrapper library such as idb is advisable.

Collapse
naveenchandar profile image
Naveenchandar Author

Thanks for the insight πŸ™‚.

Some comments have been hidden by the post's author - find out more