Of course. Here is a detailed breakdown of IndexedDB, specifically in the context of Safari on iOS. This is a critical topic for web developers, especially those building Progressive Web Apps (PWAs) or complex web applications that need offline capabilities.
1. The Basics: What is IndexedDB?
First, a quick refresher. IndexedDB is a low-level, client-side (in-browser) database API for storing significant amounts of structured data.
- It's a NoSQL Database: It's a key-value store, but the "values" can be complex JavaScript objects. You can create "indexes" on properties within these objects to perform fast searches.
- Asynchronous: All database operations are asynchronous (they don't block the main browser thread), using Promises or older-style
IDBRequest objects. This is crucial for maintaining a responsive user interface.
- Transactional: Operations are wrapped in transactions, ensuring data integrity. If one step in a transaction fails, the entire transaction is rolled back.
- Larger Storage than
localStorage: While localStorage is a simple string-based key-value store limited to about 5-10 MB, IndexedDB can store much more (gigabytes, in theory), making it suitable for applications, not just settings.
2. IndexedDB Support and Behavior on Safari on iOS
Safari on iOS has full technical support for the IndexedDB API (since iOS 8). You can create databases, object stores, indexes, and transactions just as you would on a desktop browser. However, the implementation comes with several critical limitations and quirks that every developer must understand.
3. Key Characteristics & Limitations on iOS Safari
This is the most important part. While the API works, the platform policies around storage dramatically affect how you can use it.
a. The 7-Day Data Eviction Policy (The Biggest "Gotcha")
This is the most infamous and impactful limitation. Due to Apple's Intelligent Tracking Prevention (ITP) initiative, Safari has a strict policy for clearing website data.
- The Rule: If a user does not interact with your website/PWA for 7 days of Safari use, Safari will delete all script-writable storage. This includes IndexedDB,
localStorage, Service Worker registrations, and caches.
- What Counts as "Interaction"? The user must actively use your site in Safari (e.g., visit the URL) or, if it's a PWA, launch it from the home screen. The 7-day clock resets with each interaction.
- Why? Apple's primary motivation is privacy. This policy prevents sites from using client-side storage for long-term cross-site tracking of users. Unfortunately, it also severely impacts legitimate offline applications.
- PWA Exception (No Longer a Full Solution): It was once believed that adding a PWA to the Home Screen would make its storage persistent. This is no longer true. The 7-day cap applies to Home Screen PWAs as well. This was a major blow to the viability of data-heavy PWAs on iOS.
Implication: You cannot treat IndexedDB on iOS as permanent storage. It should be considered a temporary cache or a mechanism for short-term offline access.
b. Storage Quotas and Limits
Safari imposes a storage limit on a per-origin (protocol + domain + port) basis.
c. Private Browsing Mode
In Private Browsing mode on Safari, IndexedDB is either completely unavailable or strictly ephemeral. Any data stored will be wiped the moment the private tab is closed. Your application should detect private mode and disable features that rely on persistent storage.
d. iCloud Backup, Not iCloud Sync
- Backup: Data stored in IndexedDB for a given website is included in a user's full device backup (e.g., an iCloud Backup or a backup to a computer). If the user restores their device from this backup, the IndexedDB data will be restored.
- Sync: IndexedDB data is not automatically synced across a user's devices via iCloud. If a user saves data in your web app on their iPhone, it will not appear on their iPad unless you implement your own server-side synchronization logic.
4. Best Practices for Developers Targeting iOS Safari
Given these constraints, here's how to approach using IndexedDB on iOS:
-
Treat It as a Cache, Not a Database of Record: This is the golden rule. The single source of truth for critical user data must be a remote server. Use IndexedDB to provide offline access and improve performance, but always have a strategy to sync data to and from your server.
-
Implement a Robust Syncing Strategy: Your application logic should be built around synchronization. When online, push local changes to the server. When the app loads, pull the latest data from the server to hydrate the local IndexedDB.
-
Handle Errors Gracefully: Your code must anticipate that a write operation can fail. Wrap your IndexedDB transactions in try...catch blocks (with async/await) and specifically look for QuotaExceededError. Inform the user if storage is full.
-
Use a Wrapper Library: The native IndexedDB API is verbose and complex. Libraries like idb (by Jake Archibald) or Dexie.js provide modern, Promise-based wrappers that make working with IndexedDB much simpler and less error-prone.
- Dexie.js Example:
// npm install dexie
import Dexie from 'dexie';
const db = new Dexie('myOfflineApp');
db.version(1).stores({
friends: '++id, name, age' // Primary key ++id, index on name and age
});
async function addFriend() {
try {
await db.friends.add({ name: 'Alice', age: 30 });
} catch (error) {
console.error("Failed to add friend: ", error);
}
}
-
Inform Your Users (Especially for PWAs): If your PWA relies heavily on offline data, you might need to educate users. A small message explaining that they should use the app periodically to prevent data loss can help manage expectations.
Summary Table
| Feature / Behavior | Safari on iOS Implementation | Developer Takeaway |
|---|
| API Support | Full | The API itself works as expected. |
| Data Persistence | Ephemeral (cleared after 7 days of non-use) | Do not treat as permanent storage. It's a cache. |
| Storage Quota | Dynamic (e.g., 50% of free disk, with a cap) | Monitor usage with navigator.storage.estimate() and handle QuotaExceededError. |
| User Prompts | Yes, when storage usage grows large. | Design UX to handle potential interruptions for storage permission. |
| Private Mode | Disabled or wiped on close. | Detect private mode and disable storage-dependent features. |
| iCloud Sync | No (data is device-local) | Implement your own server-side sync for multi-device support. |
| Device Backup | Yes (data is included in iCloud/local backups) | Data can be recovered if a user restores their device from a backup. |