SkillByAIOpen interactive version →

Lesson 16 / 30

IndexedDB & storage

Store structured offline data in IndexedDB, responses in the Cache API, and plan for browser storage quotas.

Local storage options

IndexedDB stores structured data in objects/indexes. Cache API is optimized for responses. Choose IndexedDB for app data, Cache API for HTTP responses and static assets.

Store and retrieve from IndexedDB

Use IndexedDB to store app data like todos, notes, or user preferences.

const dbRequest = indexedDB.open('AppDB', 1);
dbRequest.onsuccess = () => {
  const db = dbRequest.result;
  const store = db.transaction('todos', 'readwrite').objectStore('todos');
  store.add({ id: 1, title: 'Learn PWA', completed: false });
};

dbRequest.onupgradeneeded = event => {
  const db = event.target.result;
  db.createObjectStore('todos', { keyPath: 'id' });
};

Output:

App data persisted in IndexedDB for offline access.

A common trap

IndexedDB transactions can be complex. Always handle onsuccess and onerror events, and remember that storage quotas vary by browser.