Implement a custom storage
mainStorageInterface to create your own custom storage mechanism.repository·main·Indexed 42 days ago
https://github.com/macfja/svelte-persistent-storeA Svelte store utility (v2.4.2) that persists values across page reloads and sessions. It provides built-in support for localStorage, sessionStorage, cookies, IndexedDB, and chrome.storage, as well as tools for custom storage implementations, AES-256-GCM encryption via GCMEncryption, and configurable serialization.
StorageInterface to create your own custom storage mechanism.Install the package using npm to add persistent Svelte stores to your project.
npm install @macfja/svelte-persistent-storeTo use a custom storage mechanism, implement the StorageInterface<T>.
If you want your store to react to changes made to the storage outside of the current Svelte store instance, you must also implement SelfUpdateStorageInterface<T> by adding addListener and removeListener methods.
StorageInterface Requirements:
getValue(key: string): T | null: Must be synchronous. Returns null if the key doesn't exist.setValue(key: string, value: T): void: Saves the value.deleteValue(key: string): void: Removes the value.1.3.0 may not be deserializable in version 2.* due to changes in data serialization. Specifically, if your persisted store contains Javascript classes, you may not be able to retrieve the data by default after upgrading. Refer to the documentation on 'How To Change Serialization' for details.The persist function takes an existing Svelte writable store, a storage implementation, and a unique key. It returns a PersistentStore<T> which includes a delete method to clear the persisted data.
import { persist, createLocalStorage } from "@macfja/svelte-persistent-store"
import { writable } from "svelte/store"
// Wraps a writable store with LocalStorage persistence
let name = persist(writable("John"), createLocalStorage(), "name")
$name = "Jeanne Doe"
// On page reload, $name will still be 'Jeanne Doe'You can use the specialized writable export from @macfja/svelte-persistent-store to create a store that is automatically persisted in localStorage with a specific key.
import { writable } from "@macfja/svelte-persistent-store"
// Create a writable store, persisted in browser LocalStorage, with the key `name`
let name = writable("name", "John")
$name = "Jeanne Doe"
// On page reload, $name will still be 'Jeanne Doe'If you want data to persist only for the duration of the browser session (cleared when the tab/window is closed), use persistBrowserSession.
import { persistBrowserSession } from "@macfja/svelte-persistent-store"
import { writable } from "svelte/store"
let title = persistBrowserSession(writable("Unsaved"), "document-name")
$title = "My Document"
// On page reload, $title will still be 'My Document'The library provides 6 built-in storage implementations. You can choose the one that best fits your use case:
createLocalStorage(): Uses window.localStorage.createSessionStorage(): Uses window.sessionStorage.createCookieStorage(): Uses document.cookie.createIndexedDBStorage(): Uses window.indexedDB.createChromeStorage(): Uses chrome.storage.createEncryptedStorage(): A wrapper that encrypts data and keys (requires wrapping another storage).Returns a StorageInterface that uses window.sessionStorage.
listenExternalChanges: If set to true, the store will listen for the storage event to update itself when sessionStorage is modified.import { createSessionStorage } from 'svelte-persistent-store';
const storage = createSessionStorage(true);By default, the library uses @macfja/serializer. You can override the global serialization and deserialization logic using setSerialization. This is useful if you need to use a different format (like YAML) or custom logic for transforming data to and from strings.
When setting custom serialization, you can also provide a function to handle class registration for the serializer.
import { setSerialization } from 'svelte-persistent-store';
setSerialization(
(data) => JSON.stringify(data), // Custom serializer
(input) => JSON.parse(input), // Custom deserializer
(classConstructor) => { /* custom class registration logic */ }
);Use the persist function to wrap an existing Svelte Writable store. This creates a PersistentStore that automatically synchronizes its value with the provided StorageInterface using a specific key.
When a PersistentStore is created, it immediately attempts to load the initial value from storage. If the storage supports listeners (SelfUpdateStorageInterface), the store will also react to external changes made to that storage key.
import { writable } from 'svelte/store';
import { persist, createLocalStorage } from 'svelte-persistent-store';
const myStore = writable(0);
const persistentStore = persist(myStore, createLocalStorage(), 'my-key');
// persistentStore is now a PersistentStore<number>
// It has all Writable methods plus .delete()If you are running your Svelte application in an environment where certain storages (like localStorage) are unavailable (e.g., during Server-Side Rendering), the library will emit warnings. You can suppress these warnings by calling disableWarnings().
import { disableWarnings } from 'svelte-persistent-store';
disableWarnings();