Skip to content

Nuxt module for @erlihs/pinia-plugin-storage - A comprehensive Pinia plugin for state persistence with multiple storage adapters.

License

Notifications You must be signed in to change notification settings

erlihs/nuxt-pinia-plugin-storage

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

2 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

@erlihs/nuxt-pinia-plugin-storage

npm version npm downloads License Nuxt

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-storage

Or manually install:

npm install @erlihs/nuxt-pinia-plugin-storage

Add 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 release

Contributing

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

About

Nuxt module for @erlihs/pinia-plugin-storage - A comprehensive Pinia plugin for state persistence with multiple storage adapters.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published