Nuxt, Vuex data clears on browser refresh

Viewed 2979

I have an app using Nuxt on the front-end. Since Nuxt is a SSR technology the data in vuex stores gets deleted after refreshing the browser. Is there a way to save and keep vuex data in browser storage (preferably not cookies) even after refreshing the browser?

3 Answers

We use vuex-persist to save some store information in indexDB to provide offline feature (PWA) but you can use localstorage and cookies as well. Its pretty forward to use and also have an nuxt implementation:

// Inside - nuxt.config.js
export default {
  plugins: [
    { src: '~/plugins/vuex-persist', ssr: false }
  ]
}
// ~/plugins/vuex-persist.js
import VuexPersistence from 'vuex-persist'

export default ({ store }) => {
  new VuexPersistence({
  /* your options */
    key: 'vuex', // The key to store the state on in the storage provider.
    storage: window.localStorage, // or window.sessionStorage or localForage 
  }).plugin(store);
}

You cannot save your Vuex state without any kind of browser storage. Depending on what you need to store, you could use:

  • localStorage if it's some small information, some setting or alike
  • make an API call to your backend and repopulate your Vuex store accordingly (best solution, especially if you stored some JWT token in your localStorage)
  • IndexedDB API, never used it but it's some kind of light database

Still, storing your whole Vuex state is not a thing to do in the browser for various reasons (security, performance, principle etc...).

In Addition to kissu's answer. You can use replaceState to restore a saved state.

But you probably shouldn't, you can create a bug that your user can't get out of by refreshing. And that's really frustrating.

The pattern to do this is fairly simple.

First, in vuex, subscribe to all mutations

https://vuex.vuejs.org/api/#subscribe

const unsubscribe = store.subscribe((mutation, state) => {
  console.log(mutation.type)
  console.log(mutation.payload)
})

// you may call unsubscribe to stop the subscription
unsubscribe()

Check which mutations you are interested in saving and store them in localStorage, or IndexDb or whatever you want.

On page load you need to check your storage solution for this data. If it exists. call replaceState https://vuex.vuejs.org/api/#replacestate

store.replaceState(state: Object) // give it an object structure matching your Vuex module state structure

And this is how you can save and reload state.

Related