14  Client-side storage

Client-side storage in web browsers allows you to store data locally on a user’s device. Here are the main types:

14.1 1. Cookies

The oldest form of client-side storage. Small text files (max ~4KB) sent with every HTTP request to the same domain.

// Set a cookie
document.cookie = "username=John; expires=Thu, 18 Dec 2025 12:00:00 UTC; path=/";

// Read cookies
console.log(document.cookie); // "username=John; theme=dark"

Characteristics: - Size limit: ~4KB per cookie - Sent with every HTTP request (increases bandwidth) - Can set expiration dates - Works across browser tabs/windows - Can be accessed by server-side code

14.2 2. Local Storage

Part of Web Storage API. Stores data with no expiration time.

// Store data
localStorage.setItem('user', JSON.stringify({name: 'John', age: 30}));

// Retrieve data
const user = JSON.parse(localStorage.getItem('user'));

// Remove item
localStorage.removeItem('user');

// Clear all
localStorage.clear();

Characteristics: - Size limit: ~5-10MB (varies by browser) - Persists until explicitly deleted - Synchronous API (can block main thread) - Same-origin only - Stores strings only (need JSON.stringify for objects)

14.3 3. Session Storage

Similar to Local Storage but data expires when the tab closes.

// Same API as localStorage
sessionStorage.setItem('tempData', 'This disappears when tab closes');
const temp = sessionStorage.getItem('tempData');

Characteristics: - Size limit: ~5-10MB - Data isolated per tab/window - Cleared when tab closes - Perfect for temporary form data

14.4 4. IndexedDB

A low-level API for storing large amounts of structured data.

// Open database
const request = indexedDB.open('MyDatabase', 1);

request.onsuccess = (event) => {
    const db = event.target.result;
    
    // Create transaction
    const transaction = db.transaction(['users'], 'readwrite');
    const store = transaction.objectStore('users');
    
    // Add data
    store.add({id: 1, name: 'John', age: 30});
};

Characteristics: - Size limit: Browser-dependent (can be GBs) - Asynchronous API - Supports transactions - Can store complex data types (not just strings) - Good for offline applications

14.5 5. Cache API

Designed for storing HTTP responses for offline use (part of Service Workers).

// Store a response
caches.open('v1').then(cache => {
    cache.add('/api/data.json');
});

// Retrieve from cache
caches.match('/api/data.json').then(response => {
    if (response) {
        // Use cached response
    }
});

Characteristics: - Stores Request/Response pairs - Primarily for Service Worker use - Good for offline-first strategies - Programmatic control over cache

14.6 Comparison Diagram

┌─────────────┬──────────┬───────────┬──────────┬────────────┐
│   Storage   │   Size   │ Lifetime  │ Scope    │ Data Type  │
├─────────────┼──────────┼───────────┼──────────┼────────────┤
│ Cookies     │ ~4KB     │ Settable  │ Domain   │ String     │
│ Local       │ 5-10MB   │ Permanent │ Origin   │ String     │
│ Session     │ 5-10MB   │ Tab/Window│ Origin   │ String     │
│ IndexedDB   │ GBs      │ Permanent │ Origin   │ Any        │
│ Cache API   │ Varies   │ Manual    │ Origin   │ HTTP Resp  │
└─────────────┴──────────┴───────────┴──────────┴────────────┘

14.7 Best Practices

  1. Choose the right storage:

    • User preferences → Local Storage
    • Shopping cart (temporary) → Session Storage
    • Authentication tokens → Cookies (HttpOnly)
    • Large datasets → IndexedDB
    • Offline resources → Cache API
  2. Handle errors:

    try {
        localStorage.setItem('key', 'value');
    } catch (e) {
        // Handle quota exceeded or private browsing
        console.error('Storage failed:', e);
    }
  3. Check availability:

    if (typeof(Storage) !== "undefined") {
        // localStorage/sessionStorage supported
    }
  4. Consider privacy:

    • Users can clear storage
    • Private/incognito modes may limit storage
    • Always have fallbacks

Each storage type serves different use cases. For your radiology AI applications, you might use IndexedDB for storing DICOM metadata locally, Local Storage for user preferences, and Session Storage for temporary image annotations during a viewing session.