Saving Data in Browser with WebStorage API

Use-Cases of this Tutorial

  • Know how to save data in the browser.
  • Know about the Web Storage API.
  • Store data persistently in browser using window.localStorage object.
  • Store data temporarily in browser using window.sessionStorage object.

The Web Storage API helps web applications to store data in the user's browser. As compared to cookies a lot more data can be saved. Data is saved as key-value pairs, making it simple to perform operations on it.

Problem with Cookies (1) — Additional Bandwidth Required

Web Storage API is special not because it only allows to save more amount of data than cookies, but rather it works differently than cookies.

Cookies are sent back to the server with every request that is made. So they take up additional bandwidth. In some cases the server has no need for the information that is passed in the cookie.

For example, consider the case of a website giving an option to the user to see pages in "dark" or a "light" mode. This preference obviously needs to be saved somewhere locally. If this was saved in a cookie, this information would be passed to the server every time user goes to a new page, or an AJAX request is made in the background. But the server actually does not care whether the user wants to see the website in "dark" or "light" mode. Some cookies are just useless to the server.

WebStorage API takes care of this issue — data is never transferred to the server. All data is saved locally within the browser.

Problem with Cookies (2) — Manipulation is Not Direct

Reading, writing and deleting cookies in Javascript is not direct. It becomes unnecessarily messy to the point that developers generally prefer to use an external cookie library.

WebStorage API on the other hand saves data as key-value pairs. Reading, writing and deleting data becomes really simple.

WebStorage API — Simple Way of Storing More Data

WebStorage API saves all data in the browser. A lot of data can be saved.

WebStorage API comes in 2 flavors. They are :

  • localStorage : The data is stored indefinitely and is available across sessions and browser tabs / windows.
  • sessionStorage : The data is stored just for the current page session. Once the page is closed, data is deleted.

Storing Data for Persistent (Indefinite) Use

The localStorage global object is the interface used to store data for persistent use. The data stored will stay even if the user closes the browser or tab. Next when user opens up the application, the stored data can be used for a better user experience.

  • The saved data has no expiration time and can only be removed through Javascript, or when the user explicitly clears the browser's local cache.
  • Data is stored as key-value pairs. Only a string value can be stored — if we want to store an object for example, it needs to converted it to a custom string (JSON encode perhaps).
  • Data is stored per origin — per domain and protocol. Keep in mind that separate data will be stored for http / https versions (if present).
  • Data is not tranferred to server any time, unlike cookies.
  • Maximum storage size is different for all browsers. To be on the safe side consider it around 5 MB. However it is possible to find the exact free storage space with the StorageManager API.

Data can be saved / retrieved / removed through methods available on the localStorage object.

  • Saving an item

    To save an item in storage or to update it, the setItem() method is called.

    This method accepts 2 parameters — the name of the key and its value.

    // add item "theme" with value "dark"
    localStorage.setItem('theme', 'dark');
    
  • Getting an item

    To retrieve an item from storage, getItem() method is called.

    This method accepts the key name of the item as its parameter.

    // get item with key "theme"
    var stored_value = localStorage.getItem('theme');
    
  • Removing an item

    To remove an item from the storage, the removeItem() method is called.

    The key to be removed is passed as its parameter.

    // remove item with key "theme"
    localStorage.removeItem('theme');
    
  • Removing all available items

    To remove all items from the storage, clear() method is called.

    // empty local storage
    localStorage.clear();
    
  • Getting notified of any change in storage

    It is also possible to listen for any changes to local storage. Say if the user has opened up multiple tabs of the application. He performs an action on one of the tabs that resulted in another item being added to local storage. In such cases, pages opened in other tabs can be informed — probably they would want to change the user interface suitably.

    A handler can be registered for the storage event. Note that the event will not be fired for the tab causing the change. Handlers in other tabs will be fired though.

    window.addEventListener('storage', function(e) {
    	// key that was changed
    	// will be null if clear() was called
    	console.log(e.key);
    
    	// new value of key
    	// will be null if key was deleted or clear() was called
    	console.log(e.newValue);
    
    	// old value of key
    	// will be null if key was newly added
    	console.log(e.oldValue);
    }
    

Storing Data for Current Page Session

The sessionStorage global object is the interface used to store data for the current page session. Once the user closes the page, saved data will be lost.

  • Data is saved only for the current page session. This means that if the user opens the same page in a different tab, a new page session will be started and will have its own session storage.
    Data will however be saved if the page is reloaded.
  • Data is saved as key-value pairs. Only strings can be saved as values (not as objects).
  • Data is stored for each given origin (per domain and protocol).
  • Data is not transferred to the server.
  • Each browser has its own limit for maximum storage space. However ~ 5MB can be assumed as a safe limit. Exact storage space can be found with the StorageManager API.

The sessionStorage object exposes methods through which data can be saved, retrieved or removed.

  • Saving an item

    To save an item for the current session or to update it, the setItem() method is called.

    This method accepts the name of the key and associated value as its parameters.

    // save item with key "preferences"
    sessionStorage.setItem('preferences', '{language:"en", font:"large"}');
    
  • Getting an item

    To get the value a saved item, getItem() method is called.

    This value of the item can be retrieved through its key.

    // get item with key "preferences"
    var stored_value = sessionStorage.getItem('preferences');
    
  • Removing an item

    To remove an item from storage, the removeItem() method is called.

    The key to be removed is passed as its parameter.

    // remove item with key "preferences"
    sessionStorage.removeItem('preferences');
    
  • Removing all available items

    To remove all saved items in session storage, clear() method is called.

    // empty session storage for the current page
    sessionStorage.clear();
    

Conclusion

Web Storage API is a welcome change from cookies. Saving lots of data in a simple way, it can really boost performance of webapps.

Finding Space Used / Space Remaining for Local Storage
KV Storage API Tutorial
Loading Comments