Course offer · HLD · LLD · System Design at ₹799 until 30 Nov (not interview packs)

Storage Quota Management in JavaScript

Manage browser storage quota in JavaScript: estimate(), localStorage size, QuotaExceededError and cleanup of old data, with explanation and output.

IntermediateJavaScript LocalStorage and SessionStorageExample 5 of 10

Run this in a browser page served over HTTPS or localhost. navigator.storage is not available in plain Node.

storage-quota-management.js
1// Method 1: Check storage quota
2async function getStorageQuota() {
3 if ('storage' in navigator && 'estimate' in navigator.storage) {
4 const estimate = await navigator.storage.estimate();
5 console.log('Quota:', estimate.quota);
6 console.log('Usage:', estimate.usage);
7 console.log('Available:', estimate.quota - estimate.usage);
8 console.log('Usage %:', ((estimate.usage / estimate.quota) * 100).toFixed(2) + '%');
9 return estimate;
10 }
11 return null;
12}
13
14getStorageQuota();
15
16// Method 2: Check localStorage size
17function getLocalStorageSize() {
18 let total = 0;
19 for (let key in localStorage) {
20 if (localStorage.hasOwnProperty(key)) {
21 total += localStorage[key].length + key.length;
22 }
23 }
24 return total;
25}
26
27const size = getLocalStorageSize();
28console.log('LocalStorage size:', size, 'bytes');
29console.log('Size in KB:', (size / 1024).toFixed(2));
30
31// Method 3: Check if storage is full
32function isStorageFull() {
33 try {
34 const test = '__storage_test__';
35 localStorage.setItem(test, 'test');
36 localStorage.removeItem(test);
37 return false;
38 } catch (e) {
39 return e.name === 'QuotaExceededError' || e.name === 'NS_ERROR_DOM_QUOTA_REACHED';
40 }
41}
42
43if (isStorageFull()) {
44 console.log('Storage is full');
45} else {
46 console.log('Storage has space');
47}
48
49// Method 4: Clear old data when full
50function setItemWithCleanup(key, value) {
51 try {
52 localStorage.setItem(key, value);
53 } catch (e) {
54 if (e.name === 'QuotaExceededError') {
55 console.log('Storage full, clearing old data...');
56 // Clear items older than 7 days
57 clearOldItems(7);
58 // Try again
59 localStorage.setItem(key, value);
60 } else {
61 throw e;
62 }
63 }
64}
65
66function clearOldItems(days) {
67 const cutoff = Date.now() - (days * 24 * 60 * 60 * 1000);
68 for (let i = localStorage.length - 1; i >= 0; i--) {
69 const key = localStorage.key(i);
70 const item = localStorage.getItem(key);
71 try {
72 const data = JSON.parse(item);
73 if (data.timestamp && data.timestamp < cutoff) {
74 localStorage.removeItem(key);
75 }
76 } catch (e) {
77 // Not JSON, skip
78 }
79 }
80}
81
82// Method 5: Monitor storage usage
83function monitorStorage() {
84 setInterval(async () => {
85 const estimate = await navigator.storage.estimate();
86 const usagePercent = (estimate.usage / estimate.quota) * 100;
87
88 if (usagePercent > 80) {
89 console.warn('Storage usage high:', usagePercent.toFixed(2) + '%');
90 }
91 }, 60000); // Check every minute
92}
93
94// Method 6: Request persistent storage
95async function requestPersistentStorage() {
96 if ('storage' in navigator && 'persist' in navigator.storage) {
97 const isPersistent = await navigator.storage.persist();
98 console.log('Persistent storage granted:', isPersistent);
99 return isPersistent;
100 }
101 return false;
102}
103
104requestPersistentStorage();

Sample Output

Quota: 10737418240

This is the site-wide budget across all storage types, so it is much bigger than the localStorage limit.

Persistent storage granted: true

Some browsers return false unless the site is installed or bookmarked.

In this one

  • How much storage a site gets
  • How to read quota and usage with estimate()
  • How to catch QuotaExceededError and clean up
  • What persistent storage protects against

How it works

  1. 1

    getStorageQuota starts an async estimate.

  2. 2

    getLocalStorageSize adds key and value lengths.

  3. 3

    isStorageFull writes a test key.

  4. 4

    setItemWithCleanup retries after clearing old items.

  5. 5

    monitorStorage can warn when usage is high.

  6. 6

    requestPersistentStorage asks the browser to keep data.

Edge cases

Retry still fails

If nothing old was removed, the second setItem throws again.

Wrap the retry in try/catch and tell the user.

estimate not supported

Older browsers lack navigator.storage.

The function returns null when the API is missing.

Persist refused

persist() resolves to false.

Treat stored data as a cache that can disappear.

What's going on

Browser storage is not unlimited. localStorage gets about 5 to 10 MB per site, and the limit varies by browser. If you try to save more, the browser throws a QuotaExceededError. Quota management means checking space and handling that error before it breaks your app.

Method 1 calls navigator.storage.estimate(). It returns how much space the site may use (quota) and how much it uses (usage). This covers all storage types for the site, not only localStorage. The function is async, which means it returns a promise and finishes later. So its lines print after the normal lines.

Method 2 measures localStorage by adding up the length of every key and value. It counts characters, which is a rough guide. Browsers store text in UTF-16, so the real bytes can be about double.

Method 3 tests if storage is full by writing a small test key. If it throws QuotaExceededError, or NS_ERROR_DOM_QUOTA_REACHED in older Firefox, storage is full.

Method 4 handles the error gracefully. When setItem fails because storage is full, it clears old data and tries again. clearOldItems removes JSON items whose timestamp is older than 7 days. It loops backwards, because removing items shifts the positions of the rest. Non-JSON items are skipped.

Method 5 monitors usage every minute and warns above 80 percent.

Method 6 asks for persistent storage. Without it, the browser may delete, or evict, your data when the device is low on space. persist() requests protection, which is better for important data. The browser may say no.

Best practices: monitor usage, clean old data, handle errors, and request persistence if needed.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

Which error is thrown when storage is full?

Pick an answer to check it.

Question 2

Why does clearOldItems loop backwards?

Pick an answer to check it.

Questions people ask

Why do the quota lines print after "Storage has space"?

estimate() is async, so its result arrives after the normal code runs.

Is the localStorage size exact?

No. It counts characters, not exact bytes.

Does monitorStorage run here?

No. It is defined but not called. Call monitorStorage() to start it.