Pinia 08 ๐ Plugins & State Persistence โ Extending stores with custom Pinia plugins and persisting state with pinia-plugin-persistedstate
While Pinia’s built-in state management is robust, real-world applications often require cross-cutting functionality that applies to every store. You might need to inject a global API client, add custom logging to every action, or ensure that specific pieces of state survive a browser refresh. Instead of duplicating this logic in every store definition, Pinia provides a powerful plugin system. Plugins allow you to augment stores with new properties, intercept every action, and hook into the store lifecycle globally.
State persistence is the most common use case for the plugin system. By default, Pinia state is stored in memory; when a user refreshes the page, the state is wiped clean. While you could manually write to localStorage in every action, a more scalable approach is to use a dedicated persistence plugin. The community-standard pinia-plugin-persistedstate automates this process, allowing you to declare which stores should be persistent with a single configuration property.
This chapter details how to create and install custom plugins to extend Pinia’s capabilities and how to implement professional-grade state persistence. We will explore the plugin API, the injection of global properties like routers or telemetry trackers, and the configuration of pinia-plugin-persistedstate for granular control over what gets saved, where it is saved, and how it is hydrated during application startup.
Key point: Pinia plugins provide a centralized way to augment all stores with global properties and side effects, while persistence plugins automate the synchronization between in-memory state and browser storage.
Why exists
The Cross-Cutting Concern Problem. In a large application with fifty stores, you don’t want to manually import and inject a “Logging Service” into each one. Plugins exist to solve this “scattering” problem by allowing you to define a logic once (at the Pinia instance level) and have it automatically applied to every store, present and future.
The Volatile State Problem. Browsers are inherently ephemeral environments. A simple page refresh can clear a shopping cart or a user’s theme preference. Manual persistence logic is prone to “stale data” bugs. Automatic persistence plugins exist to ensure that the “Source of Truth” in memory is always seamlessly mirrored to a persistent medium like localStorage or sessionStorage.
The Boilerplate Problem. If every store needs access to the application router or a specific translation function, adding that to every defineStore setup function creates significant noise. Plugins allow you to “augment” the store instance, making these global utilities available via this (in Option stores) or directly on the store object, keeping your business logic clean.
The Global Audit Problem. For security or debugging, you may need to track every single state change across the entire application. Writing a $subscribe listener inside every store is inefficient. A plugin allows you to attach a single global listener that intercepts every mutation across every domain, providing a centralized audit trail.
The Hydration Problem. When loading state from localStorage, you often face issues with data types. JSON does not natively support Date objects or Map structures. Persistence plugins exist to provide a framework for “Serializers,” ensuring that when data is pulled from disk, it is correctly “re-hydrated” into the complex JavaScript types your store expects.
a. Anatomy of a Pinia Plugin
A Pinia plugin is a function that receives a single object containing the pinia instance, the Vue app, the specific store being extended, and the options passed to defineStore. Because this function runs once for every store created, it is the perfect place to inject shared logic.
export function myPiniaPlugin({ store }) {
// Add a static property to every store
store.env = 'production';
// Any property returned will be available on the store
return {
hello: 'world',
// You can also add reactive state
isSyncing: ref(false)
};
}
// Installation
const pinia = createPinia();
pinia.use(myPiniaPlugin);
When you return an object from a plugin, Pinia automatically makes those properties available on the store. However, if you are adding external instances (like a Router), you should use markRaw to prevent Pinia from trying to make the router itself reactive, which can cause significant performance degradation.
Plugins can also use store-specific methods like $subscribe or $onAction. This allows you to create global loggers or synchronization engines that react to any change in the application without requiring the developer to remember to add a listener to their new store.
b. Using pinia-plugin-persistedstate
The most popular way to handle persistence is through the pinia-plugin-persistedstate library. Once installed and registered with pinia.use(), it adds a new persist option to your store definitions. In its simplest form, setting persist: true will save the entire store state to localStorage using the store’s ID as the key.
import { defineStore } from 'pinia';
export const useUserStore = defineStore('user', {
state: () => ({
name: 'Alice',
theme: 'dark'
}),
persist: true, // Automatically saves to localStorage
});
The plugin is highly configurable. You can specify a custom key (to avoid naming collisions), change the storage type (e.g., using sessionStorage for sensitive data), or even use a custom storage backend like localForage. This flexibility is essential for applications that need to balance performance with data longevity.
Granular persistence is often required. You might want to persist a user’s “Theme” but not their “Current Search Query.” The paths option allows you to define an array of strings representing the specific keys in your state that should be saved to disk, leaving the rest volatile.
c. Advanced Plugin Logic & SSR
When writing custom plugins, you have access to the options passed to defineStore. This allows you to create “Custom Options” that your plugin reads to change its behavior. For example, you could create an audit: true option that, when detected by your plugin, triggers a remote logging event whenever that specific store is modified.
// Plugin logic
pinia.use(({ options, store }) => {
if (options.audit) {
store.$subscribe(() => {
console.log(`Auditing ${store.$id}...`);
});
}
});
// Store definition
defineStore('secure', {
state: () => ({ secret: '123' }),
audit: true // The plugin sees this custom flag
});
Server-Side Rendering (SSR) adds a layer of complexity to plugins and persistence. Because the server does not have access to window.localStorage, a persistence plugin must be carefully configured to avoid “Hydration Mismatches.” The standard practice is to only trigger the reading of persistent state once the application has mounted on the client side.
Finally, plugins can be used to synchronize stores with external state sources, such as a WebSocket or a Browser Extension’s background script. By using the plugin architecture, you can bridge the gap between Pinia and external APIs, ensuring that your store remains the centralized “Source of Truth” while still staying in sync with the outside world.
Complete Example Session
// ============================================
// PART 1: THE CUSTOM LOGGING PLUGIN
// ============================================
import { markRaw } from 'vue';
function ActionLoggerPlugin({ store }) {
store.$onAction(({ name, args, after, onError }) => {
console.log(`[๐ Action] ${store.$id}.${name}`, args);
after((result) => console.log(`[โ
Success]`, result));
onError((error) => console.warn(`[โ Error]`, error));
});
}
// ============================================
// PART 2: PERSISTENCE INSTALLATION
// ============================================
import { createPinia } from 'pinia';
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate';
const pinia = createPinia();
pinia.use(ActionLoggerPlugin);
pinia.use(piniaPluginPersistedstate);
// ============================================
// PART 3: SIMPLE PERSISTED STORE
// ============================================
export const useThemeStore = defineStore('theme', {
state: () => ({ mode: 'light' }),
persist: true,
});
// ============================================
// PART 4: ADVANCED PERSISTENCE (PATHS & STORAGE)
// ============================================
export const useAuthStore = defineStore('auth', {
state: () => ({
token: null,
tempCode: null,
user: { id: 1, name: 'Bob' }
}),
persist: {
key: 'my-auth-app',
storage: sessionStorage, // Use session instead of local
paths: ['token', 'user.name'], // Only save these specific fields
},
});
// ============================================
// PART 5: CUSTOM SERIALIZER (Handling Dates)
// ============================================
export const useEventStore = defineStore('events', {
state: () => ({ date: new Date() }),
persist: {
serializer: {
deserialize: (value) => ({ date: new Date(JSON.parse(value).date) }),
serialize: JSON.stringify,
},
},
});
// ============================================
// PART 6: AUGMENTING STORES WITH ROUTER
// ============================================
import router from './router';
pinia.use(({ store }) => {
store.router = markRaw(router);
});
// ============================================
// PART 7: USING INJECTED ROUTER IN ACTION
// ============================================
// Inside an action: this.router.push('/home');
// ============================================
// PART 8: CONDITIONAL PLUGIN LOGIC
// ============================================
pinia.use(({ options, store }) => {
if (options.debounceSaving) {
// Logic to throttle save events
}
});
// ============================================
// PART 9: REHYDRATION HOOKS
// ============================================
export const useCartStore = defineStore('cart', {
state: () => ({ items: [] }),
persist: {
afterRestore: (ctx) => {
console.log('Cart re-synced from disk!');
}
}
});
// ============================================
// PART 10: CLEARING PERSISTED STATE
// ============================================
// To clear: localStorage.removeItem('theme');
The sequence above demonstrates the creation of custom logging plugins, the configuration of complex persistence logic (paths, serializers, custom storage), and the injection of global router instances.
Quick Reference
Plugin Argument (context)
| Property | Type | Description |
|---|---|---|
pinia | Pinia | The root pinia instance |
app | App | The current Vue application instance |
store | Store | The store currently being initialized |
options | Object | The options object passed to defineStore |
pinia-plugin-persistedstate Options
| Option | Default | Purpose |
|---|---|---|
key | store.$id | The key used in storage |
storage | localStorage | Where to save (local, session, etc.) |
paths | undefined | Specific state keys to persist |
serializer | JSON | How to convert state to string |
beforeRestore | undefined | Hook fired before loading from disk |
afterRestore | undefined | Hook fired after loading from disk |
Best Practices
โ Do This:
// Use markRaw when injecting non-reactive objects
store.api = markRaw(apiClient); // โ
// Use 'paths' to avoid persisting sensitive or huge data
persist: { paths: ['themePreference'] } // โ
// Namespace your custom plugin properties to avoid collisions
store._myPlugin_tracker = tracker; // โ
// Define serializers if you use Dates, Maps, or Sets
serializer: { deserialize: v => new Map(JSON.parse(v)) } // โ
โ Don’t Do This:
// Directly modify state in a plugin without $patch (breaks devtools)
store.state.value = { ... }; // โ
// Persist massive objects (e.g., image blobs) to localStorage
persist: { paths: ['hugeBinaryData'] } // โ
// Call store actions inside the plugin function directly
// (Wait for the store to be initialized) // โ
// Overwrite standard Pinia methods like $reset
store.$reset = () => { ... }; // โ
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Serialization Error | JSON.stringify fails on circular refs or BigInt | Use a custom serializer in persist options |
| Hydration Mismatch | Server and Client state differ during SSR | Use the afterRestore hook or client-only flags |
| Performance Lag | Persisting large state on every mutation | Use paths or a throttled custom plugin |
| Missing Reactive Props | Returning a non-ref from a plugin | Ensure reactive properties use ref() or reactive() |
| Key Collisions | Two stores using the same persistence key | Always define a unique key in persist options |
Real-World Examples
1. Injected API Client
pinia.use(({ store }) => { store.$api = markRaw(myApiClient); });
2. Global Undo/Redo
pinia.use(({ store }) => { store.$subscribe((m, s) => history.push(s)); });
3. Session-only Persistence
persist: { storage: sessionStorage }
4. Persisting only the User ID
persist: { paths: ['user.id'] }
5. Router Injection
pinia.use(({ store }) => { store.router = markRaw(router); });
6. Analytics Action Tracker
store.$onAction(({ name }) => trackEvent(name));
7. Development-only Logger
if (process.env.NODE_ENV === 'development') pinia.use(logger);
8. Custom Key for Versioning
persist: { key: 'app-state-v1' }
9. Remote Sync Plugin
store.$subscribe((m, state) => sendToBackend(state));
10. Validating State after Restore
afterRestore: (ctx) => { if(!ctx.store.token) ctx.store.logout(); }
Visual
Plugin Injection Flow
โโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ createPinia() โ โ PLUGIN FUNCTION โ
โโโโโโโโโโโโโโโโโโโโค โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ .use(plugin) โโโโโโถ โ Receive Context: โ
โโโโโโโโโโโโโโโโโโโโ โ { store, options, app } โ
โโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโ
โ
โโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโ
โ AUGMENT STORE โ
โ - Add $api โ
โ - Add $onAction logger โ
โ - Read custom options โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Persistence Sync Loop
โโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโ
โ PINIA STATE โ โ BROWSER โ
โ (RAM) โ โ STORAGE โ
โโโโโโโโฌโโโโโโโโ โโโโโโโโฌโโโโโโโโ
โ โ
MUTATION โโโโ (Sync) โโโโถ WRITE (JSON)
โฒ โ
โ โ
RELOAD/MOUNT โโโ (Hydrate) โโ READ
Serialization Logic
โโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโ
โ Store Obj โ โโโโถ โ Serializer โ โโโโถ โ Disk Str โ
โ (Date) โ โ (ISO String) โ โ "2023..." โ
โโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโ
Summary
| Item | Value |
|---|---|
| Extension Hook | pinia.use() |
| Context Object | store, options, pinia, app |
| Persistence Lib | pinia-plugin-persistedstate |
| Storage Default | localStorage |
| SSR Handling | Requires client-side activation |
| Property Return | Merged into store instance |
| Circular Refs | Handled by custom serializers |
| Global Observation | Use $subscribe / $onAction in plugin |
Key takeaways:
- Plugins are for shared logic. If you find yourself adding the same service or logger to every store, move that logic into a global Pinia plugin to keep your code DRY .
- Persistence is declarative. Using the persistence plugin allows you to simply mark a store as
persist: truewithout worrying about the underlying storage API or race conditions . - Granularity saves performance. Don’t persist your entire state if only one or two keys actually need to survive a refresh. Use the
pathsoption to keep your storage footprint small . - Type safety requires serializers. JSON is a limited format. When persisting complex data types like
Dateor custom classes, always provide a custom serializer to handle the conversion . - Mark external objects as Raw. Always use
markRaw()when injecting things like routers or API clients into your stores to prevent Pinia from wasting CPU cycles making them reactive . - Plugins run on every store. Remember that your plugin function is executed for every
defineStorecall. Use theoptionsobject to conditionally apply logic only to specific stores .
Remember: Pinia Plugins turn your state management from a collection of isolated stores into a unified application framework, and persistence ensures that the user’s experience is continuous across sessions.
Stop using slow, ad-bloated tool sites! ๐คฎ
๐ Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
โ
Finance (Mortgage, Interest, Inflation)
โ
Tech (Base64, JSON, Dev Suite, IP)
โ
Health (BMI, BMR, TDEE)
โ
Productivity (Timer, Workspace, QR)
โก๏ธ Fast & Private
๐ No data leaves your device
๐ 100% Free
๐ Use it now: https://tools.kandz.me
๐ Bookmark itโyouโll need it later!