When localStorage limit is exceeded, browser throws [QuotaExceededError]. Application won’t break, but data won’t be saved! ⚠️
try {
localStorage.setItem('bigData', 'very_large_data');
} catch (error) {
if (error instanceof QuotaExceededError) {
console.log('Limit exceeded!'); // Handle error
}
}Think of localStorage as a box of a certain size. If you try to put more than it can hold, the lid won’t close! 📦💥
Usually browsers have 5-10 MB limit per domain:
// Typical limit: 5-10 MB
// Different in different browsers
// Shared for all storage APIs of one domainBrowser throws a special error:
try {
// Trying to save very large data
localStorage.setItem('hugeData', 'x'.repeat(10000000)); // 10 MB
} catch (error) {
// Catch quota exceeded error
if (error.name === 'QuotaExceededError') {
console.log('Cannot save: limit exceeded!');
// Handle the situation
}
}You can check manually:
function canStoreData(key, data) {
try {
localStorage.setItem(key, data);
localStorage.removeItem(key); // Remove test data
return true; // Enough space
} catch (error) {
return false; // No space
}
}
// Check before saving
if (canStoreData('test', largeData)) {
localStorage.setItem('test', largeData);
} else {
console.log('Not enough space!');
}// ❌ Problem — saving large data
const userDocuments = getAllUserDocuments(); // Very large array
localStorage.setItem('documents', JSON.stringify(userDocuments));
// May throw QuotaExceededError!// ❌ Problem — constantly adding data
for (let i = 0; i < 10000; i++) {
localStorage.setItem(`item${i}`, largeData);
// Will exceed limit sooner or later!
}// ✅ Good — check before saving
try {
localStorage.setItem('data', importantData);
} catch (error) {
if (error.name === 'QuotaExceededError') {
// Free space or use different storage
clearOldData();
localStorage.setItem('data', importantData);
}
}// ✅ For large data — IndexedDB
const db = indexedDB.open('largeDataDB');
// ✅ For temporary data — sessionStorage
sessionStorage.setItem('temporary', data);
// ✅ For cache — Cache API
caches.open('myCache');// ❌ Bad — not catching error
localStorage.setItem('big', hugeData); // May break application!
// ✅ Good — always wrap in try-catch
try {
localStorage.setItem('big', hugeData);
} catch (error) {
if (error.name === 'QuotaExceededError') {
// Handle correctly
}
}// ❌ Bad — trying to store large files
localStorage.setItem('userPhotos', JSON.stringify(photos));
// ✅ Better — use File API or IndexedDB
const db = indexedDB.open('photosDB');Understanding localStorage limitations helps write more reliable applications! 💪
Want more articles to prepare for interviews? Subscribe to EasyAdvice, bookmark the site and improve yourself every day 💪