vuex-persist2.0.1 • Public • Published
A Typescript-ready Vuex plugin that enables you to save the state of your app to a persisted storage like Cookies or localStorage.
Table of Contents
- Table of Contents
- Unit Testing
- 📦 NEW in v1.5
- distributed as esm and cjs both (via module field of package.json)
- better tree shaking as a result of esm
- 🎗 NEW IN V1.0.0
- Support localForage and other Promise based stores
- Fix late restore of state for localStorage
- Automatically save store on mutation.
- Choose which mutations trigger store save, and which don't, using
- Works perfectly with modules in store
- Ability to save partial store, using a
- Automatically restores store when app loads
- You can create mulitple VuexPersistence instances if you want to -
- Save some parts of the store to localStorage, some to sessionStorage
- Trigger saving to localStorage on data download, saving to cookies on authentication result
Vue CLI Build Setup (using Webpack or some bundler)
npm install --save vuex-persist
yarn add vuex-persist
This module is distributed in 3 formats
- umd build
/dist/umd/index.jsin es5 format
- commonjs build
/dist/cjs/index.jsin es2015 format
- esm build
/dist/esm/index.jsin es2015 format
When using with Webpack (or Vue CLI 3), the esm file gets used by default.
If your project has a
es2015 target, you're good, but if
for backwards compatibility, you are compiling your project to
this module also needs to be transpiled.
To enable transpilation of this module
// in your vue.config.jsmoduleexports =/* ... other config ... */transpileDependencies: 'vuex-persist'
Directly in Browser
<!-- We need lodash.merge so get lodash first -->
Tips for NUXT
This is a plugin that works only on the client side. So we'll register it as a ssr-free plugin.
// Inside - nuxt.config.jsplugins:src: '~/plugins/vuex-persist' ssr: false
NOTE: In browsers, you can directly use
Create an object
const vuexLocal =storage: windowlocalStorage
Use it as Vue plugin. (in typescript)
const store =state: ...mutations: ...actions: ...plugins: vuexLocalplugin
Constructor Parameters -
When creating the VuexPersistence object, we pass an
Here are the properties, and what they mean -
|key||string||The key to store the state in the storage
|storage||Storage (Web API)||localStorage, sessionStorage, localforage or your custom Storage object.
Must implement getItem, setItem, clear etc.
(key, state[, storage])
|If not using storage, this custom function handles
saving state to persistence
(key[, storage]) => state
|If not using storage, this custom function handles
retrieving state from storage
(state) => object
|State reducer. reduces state to only those values you want to save.
By default, saves entire state
(mutation) => boolean
|Mutation filter. Look at
for only those ones which you want a persistence write to be triggered for.
Default returns true for all mutations
|modules||string||List of modules you want to persist. (Do not write your own reducer if you want to use this)|
|asyncStorage||boolean||Denotes if the store uses Promises (like localforage) or not
|supportCircular||boolean||Denotes if the state has any circular references to itself (state.x === state)|
Your reducer should not change the shape of the state.
const persist =stateproducts...
Above code is wrong You intend to do this instead
const persist =products: stateproducts...
If you have circular structures in your state
let x = a: 10xx = xxx === xxx // truexxxa === xxxxa //true
JSON.stringify() will not work.
You'll need to install
npm install flatted
And when constructing the store, add
Quick example -
Here is an example store that has 2 modules,
We are going to save user details into a Cookie (using js-cookie)
And, we will save the navigation state into localStorage whenever
a new item is added to nav items.
So you can use multiple VuexPersistence instances to store different
parts of your Vuex store into different storage providers.
Warning: when working with modules these should be registered in
the Vuex constructor. When using
store.registerModule you risk the
(restored) persisted state being overwritten with the default state
defined in the module itself.
Support Strict Mode
This now supports Vuex strict mode
(Keep in mind, NOT to use strict mode in production)
In strict mode, we cannot use
store.replaceState so instead we use a mutation
You'll need to keep in mind to add the
RESTORE_MUTATION to your mutations
See example below
To configure with strict mode support -
Some of the most popular ways to persist your store would be -
- js-cookie to use browser Cookies
- window.localStorage (remains, across PC reboots, untill you clear browser data)
- window.sessionStorage (vanishes when you close browser tab)
- localForage Uses IndexedDB from the browser
Note on LocalForage and async stores
There is Window.Storage API as defined by HTML5 DOM specs, which implements the following -
As you can see it is an entirely synchronous storage. Also note that it saves only string values. Thus objects are stringified and stored.
Now note the representative interface of Local Forage -
You can note 2 differences here -
- All functions are asynchronous with Promises (because WebSQL and IndexedDB are async)
- It works on objects too (not just strings)
I have made
vuex-persist compatible with both types of storages, but this comes
at a slight cost.
When using asynchronous (promise-based) storages, your state will not be
immediately restored into vuex from localForage. It will go into the event loop
and will finish when the JS thread is empty. This can invoke a delay of few seconds.
Issue #15 of this repository explains
what you can do to find out when store has restored.
When testing with Jest, you might find this error -
TypeError: Cannot read property 'getItem' of undefined
This is because there is no localStorage in Jest. You can add the following Jest plugins to solve this https://www.npmjs.com/package/jest-localstorage-mock