@erlihs/nuxt-pinia-plugin-storage
v1.0.0
Published
Nuxt plugin for @erlihs/pinia-plugin-storage - A comprehensive Pinia plugin for state persistence with multiple storage adapters
Maintainers
Readme
@erlihs/nuxt-pinia-plugin-storage
Nuxt module for @erlihs/pinia-plugin-storage - A comprehensive Pinia plugin for state persistence with multiple storage adapters.
Features
- 🍍 Full Pinia Integration: Seamlessly works with Pinia stores in Nuxt
- 🔄 Multiple Storage Adapters: localStorage, sessionStorage, cookies, and indexedDB
- 🎯 Selective Persistence: Include/exclude specific state properties
- 📦 Multiple Buckets: Different parts of state can use different storage adapters
- ⚡ Automatic Hydration: Restores state from storage on app initialization
- 🔄 Real-time Synchronization: Syncs state changes across browser tabs/windows
- ⚡ Performance Optimized: Configurable debouncing and throttling
- 🏷️ Namespace & Versioning: Prevents storage key collisions and supports data migration
- 🔀 State Transformation: Before/after hooks for data transformation during hydration
- 🚀 SSR Safe: Server-side rendering compatible with environment detection
- 🛡️ Error Handling: Comprehensive error handling with custom error callbacks
Quick Setup
Install the module to your Nuxt application with one command:
npx nuxi module add @erlihs/nuxt-pinia-plugin-storageOr manually install:
npm install @erlihs/nuxt-pinia-plugin-storageAdd the module to nuxt.config.ts:
export default defineNuxtConfig({
modules: [
'@pinia/nuxt',
'@erlihs/nuxt-pinia-plugin-storage'
],
piniaPluginStorage: {
// Global configuration options
namespace: 'my-app',
version: '1.0.0'
}
})Usage
Basic Usage
// stores/counter.ts
export const useCounterStore = defineStore('counter', () => {
const count = ref(0)
const increment = () => {
count.value++
}
return { count, increment }
}, {
// Enable localStorage persistence
storage: 'localStorage'
})Advanced Usage with Multiple Buckets
// stores/user.ts
export const useUserStore = defineStore('user', () => {
const user = ref({ id: null, name: '', email: '' })
const preferences = ref({ theme: 'light', language: 'en' })
const sessionData = ref({ loginTime: null, lastActivity: null })
return { user, preferences, sessionData }
}, {
storage: {
buckets: [
{
// Persist user data in localStorage
adapter: 'localStorage',
include: ['user'],
key: 'user-data'
},
{
// Persist preferences in cookies (for cross-device sync)
adapter: 'cookies',
include: ['preferences'],
key: 'user-prefs',
options: {
maxAgeSeconds: 60 * 60 * 24 * 30 // 30 days
}
},
{
// Persist session data in sessionStorage
adapter: 'sessionStorage',
include: ['sessionData'],
key: 'session'
}
]
}
})Using with IndexedDB
// stores/documents.ts
export const useDocumentStore = defineStore('documents', () => {
const documents = ref([])
const cache = ref({})
return { documents, cache }
}, {
storage: {
adapter: 'indexedDB',
options: {
dbName: 'MyAppDB',
storeName: 'documents',
dbVersion: 1
},
// Debounce writes for better performance
debounceDelayMs: 1000
}
})Configuration
Module Options
Configure the module in your nuxt.config.ts:
export default defineNuxtConfig({
piniaPluginStorage: {
// Global namespace (prevents conflicts with other apps)
namespace: 'my-app',
// Schema version for data migration
version: '1.0.0',
// Global debounce delay
debounceDelayMs: 300,
// Global throttle delay
throttleDelayMs: 1000,
// Global error handler
onError: (error, ctx) => {
console.error('Storage error:', error, ctx)
}
}
})Store Configuration
Each store can have its own storage configuration:
export const useMyStore = defineStore('myStore', () => {
// Your store logic
}, {
storage: {
// Single adapter (simple)
adapter: 'localStorage'
}
// OR multiple buckets (advanced)
storage: {
namespace: 'store-specific',
version: '2.0.0',
buckets: [
{
adapter: 'localStorage',
include: ['someData'],
key: 'my-data',
debounceDelayMs: 500
},
{
adapter: 'cookies',
include: ['userPrefs'],
options: {
secure: true,
sameSite: 'Strict'
}
}
]
}
})Storage Adapters
localStorage / sessionStorage
storage: {
adapter: 'localStorage' // or 'sessionStorage'
}Cookies
storage: {
adapter: 'cookies',
options: {
path: '/',
domain: '.example.com',
secure: true,
sameSite: 'Strict',
maxAgeSeconds: 86400, // 1 day
httpOnly: false
}
}IndexedDB
storage: {
adapter: 'indexedDB',
options: {
dbName: 'MyDatabase',
storeName: 'MyStore',
dbVersion: 1
}
}API Reference
The module re-exports all types and utilities from @erlihs/pinia-plugin-storage:
import type {
StorageOptions,
Bucket,
GlobalStorageOptions
} from '@erlihs/nuxt-pinia-plugin-storage'
import {
updateStorage,
PLUGIN_VERSION
} from '@erlihs/nuxt-pinia-plugin-storage'Manual Storage Updates
You can manually trigger storage updates:
// In a component or composable
import { updateStorage } from '@erlihs/nuxt-pinia-plugin-storage'
const store = useMyStore()
// Update storage for a specific bucket
await updateStorage({
adapter: 'localStorage',
key: 'manual-save'
}, store)Development
# Install dependencies
npm install
# Generate type stubs
npm run dev:prepare
# Develop with the playground
npm run dev
# Build the module
npm run build
# Run ESLint
npm run lint
# Run Vitest
npm run test
npm run test:watch
# Release new version
npm run releaseContributing
Contributions are welcome! Please read the contributing guidelines before submitting PRs.
Credits
This Nuxt module is a wrapper around @erlihs/pinia-plugin-storage.
License
MIT License © 2024 Jānis Erlihs
