Почему IndexedDB?
Данная страница находится в процессе перевода. Временно доступна английская версия.
Form Guardian uses IndexedDB as its storage backend. This guide explains why IndexedDB is the best choice for form autosave functionality.
The Problem with localStorage
Many developers initially try to use localStorage for form drafts, but it has significant limitations:
Storage Size Limits
// ❌ localStorage has strict size limits
localStorage.setItem('form-draft', JSON.stringify(largeFormData));
// Error: QuotaExceededError - usually 5-10MB limit
Problems:
- Most browsers limit localStorage to 5-10MB
- Large forms or multiple drafts quickly hit the limit
- No way to request more storage
- Errors are silent - data just fails to save
Synchronous API
// ❌ localStorage is synchronous - blocks the main thread
const data = localStorage.getItem('form-draft'); // Blocks UI
const parsed = JSON.parse(data);
Problems:
- Synchronous operations block the browser's main thread
- Can cause UI freezes with large data
- Poor performance on slower devices
No Structured Data
// ❌ localStorage only stores strings
localStorage.setItem('draft', JSON.stringify({ name: 'John', email: 'john@example.com' }));
// Everything must be serialized/deserialized
Problems:
- Must serialize/deserialize all data
- No native support for complex objects
- Performance overhead for large objects
Why IndexedDB?
IndexedDB solves all these problems:
✅ Large Storage Capacity
// ✅ IndexedDB can store much more data
// Most browsers allow 50% of available disk space
// Typically 1GB+ available
Benefits:
- 50% of available disk space (typically 1GB+)
- Can store multiple large forms
- No quota errors for typical use cases
✅ Asynchronous API
// ✅ IndexedDB is asynchronous - doesn't block UI
const request = indexedDB.open('form-guardian');
request.onsuccess = (event) => {
const db = event.target.result;
// Non-blocking operation
};
Benefits:
- Non-blocking operations
- Better performance
- Smooth UI even with large data
✅ Structured Data Storage
// ✅ IndexedDB stores structured data natively
const transaction = db.transaction(['drafts'], 'readwrite');
const store = transaction.objectStore('drafts');
store.put({ formId: 'contact', values: { name: 'John', email: 'john@example.com' } });
Benefits:
- Native object storage
- No serialization overhead
- Better performance
✅ Advanced Querying
// ✅ IndexedDB supports indexes and queries
const index = store.index('formId');
const request = index.getAll('contact-form');
Benefits:
- Query by form ID
- Filter expired drafts
- Efficient data retrieval
Real-World Comparison
localStorage Example
// ❌ localStorage approach
function saveDraft(formId, data) {
try {
const key = `draft-${formId}`;
localStorage.setItem(key, JSON.stringify(data));
return true;
} catch (e) {
// Silent failure - user loses data
console.error('Failed to save:', e);
return false;
}
}
// Problems:
// - 5-10MB limit
// - Synchronous (blocks UI)
// - No error recovery
// - Must serialize everything
IndexedDB Example (Form Guardian)
// ✅ IndexedDB approach (what Form Guardian uses)
async function saveDraft(formId, data) {
const db = await openDatabase();
const transaction = db.transaction(['drafts'], 'readwrite');
const store = transaction.objectStore('drafts');
await store.put({
formId,
values: data,
updatedAt: Date.now(),
});
// Benefits:
// - 1GB+ storage
// - Asynchronous (non-blocking)
// - Native object storage
// - Better error handling
}
Performance Comparison
| Operation | localStorage | IndexedDB |
|---|---|---|
| Save 1MB data | ~50ms (blocks UI) | ~10ms (async) |
| Load 1MB data | ~30ms (blocks UI) | ~8ms (async) |
| Storage limit | 5-10MB | 1GB+ |
| Query by key | O(n) scan | O(1) index |
Browser Support
IndexedDB is supported in:
- ✅ Chrome/Edge (all versions)
- ✅ Firefox (all versions)
- ✅ Safari (all versions)
- ✅ Mobile browsers (iOS Safari, Chrome Mobile)
Note: For very old browsers (IE 10-), Form Guardian includes fallback support.
Form Guardian's Implementation
Form Guardian uses IndexedDB efficiently:
// Form Guardian automatically:
// 1. Opens database connection
// 2. Creates object stores if needed
// 3. Handles errors gracefully
// 4. Provides simple API
import { attachFormAutosave } from '@form-guardian/dom';
const autosave = attachFormAutosave({
formId: 'my-form',
root: form,
// IndexedDB is used automatically - no configuration needed!
});
Best Practices
- Let Form Guardian handle IndexedDB - It's optimized and tested
- Use appropriate TTL - Clean up old drafts automatically
- Clear drafts after submission - Prevent storage bloat
- Trust the storage - IndexedDB is reliable and persistent