Skip to content

How to Fix localStorage Quota Exceeded Error in JavaScript

DodaTech Updated 2026-06-24 3 min read

In this tutorial, you'll learn about How to Fix localStorage Quota Exceeded Error in JavaScript. We cover key concepts, practical examples, and best practices.

The Problem

The browser throws QuotaExceededError: Failed to execute 'setItem' on 'Storage' when localStorage exceeds its 5-10 MB storage limit per origin.

Quick Fix

Step 1: Check current storage usage

Measure how much storage you are using:

function getStorageSize() {
    let total = 0;
    for (let key in localStorage) {
        if (localStorage.hasOwnProperty(key)) {
            total += localStorage.getItem(key).length + key.length;
        }
    }
    return (total / 1024 / 1024).toFixed(2) + ' MB';
}
console.log(getStorageSize());

Step 2: Remove unused keys

Clean up stale data before adding new items:

function safeSetItem(key, value) {
    try {
        localStorage.setItem(key, value);
    } catch (e) {
        if (e.name === 'QuotaExceededError') {
            const oldestKey = findOldestKey();
            localStorage.removeItem(oldestKey);
            localStorage.setItem(key, value);
        }
    }
}
function findOldestKey() {
    let oldest = null;
    let oldestTime = Infinity;
    for (let key in localStorage) {
        const time = parseInt(localStorage.getItem(key + '_ts') || '0', 10);
        if (time < oldestTime) {
            oldestTime = time;
            oldest = key;
        }
    }
    return oldest;
}

Step 3: Compress data before storing

Compress JSON strings to save space:

function compressAndStore(key, data) {
    const json = JSON.stringify(data);
    if (json.length > 1024 * 10) {
        const compressed = btoa(json);
        localStorage.setItem(key, compressed);
    } else {
        localStorage.setItem(key, json);
    }
}
function retrieveAndDecompress(key) {
    const value = localStorage.getItem(key);
    try {
        return JSON.parse(value);
    } catch {
        return JSON.parse(atob(value));
    }
}

Step 4: Migrate to IndexedDB for large data

IndexedDB supports much larger storage (50% of disk):

async function saveLargeData(data) {
    return new Promise((resolve, reject) => {
        const request = indexedDB.open('AppDB', 1);
        request.onupgradeneeded = (event) => {
            const db = event.target.result;
            if (!db.objectStoreNames.contains('store')) {
                db.createObjectStore('store');
            }
        };
        request.onsuccess = (event) => {
            const db = event.target.result;
            const tx = db.transaction('store', 'readwrite');
            tx.objectStore('store').put(data, 'largeData');
            tx.oncomplete = () => resolve();
            tx.onerror = (e) => reject(e.target.error);
        };
        request.onerror = (e) => reject(e.target.error);
    });
}

Prevention

  • Estimate storage needs before using localStorage for caching.
  • Implement an LRU eviction policy for cached data.
  • Use IndexedDB for anything over 100 KB.
  • Compress JSON data with JSON.stringify and test compressed size.
  • Show a warning to users when storage is nearly full.

Common Mistakes with localstorage quota

  1. Misunderstanding that String is [Char] with poor performance for large text operations
  2. Using foldl instead of foldl' causing stack overflow on large lists
  3. Forgetting deriving (Show, Eq) on custom data types needed for debugging

These mistakes appear frequently in real-world JS code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

### What is the localStorage size limit?

The localStorage limit is 5-10 MB per origin, depending on the browser. Chrome and Firefox offer approximately 10 MB, while Safari offers 5 MB. Private browsing modes may have lower limits or disable localStorage entirely. IndexedDB typically offers 50% of available disk space.

Does clearing the browser cache free localStorage?

No. localStorage is separate from the browser cache. Clearing cache, cookies, or browsing history in browser settings may also clear localStorage depending on the browser. Users can also clear site data for individual origins in DevTools under Application > Storage.

Can I detect how much storage is remaining?

Yes, use the Storage API (navigator.storage.estimate) for modern browsers:

const estimate = await navigator.storage.estimate();
console.log('Used:', estimate.usage, 'Quota:', estimate.quota);

This works for the entire origin including IndexedDB, Cache API, and localStorage combined.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro