Convert Figma logo to code with AI

robinvdvleuten logovuex-persistedstate

💾 Persist and rehydrate your Vuex state between page reloads.

5,763
379
5,763
27

Top Related Projects

28,431

🗃️ Centralized State Management for Vue.js.

A Vuex plugin to persist the store. (Fully Typescript enabled)

💾 Offline storage, improved. Wraps IndexedDB, WebSQL, or localStorage using a simple but powerful API.

Quick Overview

Vuex-persistedstate is a plugin for Vuex, the state management library for Vue.js applications. It allows you to persist and rehydrate your Vuex store, saving the state to localStorage, sessionStorage, or a custom storage solution. This enables your Vue.js application to maintain its state across page reloads or browser sessions.

Pros

  • Easy integration with existing Vuex stores
  • Flexible configuration options for customizing storage behavior
  • Support for multiple storage backends (localStorage, sessionStorage, custom)
  • Automatic state rehydration on page load

Cons

  • Potential performance impact when persisting large amounts of data
  • Security concerns when storing sensitive information in client-side storage
  • May require additional configuration for complex state structures
  • Limited built-in encryption options for stored data

Code Examples

  1. Basic usage with default options:
import createPersistedState from 'vuex-persistedstate'

const store = new Vuex.Store({
  // ... your store options ...
  plugins: [createPersistedState()]
})
  1. Custom storage path and storage type:
import createPersistedState from 'vuex-persistedstate'
import * as Cookies from 'js-cookie'

const store = new Vuex.Store({
  // ... your store options ...
  plugins: [
    createPersistedState({
      key: 'my-app-state',
      paths: ['auth', 'user'],
      storage: {
        getItem: key => Cookies.get(key),
        setItem: (key, value) => Cookies.set(key, value, { expires: 3, secure: true }),
        removeItem: key => Cookies.remove(key)
      }
    })
  ]
})
  1. Custom serializer and deserializer:
import createPersistedState from 'vuex-persistedstate'

const store = new Vuex.Store({
  // ... your store options ...
  plugins: [
    createPersistedState({
      serialize: state => btoa(JSON.stringify(state)),
      deserialize: state => JSON.parse(atob(state))
    })
  ]
})

Getting Started

  1. Install the package:

    npm install vuex-persistedstate
    
  2. Import and add the plugin to your Vuex store:

    import createPersistedState from 'vuex-persistedstate'
    import { createStore } from 'vuex'
    
    const store = createStore({
      // ... your store options ...
      plugins: [createPersistedState()]
    })
    
  3. (Optional) Configure the plugin with custom options:

    createPersistedState({
      key: 'my-app-state',
      paths: ['auth', 'user'],
      storage: window.sessionStorage
    })
    

Competitor Comparisons

28,431

🗃️ Centralized State Management for Vue.js.

Pros of Vuex

  • Official state management solution for Vue.js, ensuring compatibility and long-term support
  • Provides a comprehensive ecosystem with devtools, plugins, and extensive documentation
  • Offers advanced features like modules, namespacing, and strict mode for complex applications

Cons of Vuex

  • Requires more boilerplate code for setup and implementation
  • Can be overkill for small to medium-sized applications with simple state management needs
  • Doesn't provide built-in persistence functionality, requiring additional configuration

Code Comparison

Vuex (basic store setup):

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: { /* ... */ },
  mutations: { /* ... */ },
  actions: { /* ... */ }
})

vuex-persistedstate (adding persistence to Vuex):

import createPersistedState from 'vuex-persistedstate'

export default new Vuex.Store({
  // ... other store options
  plugins: [createPersistedState()]
})

While Vuex provides a robust state management solution, vuex-persistedstate offers a simple way to add persistence to Vuex stores without additional configuration. The choice between the two depends on the specific needs of the project, with Vuex being more suitable for larger, complex applications and vuex-persistedstate being a useful addon for projects requiring easy state persistence.

A Vuex plugin to persist the store. (Fully Typescript enabled)

Pros of vuex-persist

  • More flexible storage options, including custom storage engines
  • Better TypeScript support with full type definitions
  • Supports selective persistence of state modules

Cons of vuex-persist

  • Slightly more complex setup process
  • Less actively maintained (fewer recent updates)
  • May have a slightly larger bundle size

Code Comparison

vuex-persist:

import VuexPersistence from 'vuex-persist'

const vuexLocal = new VuexPersistence({
  storage: window.localStorage,
  modules: ['user', 'cart']
})

export default new Vuex.Store({
  plugins: [vuexLocal.plugin]
})

vuex-persistedstate:

import createPersistedState from 'vuex-persistedstate'

export default new Vuex.Store({
  plugins: [createPersistedState({
    paths: ['user', 'cart']
  })]
})

Both libraries serve the same primary purpose of persisting Vuex state, but vuex-persist offers more flexibility and better TypeScript support. However, vuex-persistedstate has a simpler setup process and is more actively maintained. The code comparison shows that vuex-persist requires slightly more configuration, while vuex-persistedstate has a more straightforward implementation. Choose based on your specific needs for flexibility, TypeScript support, and ease of use.

💾 Offline storage, improved. Wraps IndexedDB, WebSQL, or localStorage using a simple but powerful API.

Pros of localForage

  • More versatile: Can be used in various JavaScript environments, not limited to Vue.js applications
  • Supports multiple storage backends: IndexedDB, WebSQL, and localStorage
  • Provides a simple, localStorage-like API for complex storage operations

Cons of localForage

  • Requires more setup and configuration for use with Vuex
  • Not specifically designed for Vuex state persistence
  • May require additional code to integrate with Vuex store

Code Comparison

vuex-persistedstate:

import createPersistedState from 'vuex-persistedstate'

const store = new Vuex.Store({
  plugins: [createPersistedState()]
})

localForage:

import localForage from 'localforage'

localForage.setItem('key', 'value').then(() => {
  console.log('Value stored')
})

While vuex-persistedstate is designed to work seamlessly with Vuex, localForage requires additional implementation to achieve the same state persistence functionality. However, localForage offers more flexibility in terms of storage options and can be used in a wider range of applications beyond Vue.js.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

vuex-persistedstate

Persist and rehydrate your Vuex state between page reloads.


🚨 Not maintained anymore! As I don't use Vue in my day to day work, it becomes very hard to stay up to date with any changes with things like Vuex, Nuxt.js and other tools used by the community. That's why I decided to stop spending my spare time to this repository. Feel free to reach out if you would like to take over ownership of the package on NPM. Thank you for any contribution any of you had made to this project 🙏.


Build Status NPM version NPM downloads Prettier MIT license

PRs Welcome Code Of Conduct

Sponsored by The Webstronauts

Install

npm install --save vuex-persistedstate

The UMD build is also available on unpkg:

<script src="https://unpkg.com/vuex-persistedstate/dist/vuex-persistedstate.umd.js"></script>

You can find the library on window.createPersistedState.

Usage

import { createStore } from "vuex";
import createPersistedState from "vuex-persistedstate";

const store = createStore({
  // ...
  plugins: [createPersistedState()],
});

For usage with for Vuex 3 and Vue 2, please see 3.x.x branch.

Examples

Check out a basic example on CodeSandbox.

Edit vuex-persistedstate

Or configured to use with js-cookie.

Edit vuex-persistedstate with js-cookie

Or configured to use with secure-ls

Edit vuex-persistedstate with secure-ls (encrypted data)

Example with Vuex modules

New plugin instances can be created in separate files, but must be imported and added to plugins object in the main Vuex file.

/* module.js */
export const dataStore = {
  state: {
    data: []
  }
}

/* store.js */
import { dataStore } from './module'

const dataState = createPersistedState({
  paths: ['data']
})

export new Vuex.Store({
  modules: {
    dataStore
  },
  plugins: [dataState]
})

Example with Nuxt.js

It is possible to use vuex-persistedstate with Nuxt.js. It must be included as a NuxtJS plugin:

With local storage (client-side only)

// nuxt.config.js

...
/*
 * Naming your plugin 'xxx.client.js' will make it execute only on the client-side.
 * https://nuxtjs.org/guide/plugins/#name-conventional-plugin
 */
plugins: [{ src: '~/plugins/persistedState.client.js' }]
...
// ~/plugins/persistedState.client.js

import createPersistedState from 'vuex-persistedstate'

export default ({store}) => {
  createPersistedState({
    key: 'yourkey',
    paths: [...]
    ...
  })(store)
}

Using cookies (universal client + server-side)

Add cookie and js-cookie:

npm install --save cookie js-cookie or yarn add cookie js-cookie

// nuxt.config.js
...
plugins: [{ src: '~/plugins/persistedState.js'}]
...
// ~/plugins/persistedState.js

import createPersistedState from 'vuex-persistedstate';
import * as Cookies from 'js-cookie';
import cookie from 'cookie';

export default ({ store, req }) => {
    createPersistedState({
        paths: [...],
        storage: {
            getItem: (key) => {
                // See https://nuxtjs.org/guide/plugins/#using-process-flags
                if (process.server) {
                    const parsedCookies = cookie.parse(req.headers.cookie);
                    return parsedCookies[key];
                } else {
                    return Cookies.get(key);
                }
            },
            // Please see https://github.com/js-cookie/js-cookie#json, on how to handle JSON.
            setItem: (key, value) =>
                Cookies.set(key, value, { expires: 365, secure: false }),
            removeItem: key => Cookies.remove(key)
        }
    })(store);
};

API

createPersistedState([options])

Creates a new instance of the plugin with the given options. The following options can be provided to configure the plugin for your specific needs:

  • key <String>: The key to store the persisted state under. Defaults to vuex.

  • paths <Array>: An array of any paths to partially persist the state. If no paths are given, the complete state is persisted. If an empty array is given, no state is persisted. Paths must be specified using dot notation. If using modules, include the module name. eg: "auth.user" Defaults to undefined.

  • reducer <Function>: A function that will be called to reduce the state to persist based on the given paths. Defaults to include the values.

  • subscriber <Function>: A function called to setup mutation subscription. Defaults to store => handler => store.subscribe(handler).

  • storage <Object>: Instead of (or in combination with) getState and setState. Defaults to localStorage.

  • getState <Function>: A function that will be called to rehydrate a previously persisted state. Defaults to using storage.

  • setState <Function>: A function that will be called to persist the given state. Defaults to using storage.

  • filter <Function>: A function that will be called to filter any mutations which will trigger setState on storage eventually. Defaults to () => true.

  • overwrite <Boolean>: When rehydrating, whether to overwrite the existing state with the output from getState directly, instead of merging the two objects with deepmerge. Defaults to false.

  • arrayMerger <Function>: A function for merging arrays when rehydrating state. Defaults to function (store, saved) { return saved } (saved state replaces supplied state).

  • rehydrated <Function>: A function that will be called when the rehydration is finished. Useful when you are using Nuxt.js, which the rehydration of the persisted state happens asynchronously. Defaults to store => {}

  • fetchBeforeUse <Boolean>: A boolean indicating if the state should be fetched from storage before the plugin is used. Defaults to false.

  • assertStorage <Function>: An overridable function to ensure storage is available, fired on plugins's initialization. Default one is performing a Write-Delete operation on the given Storage instance. Note, default behaviour could throw an error (like DOMException: QuotaExceededError).

Customize Storage

If it's not ideal to have the state of the Vuex store inside localstorage. One can easily implement the functionality to use cookies for that (or any other you can think of);

Edit vuex-persistedstate with js-cookie

import { Store } from "vuex";
import createPersistedState from "vuex-persistedstate";
import * as Cookies from "js-cookie";

const store = new Store({
  // ...
  plugins: [
    createPersistedState({
      storage: {
        getItem: (key) => Cookies.get(key),
        // Please see https://github.com/js-cookie/js-cookie#json, on how to handle JSON.
        setItem: (key, value) =>
          Cookies.set(key, value, { expires: 3, secure: true }),
        removeItem: (key) => Cookies.remove(key),
      },
    }),
  ],
});

In fact, any object following the Storage protocol (getItem, setItem, removeItem, etc) could be passed:

createPersistedState({ storage: window.sessionStorage });

This is especially useful when you are using this plugin in combination with server-side rendering, where one could pass an instance of dom-storage.

🔐Obfuscate Local Storage

If you need to use Local Storage (or you want to) but want to prevent attackers from easily inspecting the stored data, you can obfuscate it.

Important ⚠️ Obfuscating the Vuex store means to prevent attackers from easily gaining access to the data. This is not a secure way of storing sensitive data (like passwords, personal information, etc.), and always needs to be used in conjunction with some other authentication method of keeping the data (such as Firebase or your own server).

Edit vuex-persistedstate with secure-ls (obfuscated data)

import { Store } from "vuex";
import createPersistedState from "vuex-persistedstate";
import SecureLS from "secure-ls";
var ls = new SecureLS({ isCompression: false });

// https://github.com/softvar/secure-ls

const store = new Store({
  // ...
  plugins: [
    createPersistedState({
      storage: {
        getItem: (key) => ls.get(key),
        setItem: (key, value) => ls.set(key, value),
        removeItem: (key) => ls.remove(key),
      },
    }),
  ],
});

⚠️ LocalForage ⚠️

As it maybe seems at first sight, it's not possible to pass a LocalForage instance as storage property. This is due the fact that all getters and setters must be synchronous and LocalForage's methods are asynchronous.

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributors ✨

Thanks goes to these wonderful people (emoji key):


Robin van der Vleuten

💻 📖 🚇 ⚠️

Sebastian

💻 📖

Boris Graeff

💻

Cícero Pablo

📖

Gurpreet Atwal

⚠️

Jakub Koralewski

💻

Jankees van Woezik

📖

Jofferson Ramirez Tiquez

📖

Jordan Deprez

📖

Juan Villegas

📖

Jürg Rast

💻

Kartashov Alexey

💻

Leonard Pauli

💻 📖

Nelson Liu

💻 📖 ⚠️

Nico

💻 ⚠️

Quentin Dreyer

💻

Raphael Saunier

💻

Rodney Rehm

💻 ⚠️

Ryan Wang

💻 📖 ⚠️

Sébastien Chopin

📖

jeffjing

💻

macarthuror

📖

Paul Melero

📖 💻 ⚠️

Guillaume da Silva

💻

Jonathan Santerre

💻

Fábio Santos

📖

robertgr991

💻

JurijsKolesnikovs

📖

David Bond

📖

Freek van Rijt

📖

Ilyes Hermellin

💻

Peter Siska

📖

Dmitry Filippov

📖

Thomas Meitz

📖 ⚠️

Neeron Bhatta

📖

joaoaraujo-hotmart

💻

This project follows the all-contributors specification. Contributions of any kind welcome!

License

The MIT License (MIT). Please see License File for more information.

NPM DownloadsLast 30 Days