Storage Quota Management

Check and manage storage quota

IntermediateTopic: LocalStorage/SessionStorage
Back

JavaScript Storage Quota Management Program

This program helps you to learn the fundamental structure and syntax of JavaScript programming.

Try This Code
// Method 1: Check storage quota
async function getStorageQuota() {
    if ('storage' in navigator && 'estimate' in navigator.storage) {
        const estimate = await navigator.storage.estimate();
        console.log('Quota:', estimate.quota);
        console.log('Usage:', estimate.usage);
        console.log('Available:', estimate.quota - estimate.usage);
        console.log('Usage %:', ((estimate.usage / estimate.quota) * 100).toFixed(2) + '%');
        return estimate;
    }
    return null;
}

getStorageQuota();

// Method 2: Check localStorage size
function getLocalStorageSize() {
    let total = 0;
    for (let key in localStorage) {
        if (localStorage.hasOwnProperty(key)) {
            total += localStorage[key].length + key.length;
        }
    }
    return total;
}

const size = getLocalStorageSize();
console.log('LocalStorage size:', size, 'bytes');
console.log('Size in KB:', (size / 1024).toFixed(2));

// Method 3: Check if storage is full
function isStorageFull() {
    try {
        const test = '__storage_test__';
        localStorage.setItem(test, 'test');
        localStorage.removeItem(test);
        return false;
    } catch (e) {
        return e.name === 'QuotaExceededError' || e.name === 'NS_ERROR_DOM_QUOTA_REACHED';
    }
}

if (isStorageFull()) {
    console.log('Storage is full');
} else {
    console.log('Storage has space');
}

// Method 4: Clear old data when full
function setItemWithCleanup(key, value) {
    try {
        localStorage.setItem(key, value);
    } catch (e) {
        if (e.name === 'QuotaExceededError') {
            console.log('Storage full, clearing old data...');
            // Clear items older than 7 days
            clearOldItems(7);
            // Try again
            localStorage.setItem(key, value);
        } else {
            throw e;
        }
    }
}

function clearOldItems(days) {
    const cutoff = Date.now() - (days * 24 * 60 * 60 * 1000);
    for (let i = localStorage.length - 1; i >= 0; i--) {
        const key = localStorage.key(i);
        const item = localStorage.getItem(key);
        try {
            const data = JSON.parse(item);
            if (data.timestamp && data.timestamp < cutoff) {
                localStorage.removeItem(key);
            }
        } catch (e) {
            // Not JSON, skip
        }
    }
}

// Method 5: Monitor storage usage
function monitorStorage() {
    setInterval(async () => {
        const estimate = await navigator.storage.estimate();
        const usagePercent = (estimate.usage / estimate.quota) * 100;
        
        if (usagePercent > 80) {
            console.warn('Storage usage high:', usagePercent.toFixed(2) + '%');
        }
    }, 60000); // Check every minute
}

// Method 6: Request persistent storage
async function requestPersistentStorage() {
    if ('storage' in navigator && 'persist' in navigator.storage) {
        const isPersistent = await navigator.storage.persist();
        console.log('Persistent storage granted:', isPersistent);
        return isPersistent;
    }
    return false;
}

requestPersistentStorage();
Output
Quota: 10737418240
Usage: 1024000
Available: 10736394240
Usage %: 0.01%
LocalStorage size: 5120 bytes
Size in KB: 5.00
Storage has space
Persistent storage granted: true

Understanding Storage Quota Management

Quota management prevents storage errors.

Storage Quota

~5-10MB for localStorage
Varies by browser
Check with estimate()

QuotaExceededError

Thrown when full
Handle gracefully
Clear old data

Monitoring

Check usage regularly
Warn when high
Clean up automatically

Persistent Storage

Request permission
Prevents eviction
Better for important data

Best Practices

Monitor usage
Clean old data
Handle errors
Request persistence if needed

Let us now understand every line and the components of the above program.

Note: To write and run JavaScript programs, you need to set up the local environment on your computer. Refer to the complete article Setting up JavaScript Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your JavaScript programs.

Table of Contents