for using vuex-persistedstate in nuxt both client and server , follow these steps.
For example consider you have a Vuex Module user and you want to persist it . even if you refresh or route to another page.
const user = {
namespaced: true,
state: () => ({
name: 'geeekfa'
}),
mutations: {
name(state, name) {
state.name = name;
},
},
getters: {
name: (state) => {
return state.name;
},
}
}
export default user
- install vuex-persistedstate
npm install --save vuex-persistedstate
- install cookie & js-cookie
npm install --save cookie js-cookie
after that your package.json is like :
"dependencies": {
...
"cookie": "^0.3.1",
"js-cookie": "^2.2.1",
"vuex-persistedstate": "^4.0.0-beta.3",
...
}
- create
persistedState.js in ~/plugin/persistedState.js
// persistedState.js
import createPersistedState from 'vuex-persistedstate'
import * as Cookies from 'js-cookie'
import cookie from 'cookie'
export default ({ store, req }) => {
createPersistedState({
paths: ['user'], // your vuex module name
storage: {
getItem: (key) => {
if (process.server) {
const parsedCookies = cookie.parse(req.headers.cookie)
return parsedCookies[key]
} else {
return Cookies.get(key)
}
},
setItem: (key, value) =>
Cookies.set(key, value, { expires: 365, secure: false }),
removeItem: key => Cookies.remove(key)
}
})(store)
}
- add this plugin to
nuxt.config.js
plugins: [
...
{ src: '~/plugins/persistedState.js' }
...
],
this is enough ! you can persist user module even after refresh in both client and server side . there is no need to change ~/store/index.js file