All posts

Fix localStorage Quota Exceeded Error in Angular

Resolve the QuotaExceededError in Angular apps when localStorage reaches its 5-10MB limit, with strategies for data management.

QuotaExceededError in Angular

When your Angular app writes to localStorage and exceeds the browser's storage limit (typically 5-10MB), you get a DOMException: QuotaExceededError. This often happens silently, breaking app state persistence.

Catching the Error

Always wrap localStorage writes in a try-catch:

@Injectable({ providedIn: 'root' })
export class StorageService {
  set(key: string, value: unknown): boolean {
    try {
      localStorage.setItem(key, JSON.stringify(value));
      return true;
    } catch (e) {
      if (e instanceof DOMException && e.name === 'QuotaExceededError') {
        this.cleanup();
        return false;
      }
      throw e;
    }
  }

  private cleanup(): void {
    // Remove expired or least recently used items
    const keys = Object.keys(localStorage);
    keys
      .filter(k => k.startsWith('cache_'))
      .forEach(k => localStorage.removeItem(k));
  }
}

Prevention Strategies

  1. Use sessionStorage for temporary data — cleared when the tab closes
  2. Implement TTL on cached items:
set(key: string, value: unknown, ttlMs: number): void {
  const item = {
    value,
    expiry: Date.now() + ttlMs
  };
  localStorage.setItem(key, JSON.stringify(item));
}

get(key: string): unknown | null {
  const raw = localStorage.getItem(key);
  if (!raw) return null;
  const item = JSON.parse(raw);
  if (Date.now() > item.expiry) {
    localStorage.removeItem(key);
    return null;
  }
  return item.value;
}
  1. Use IndexedDB for large datasets — no practical size limit

Bugsly captures QuotaExceededError exceptions from the browser, including which key triggered the error and the current storage usage, so you can identify the data that's eating your quota.

Try Bugsly Free

AI-powered error tracking that explains your bugs. Set up in 2 minutes, free forever for small projects.

Get Started Free