Persistence helpers
This page covers the persistence-specific helpers, option types, and adapter contracts used by createPersistencePlugin().
Persistence adapter contract
PersistenceAdapter is the shape the plugin expects for storage backends.
getItem(key)reads a stored snapshot and returnsnullwhen missing.setItem(key, value)writes the encoded snapshot.removeItem(key)deletes a stored snapshot.clear?()andkeys?()are optional convenience methods for richer backends.
Built-in adapters
createLocalStorageAdapter(storage?)for browserlocalStorageor a custom storage-like objectcreateSessionStorageAdapter(storage?)for browsersessionStorageor a custom storage-like objectcreateMemoryStorageAdapter()for tests and server-side fallback storagecreateIndexedDbAdapter(database)for async databases that already exposeget,set,delete,clear, andkeys
The browser adapters gracefully handle missing storage and quota errors.
Compression helpers
createLzStringCompression() returns a PersistCompression implementation that prefixes encoded values with lz: and decodes them with lz-string.
Use compression when persisted state is large enough to justify the encoding overhead.
PersistOptions
PersistOptions configures how a store is hydrated and flushed.
Important fields:
adapter— required storage backendversion— required finite version numberkey— optional storage key, defaults to the store idcompression— optional compressor/decompressorserialize— optional custom serializerdeserialize— optional custom deserializermigrate— optional version migration function used by the built-in deserializer path
Example:
import {
createMemoryStorageAdapter,
createPersistencePlugin,
createStateManager,
defineStore
} from '@selfagency/stately';
const manager = createStateManager().use(createPersistencePlugin());
export const usePreferencesStore = defineStore('preferences', {
state: () => ({ theme: 'dark', compact: false }),
persist: {
adapter: createMemoryStorageAdapter(),
version: 1,
key: 'stately:preferences'
}
});PersistController
The plugin exposes a controller on each persisted store as $persist.
readyresolves after the initial rehydration attemptflush()writes the current snapshot immediatelyrehydrate()re-reads persisted state on demandclear()removes the stored snapshotpause()andresume()temporarily disable automatic writes
This is useful when you need to batch updates or recover from a storage failure without tearing down the store.
Public persistence types
The persistence module also exports PersistEnvelope and PersistCompression so consumers can type custom serializers, migrations, or storage bridges without guessing at the shape.