Svelte Store Adapter

Storagefy's Svelte adapter provides seamless integration between Svelte's reactive stores and your choice of persistent storage backend. This adapter works with Svelte's standard store contract, allowing you to easily persist and synchronize writable stores across page reloads and browser sessions.

1. Basic Usage

The Svelte adapter works with Svelte's built-in stores, enabling straightforward state persistence with minimal configuration:

        
import { writable } from 'svelte/store';
import { startStoragefy, getSvelteAdapter } from "storagefy";

// Initialize the storage backend
startStoragefy({
  dbName: "my-svelte-app",
  adapter: "indexedDB", // or "localStorage" or "sessionStorage"
  encrypt: true,
  channelName: "svelte-sync",  // the channel the tabs talk on…
  enableSyncTabs: true   // …and this storage tells them about its writes
});

// Create a Svelte store
const themeStore = writable({ mode: 'light', accent: 'blue' });

// Get the Svelte adapter
const { setInStorage, getFromStorage } = getSvelteAdapter();

// Load existing data first
await getFromStorage(themeStore, "theme-settings");

// Then set up persistence
await setInStorage(themeStore, "theme-settings", {
  timeout: 2592000000, // 30 days expiration
  ignoreKeys: ["tempTheme", "user.password"],
  syncTabs: true
});
        
      

2. Using the Helper Function

For a more concise approach, use the setSvelteStorage helper function:

        
import { writable } from 'svelte/store';
import { startStoragefy, setSvelteStorage } from "storagefy";

// Initialize storage backend
startStoragefy({
  dbName: "my-svelte-app",
  adapter: "localStorage"
});

// Create a Svelte store
const userPrefs = writable({
  notifications: true,
  darkMode: false
});

// Use the helper function to load and persist in one step
await setSvelteStorage(userPrefs, "user-preferences", {
  timeout: 86400000, // 24 hours
  ignoreKeys: ["tempPrefs", "user.password"],
  syncTabs: true
});
        
      

3. Test It

4. Advanced Configuration

You can directly instantiate the SvelteAdapter class for more advanced control:

        
import { writable } from 'svelte/store';
import { SvelteAdapter, IndexedDBAdapter } from "storagefy";

// Create storage adapter instance
const storageAdapter = new IndexedDBAdapter({ 
  dbName: "svelte-app",
  encrypt: true
});

// Create Svelte adapter with the storage adapter
const svelteAdapter = new SvelteAdapter(storageAdapter);

// Create a Svelte store
const cartStore = writable({ items: [], total: 0 });

// Hydrate store from storage
await svelteAdapter.getFromStorage(cartStore, "shopping-cart");

// Set up persistence
await svelteAdapter.setInStorage(cartStore, "shopping-cart", {
  ignoreKeys: ["pendingActions", "user.password"],
  timeout: 3600000 // 1 hour
});
        
      

5. Configuration Options

The setInStorage method accepts the following options:

Options Object

  • ignoreKeys: Array of store property keys to exclude from persistence

    Use this for sensitive data or temporary state that doesn't need persistence. Supports both flat keys and dot-notation paths for nested properties at any depth.

            
    // Flat keys — exclude top-level properties
    ignoreKeys: ["password", "token"]
    
    // Nested keys — exclude properties inside objects (dot notation)
    ignoreKeys: ["auth.password", "auth.token"]
    
    // Deeply nested — works at any depth
    ignoreKeys: ["config.api.secretKey", "config.api.privateToken"]
    
    // Mixed — combine flat and nested freely
    ignoreKeys: [
      "sessionToken",           // flat
      "auth.password",          // nested
      "config.api.secretKey"    // deeply nested
    ]
            
          

    Ignored keys are set to undefined in the persisted value. Sibling and parent keys are never affected — only the exact path specified is omitted.

  • timeout: expiration of the stored state, in milliseconds

    Counted again after each write. It is not a time limit of the operation: after it, the stored state is gone (the store keeps what it holds in memory). If not set, the state is kept until removed. A change of an ignoreKeys key alone writes nothing, so it does not renew it.

            
    timeout: 3600000  // expires after 1 hour
    timeout: 86400000 // expires after 24 hours
    timeout: 300000   // expires after 5 minutes
            
          
  • syncTabs: Boolean flag to enable cross-tab synchronization

    When true, changes made in one browser tab will be reflected in all others in real time. Requires channelName and enableSyncTabs: true on the storage adapter — without both, nothing is synced and nothing warns you. Only a state newer than the store's is applied — every write has a revision, so an older state never undoes a newer change; two tabs changing the store at once end with the same state, the one stored (with localStorage, the tab of the newer change writes it again). With IndexedDB and localStorage, a tab shown again reads storage again.

            
    // Enable tab sync
    startStoragefy({
      dbName: "my-app",
      channelName: "storagefy-sync", // 1. the channel the tabs talk on
      enableSyncTabs: true            // 2. this storage tells the other tabs about its writes
    });
    
    await setInStorage(myStore, "user", {
      syncTabs: true
    });
            
          
  • onError: called with an Error when the state could not be saved

    The storage is full, the encryption failed, or a change from another tab could not be read — the store keeps working. getFromStorage(store, key, { onError }) also tells a stored state that is there but cannot be read (another password, changed by hand). A mistake of the app throws instead, so it shows while developing: setInStorage rejects when its first write threw (a storage adapter of your own whose set throws, a state that cannot be copied).

            
    await setInStorage(myStore, "user", {
      onError: (error) => reportToMyApp(error) // error.cause holds what failed
    });
            
          

6. Store Compatibility

The Svelte adapter works with stores that follow Svelte's store contract:

  • Writable stores: Full read/write support with subscribe, set, and update methods
  • Custom stores: Compatible as long as they implement the subscribe and set methods
        
// Works with standard writable stores
import { writable } from 'svelte/store';
const standardStore = writable({ count: 0 });

// Works with custom stores that implement the store contract
function createCustomStore(initial) {
  const { subscribe, set, update } = writable(initial);
  
  return {
    subscribe,
    set,
    increment: () => update(n => ({ count: n.count + 1 })),
    reset: () => set({ count: 0 })
  };
}

const customStore = createCustomStore({ count: 0 });
await setSvelteStorage(customStore, "counter");
        
      

7. Cross-Tab Synchronization

When syncTabs: true is set, your Svelte stores will automatically stay in sync across browser tabs:

        
// In Tab 1
const sharedStore = writable({ value: 'initial' });
await setSvelteStorage(sharedStore, "shared-data", { syncTabs: true });

// Later in Tab 1
sharedStore.update(state => ({ ...state, value: 'updated' }));

// In Tab 2 (automatically updated)
// sharedStore value will now be { value: 'updated' }
        
      

This feature uses the BroadcastChannel API to synchronize changes across tabs or windows. The storage adapter needs channelName andenableSyncTabs: true (in startStoragefy or its constructor). Up to 1.2.x Svelte stores did not sync — fixed in 1.3.0.

8. API Reference

getSvelteAdapter([options])

Returns a configured Svelte adapter instance. Options include:

  • adapterParams: Configuration for the underlying storage adapter

Returns: { setInStorage, getFromStorage } methods

setSvelteStorage(store, key, [options])

Helper function that internally calls getFromStorage followed by setInStorage.

  • store: Svelte writable store instance
  • key: Storage key string
  • options: Configuration options (ignoreKeys, timeout, syncTabs, onError)

Returns: Promise resolving to true on success

SvelteAdapter Class Methods

  • setInStorage(store, key, options): Persists store state and sets up subscription
  • getFromStorage(store, key): Loads persisted state into store — { onError } tells a stored state that cannot be read
  • flush([key]): Makes sure the state is in storage — what the store holds now is written, unless it is stored already, and the promise resolves once its writes are done: true stored,false a write was not saved (onError says why). It never rejects for a write. Without key, every store of the adapter; a key no store is kept under rejects. Call it before something that must not lose a change, such as signing out
  • destroy(key): Stops keeping the store of key — no more writes, no more changes from the other tabs. What is stored stays
  • destroyAll(): Stops keeping every store of the adapter. The storage adapter goes on
  • What the store holds is written and loaded back as it was — any JSON value (an object, an array, a number, a string, a boolean). A state set to null or undefined removes the stored key (a store emptied on sign-out is not loaded back)

9. Best Practices

  • Always call getFromStorage before setInStorage to hydrate your store with existing data
  • Before signing out (or anything that must not lose a change), clear the store and await flush(key): once it resolves, the cleared state is in storage and the page may close
  • For simplicity, use the setSvelteStorage helper which handles this sequence automatically
  • Use appropriate timeout values based on your data's volatility (longer for preferences, shorter for temporary state)
  • Call destroy(key) on the Svelte adapter when you no longer keep a store, anddestroy() on the storage adapter when you stop using it (it releases its timer, channel and connection)
  • For larger applications, consider a more structured approach to key naming, such as prefixing with module names
  • Be thoughtful about what you persist - don't store large objects unnecessarily