Finding Space Used / Space Remaining for Local Storage

Use-Cases of this Tutorial

  • Find the amount of total storage space allotted by the browser to your web application.
  • Find the amount of free storage space remaining to store data in the browser.

For any application or website, the browser needs to save its related data somewhere. This application specific data to be saved can come through various ways :

  • data saved through Web Storage API (window.localStorage / window.sessionStorage)
  • cookies
  • data saved through Cache API
  • data saved through History API
  • data saved through Notifications API
  • IndexedDB
  • KV Storage
  • and others

The browser allots a specific amount of space to each website that is visited. Some data is saved temporarily while some are saved for a long time (unless explicitly removed).

For simple cases we probably would not need to know the amount of data currently being stored for our application and the quota allotted to it. But when storing data of the order of MBs, we may need to know whether space is left for new data to be stored. This is to avoid error cases when there is no space left to store more data — in such cases browser may delete old data which may be important for the application.

This amount of space used and space allotted can be found with the StorageManager object. This object can be accessed through navigator.storage.

// StorageManager object
var storageManagerOb = navigator.storage;

The estimate method of navigator.storage asynchronously gets the amount of space used up and total space allotted to the application.

navigator.storage.estimate().then(function(estimate) {
    console.log("Total Storage Available: " + estimate.quota);
    console.log("Storage Used: " + estimate.usage);
});

// sample output
// "Total Storage Available: 2147483648"
// "Storage Used: 49152"

This estimate method returns a Promise. This Promise when resolved contains a storage information object that holds two keys :

  • usage : Represents the amount of storage being used by the current application.
  • quota : Represents the total storage available. This is an approximate number. Storage available may be more than the value returned but never less.

Note — StorageManager requires HTTPS

The StorageManager object requires a secure context (HTTPS) to work as intended. So getting information about space remaining and total quota will not be possible on a HTTP based website.

For testing purposes it will work on localhost environment as well.

Saving Data in Browser with WebStorage API