A Svelte reactive rune that keep its value through pages and reloads
npm install @macfja/svelte-persistent-runesA Svelte reactive rune that keep its value through pages and reloads
!GitHub Repo stars
!NPM bundle size
!Download per week
!License
!NPM version

[D E M O ]
With NPM
``sh`
npm install --save-dev @macfja/svelte-persistent-runesor
yarn add --save-dev @macfja/svelte-persistent-runesor
pnpm add --save-dev @macfja/svelte-persistent-runesor
deno install --dev npm:@macfja/svelte-persistent-runes
Update your ./svelte.config.js to add a new preprocessor:`diff`
import adapter from '@sveltejs/adapter-auto';
+import persist from "@macfja/svelte-persistent-runes/preprocessor"
const config = {
+ preprocess: [persist()],
kit: {
adapter: adapter()
}
};
export default config;
Replace your $state with $persist:`diff`
This library have 2 parts:
- A preprocessor to add the $persist rune (and optionally a Vite plugin).
- A set of configuration to persist your data.
You MUST add the preprocessor to use $persist.svelte.config.js
It's as simple as to add it in your Svelte configuration () with the import of @macfja/svelte-persistent-runes/plugins
./svelte.config.js
`js
import adapter from '@sveltejs/adapter-auto';
import { vitePreprocess } from '@sveltejs/vite-plugin-svelte';
import { persistPreprocessor } from "@macfja/svelte-persistent-runes/plugins"
/* @type {import('@sveltejs/kit').Config} /
const config = {
preprocess: [vitePreprocess(), persistPreprocessor()],
kit: {
adapter: adapter()
}
};
export default config;
`
> [!IMPORTANT]
> If you are using .svelte.js/.svelte.ts file you need to also add a Vite plugin:`
> ./vite.config.ts
>
> ts`
> import { sveltekit } from '@sveltejs/kit/vite';
> import { defineConfig } from 'vite';
> import { persistPlugin as persist } from "@macfja/svelte-persistent-runes/plugins";
>
> export default defineConfig({
> plugins: [persist(), sveltekit()]
> });
>
>
>
Now that the preprocessor is added, you can use the $persist rune instead of the $state rune.
./src/anywhere/component.svelte
`html`
{count}
./src/anywhere/data.svelte.ts
`tsHello ${this.name}
import "@macfja/svelte-persistent-runes"
export class Person {
name = $persist('John', 'user-name')
age = $persist(33, 'user-age')
greet(): string {
return ;Happy birthday ${this.name}!
}
birthday(): string {
this.age += 1;
return `
}
}
export const currentUser = new Person()
> [!IMPORTANT]
> You need to import import "@macfja/svelte-persistent-runes" to prevent Typescript to complain about the unknown function $persist./src/app.d.ts
>
> ---
>
> You can add this import in an ambient Typescript Module (like in SvelteKit), and you won't need to import it in every file
`tsundefined
type PersistentRunesOptions = {
/**
* Convert the source data into its string representation
* @param input The source data
* @return The string representation of data
*/
serialize
/**
* Convert back the string representation into the source data
* @param input The string representation of the date
* @return The new data based on its string representation
*/
deserialize
/**
* Write data into the store
* @param key The storage key to write
* @param value The data to write
*/
storageWrite(key: string, value: string): void;
/**
* Read data from the storage
* @param key The storage key to read
* @returns The data or if the data don't exist in the storage
*/
storageRead(key: string): string | undefined;
};
/**
* A reactive state, that can restore its state upon page reload
* @param initial The initial value of the state
* @param key The storage key of the state. Must be unique in your application
* @param options The persistence options (how and where)
*/
declare function $persist
`
You can customize how and where the state value is persisted.
The $persist runes take a third (and optional) parameter of type PersistentRunesOption.
The options consist of 2 main part: the serializer and the storage. It can be defined as a plain object or as the result of the buildOptions (impoerted from @macfja/svelte-persistent-runes/options)
`tsPersistentRunesOptions
/**
* Create a from a serializer and a storageundefined
* @param serializer The serializer to use (if then JsonSerializer will be used)undefined
* @param storage The storage to use (if then BrowserLocalStorage will be used)`
*/
declare function buildOptions(
serializer: PersistentRunesSerializer | undefined,
storage: PersistentRunesStorage | undefined
): PersistentRunesOptions;
#### The serializer
The serializer part of the option are:
- serialize: This function is responsible for converting the original type into a stringdeserialize
- : This function is responsible to convert back a string to the original type
The library have several built-in serializer:
- JsonSerializerFactory: factory to create a JSON based serializerJsonSerializer
- : A basic JSON serializer (no replacer, nor reviver)DevalueSerializerFactory
- : factory to create a [Devalue] based serializerDevalueSerializer
- : A basic [Devalue] serializer (no reducers, nor revivers)ESSerializerSerializerFactory
- : factory to create a [ESSerializer] based serializerESSerializerSerializer
- : A basic [ESSerializer] serializer (no SerializeOptions, nor classes)MacfjaSerializerFactory
- : factory to create a [@macfja/serializer] based serializerMacfjaSerializer
- : A basic [@macfja/serializer] serializer (no additional classes mapping)SuperJsonSerializer
- : A [superjson] serializerNextJsonSerializerFactory
- : factory to create a [next-json] based serializerNextJsonSerializerFactory
- : A basic [next-json] serializer (no options, nor replacers, nor revivers)PhpSerializeSerializerFactory
- : factory to create a [php-serialize] based serializerPhpSerializeSerializer
- : A basic [php-serialize] serializer (no options)SerializeAnythingSerializerFactory
- : factory to create a [serialize-anything] based serializerSerializeAnythingSerializer
- : A basic [serialize-anything] serializer (no options)
[ESSerializer]: https://www.npmjs.com/package/esserializer
[Devalue]: https://www.npmjs.com/package/devalue
[@macfja/serializer]: https://www.npmjs.com/package/@macfja/serializer
[superjson]: https://www.npmjs.com/package/superjson
[next-json]: https://www.npmjs.com/package/next-json
[php-serialize]: https://www.npmjs.com/package/php-serialize
[serialize-anything]: https://www.npmjs.com/package/serialize-anything
#### The storage
The storage part of the option are:
- storageWrite: This function is responsible to write data into the storagestorageRead
- : This function is responsible to read data from the storage
The library have several built-in storage:
- BrowserCookieStorageFactory: factory to create a Cookie based storage (DOM API, browser only)BrowserCookieStorage
- : A basic Cookie storage (no particular options, except for samesite: Strict)BrowserLocalStorage
- : a browser localStorage storage (DOM API, browser only)BrowserSessionStorage
- : a browser sessionStorage storage (DOM API, browser only)addEncryptionStorage
- : a wrapper function to add AES [GCM encryption] on stored data
[GCM encryption]: https://en.wikipedia.org/wiki/Galois/Counter_Mode
#### Example
`html`
{count}
`html``
{count}