localStorage Quota Exceeded in Svelte
Svelte apps that persist reactive state to localStorage can hit the 5MB browser limit, especially when caching API responses or large form data. Here's a resilient approach.
The Problem
<script>
// This will throw QuotaExceededError if storage is full
$: localStorage.setItem('data', JSON.stringify(largeDataset));
</script>Safe Storage Store
Create a custom Svelte store that handles quota errors and SSR:
// src/lib/stores/localStorage.ts
import { writable } from 'svelte/store';
import { browser } from '$app/environment';
export function persisted<T>(key: string, initial: T) {
const stored = browser ? localStorage.getItem(key) : null;
const data = stored ? JSON.parse(stored) : initial;
const store = writable<T>(data);
if (browser) {
store.subscribe((value) => {
try {
localStorage.setItem(key, JSON.stringify(value));
} catch (e) {
if (e instanceof DOMException && e.name === 'QuotaExceededError') {
console.warn(`Storage full. Clearing old entries.`);
clearOldEntries();
}
}
});
}
return store;
}
function clearOldEntries() {
const keys = Object.keys(localStorage);
// Remove items with timestamps older than 24h
keys.forEach((k) => {
try {
const item = JSON.parse(localStorage.getItem(k) || '');
if (item._ts && Date.now() - item._ts > 86400000) {
localStorage.removeItem(k);
}
} catch { /* not our format, skip */ }
});
}Usage
<script>
import { persisted } from '$lib/stores/localStorage';
const settings = persisted('user-settings', { theme: 'light' });
</script>
<button on:click={() => $settings.theme = 'dark'}>
Toggle theme
</button>Bugsly captures client-side QuotaExceededError events so you can track how often users hit storage limits and which keys are the culprits.
Try Bugsly Free
AI-powered error tracking that explains your bugs. Set up in 2 minutes, free forever for small projects.
Get Started FreeRelated Articles
How to Fix Undefined Variable in Deno
Learn how to diagnose and fix Undefined Variable errors in Deno. Step-by-step guide with code examples.
Read moreTypeScript Application Deployment Checklist
A comprehensive TypeScript deployment checklist covering strict compilation, build optimization, type checking in CI, and runtime validation.
Read moreHow to Fix Undefined Variable in Nuxt
Learn how to diagnose and fix Undefined Variable errors in Nuxt. Step-by-step guide with code examples.
Read moreFix SyntaxError in Kotlin In Production
Step-by-step guide to fix SyntaxError in Kotlin In Production. Includes root cause analysis, code examples, debugging tips, and prevention strategies.
Read more