• This repository has been archived on 04/Feb/2022
  • Stars
    star
    5,763
  • Rank 7,053 (Top 0.2 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created about 8 years ago
  • Updated almost 3 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

๐Ÿ’พ Persist and rehydrate your Vuex state between page reloads.

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.

More Repositories

1

php-ulid

A PHP port of alizain/ulid with some minor improvements.
PHP
441
star
2

shvl

๐Ÿšง Get and set dot-notated properties within an object.
JavaScript
73
star
3

php-nntp

Client for communicating with servers throught the Network News Transfer Protocol (NNTP) protocol.
PHP
38
star
4

gingerbread

๐Ÿ“ A wrapper around Ginger proofreader for correcting spelling and grammar mistakes based on the context of complete sentences.
JavaScript
34
star
5

preact-cli-plugin-env-vars

๐Ÿ›  Consume variables in your environment with the Preact CLI.
JavaScript
34
star
6

chronicle

Tiny observable & high-performance state management.
JavaScript
21
star
7

vue-auth0-vuex

Simple authentication flow setup in Vue with Auth0 and Vuex.
JavaScript
13
star
8

node-nntp

Client for communicating with servers throught the Network News Transfer Protocol (NNTP) protocol.
JavaScript
10
star
9

preact-cli-plugin-graphql

๐Ÿ›  Preprocess GraphQL queries with the Preact CLI.
JavaScript
9
star
10

guzzle-clients

Contains the configuration for multiple APIs in Guzzle.
PHP
6
star
11

hapi-ember-fastboot

Ember Fastboot handler for hapi.js.
JavaScript
4
star
12

react-todo-workshop

โ›ฑ Sandbox project for one of my React workshops
HTML
3
star
13

gigya-toolkit

๐Ÿ“ฆ A CLI toolkit to create your Gigya screensets with React.
JavaScript
3
star
14

preact-cli-plugin-styled-components

๐Ÿ’… Adds the styled-components Babel plugin to Preact CLI.
JavaScript
3
star
15

observable-fetch

๐Ÿ”‹ RxJS Observable wrapped around the WHATWG Fetch API.
JavaScript
3
star
16

addressing

Addressing library powered by CLDR and Google's address data
Ruby
3
star
17

guzzle-ews

EWS Exchange client based on Guzzle
PHP
3
star
18

beancount

Go
2
star
19

dotfiles

โš™๏ธ Public repo for my personal dotfiles
Shell
2
star
20

json-from-script

๐Ÿ‘ฎ๐Ÿป Tiny JSON parser for your CSP aware script tags.
JavaScript
2
star
21

react-auth0-redux

Simple authentication flow setup in React with Auth0 and Redux.
JavaScript
2
star
22

php-lazy-event-dispatcher

๐Ÿ˜ด An event dispatcher that holds any events until flushed.
PHP
1
star
23

postcss-camelize

PostCSS plugin for camelizing strings.
JavaScript
1
star
24

hippalus

โš“๏ธ [WIP] Tiny router to navigate through browser apps.
JavaScript
1
star
25

react-whatever

๐Ÿคทโ€โ™‚๏ธ Higher-order component to render whatever it gets passed.
JavaScript
1
star
26

redirect-now

Middleware to redirect aliased Now deployments.
JavaScript
1
star
27

react-rxjs-workshop

๐Ÿ Sandbox project for one of my React workshops
JavaScript
1
star
28

hhmm

Convert a digit time string to milliseconds: '22:17' โ†’ 80220000
JavaScript
1
star
29

ns-journey-planner

JavaScript
1
star
30

dsmr

A parser for DSMR telegram data in Go
Go
1
star
31

react-nntp

Network News Transfer Protocol (NNTP) bindings for React.
PHP
1
star